answer stringlengths 17 10.2M |
|---|
package com.github.underscore;
import java.util.*;
import org.junit.Test;
import static java.util.Arrays.asList;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertNull;
/**
* Underscore library unit test.
*
* @author Valentyn Kolesnikov
*/
public class _Test {
/*
_.each([1, 2, 3], alert);
=> alerts each number in turn...
*/
@Test
public void each() {
final List<Integer> result = new ArrayList<Integer>();
_.<Integer>each(asList(1, 2, 3), new Block<Integer>() {
public void apply(Integer item) {
result.add(item);
}
});
assertEquals("[1, 2, 3]", result.toString());
}
/*
_.forEach([1, 2, 3], alert);
=> alerts each number in turn...
*/
@Test
public void forEach() {
final List<Integer> result = new ArrayList<Integer>();
_.forEach(asList(1, 2, 3), new Block<Integer>() {
public void apply(Integer item) {
result.add(item);
}
});
assertEquals("[1, 2, 3]", result.toString());
}
/*
_([1, 2, 3]).forEach(alert);
=> alerts each number in turn...
*/
@Test
public void forEachObj() {
final List<Integer> result = new ArrayList<Integer>();
new _(asList(1, 2, 3)).forEach(new Block<Integer>() {
public void apply(Integer item) {
result.add(item);
}
});
assertEquals("[1, 2, 3]", result.toString());
}
/*
_.each({one: 1, two: 2, three: 3}, alert);
=> alerts each number value in turn...
*/
@Test
public void eachMap() {
final List<String> result = new ArrayList<String>();
_.<Map.Entry<String, Integer>>each(new LinkedHashMap<String, Integer>() {{ put("one", 1); put("two", 2); put("three", 3); }}.entrySet(),
new Block<Map.Entry<String, Integer>>() {
public void apply(Map.Entry<String, Integer> item) {
result.add(item.getKey());
}
});
assertEquals("[one, two, three]", result.toString());
}
/*
_.map([1, 2, 3], function(num){ return num * 3; });
=> [3, 6, 9]
*/
@Test
public void map() {
List<Integer> result = _.map(asList(1, 2, 3), new Function1<Integer, Integer>() {
public Integer apply(Integer item) {
return item * 3;
}
});
assertEquals("[3, 6, 9]", result.toString());
}
/*
_.collect([1, 2, 3], function(num){ return num * 3; });
=> [3, 6, 9]
*/
@Test
public void collect() {
List<Integer> result = _.collect(asList(1, 2, 3), new Function1<Integer, Integer>() {
public Integer apply(Integer item) {
return item * 3;
}
});
assertEquals("[3, 6, 9]", result.toString());
Set<Integer> resultSet = _.collect(new LinkedHashSet(asList(1, 2, 3)), new Function1<Integer, Integer>() {
public Integer apply(Integer item) {
return item * 3;
}
});
assertEquals("[3, 6, 9]", resultSet.toString());
}
/*
_.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });
=> [3, 6, 9]
*/
@Test
public void mapMap() {
final Set<Integer> result =
_.map(new LinkedHashMap<Integer, String>() {{ put(1, "one"); put(2, "two"); put(3, "three"); }}.entrySet(),
new Function1<Map.Entry<Integer, String>, Integer>() {
public Integer apply(Map.Entry<Integer, String> item) {
return item.getKey() * 3;
}
});
assertEquals("[3, 6, 9]", result.toString());
}
/*
var sum = _.reduce([1, 2, 3], function(memo, num){ return memo + num; }, 0);
=> 6
*/
@Test
public void reduce() {
final Integer result =
_.reduce(asList(1, 2, 3),
new FunctionAccum<Integer, Integer>() {
public Integer apply(Integer item1, Integer item2) {
return item1 + item2;
}
},
0);
assertEquals("6", result.toString());
}
/*
var list = [[0, 1], [2, 3], [4, 5]];
var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []);
=> [4, 5, 2, 3, 0, 1]
*/
@Test
public void reduceRight() {
final List<Integer> result =
_.reduceRight(asList(asList(0, 1), asList(2, 3), asList(4, 5)),
new FunctionAccum<List<Integer>, List<Integer>>() {
public List<Integer> apply(List<Integer> item1, List<Integer> item2) {
List<Integer> list = new ArrayList<Integer>(item1);
list.addAll(item2);
return list;
}
},
Collections.<Integer>emptyList()
);
assertEquals("[4, 5, 2, 3, 0, 1]", result.toString());
}
/*
var list = [[0, 1], [2, 3], [4, 5]];
var flat = _.inject(list, function(a, b) { return a.concat(b); }, []);
=> [0, 1, 2, 3, 4, 5]
*/
@Test
public void inject() {
final List<Integer> result =
_.inject(asList(asList(0, 1), asList(2, 3), asList(4, 5)),
new FunctionAccum<List<Integer>, List<Integer>>() {
public List<Integer> apply(List<Integer> item1, List<Integer> item2) {
List<Integer> list = new ArrayList<Integer>(item1);
list.addAll(item2);
return list;
}
},
Collections.<Integer>emptyList()
);
assertEquals("[0, 1, 2, 3, 4, 5]", result.toString());
}
/*
var list = [[0, 1], [2, 3], [4, 5]];
var flat = _.foldl(list, function(a, b) { return a.concat(b); }, []);
=> [0, 1, 2, 3, 4, 5]
*/
@Test
public void foldl() {
final List<Integer> result =
_.foldl(asList(asList(0, 1), asList(2, 3), asList(4, 5)),
new FunctionAccum<List<Integer>, List<Integer>>() {
public List<Integer> apply(List<Integer> item1, List<Integer> item2) {
List<Integer> list = new ArrayList<Integer>(item1);
list.addAll(item2);
return list;
}
},
Collections.<Integer>emptyList()
);
assertEquals("[0, 1, 2, 3, 4, 5]", result.toString());
}
/*
var list = [[0, 1], [2, 3], [4, 5]];
var flat = _.foldr(list, function(a, b) { return a.concat(b); }, []);
=> [4, 5, 2, 3, 0, 1]
*/
@Test
public void foldr() {
final List<Integer> result =
_.foldr(asList(asList(0, 1), asList(2, 3), asList(4, 5)),
new FunctionAccum<List<Integer>, List<Integer>>() {
public List<Integer> apply(List<Integer> item1, List<Integer> item2) {
List<Integer> list = new ArrayList<Integer>(item1);
list.addAll(item2);
return list;
}
},
Collections.<Integer>emptyList()
);
assertEquals("[4, 5, 2, 3, 0, 1]", result.toString());
}
/*
_.contains([1, 2, 3], 3);
=> true
*/
@Test
public void contains() {
final boolean result = _.contains(asList(1, 2, 3), 3);
assertTrue(result);
}
/*
var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> 2
*/
@Test
public void find() {
final Integer result = _.find(asList(1, 2, 3, 4, 5, 6),
new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals("2", result.toString());
}
/*
var even = _.find([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> 2
*/
@Test
public void detect() {
final Integer result = _.detect(asList(1, 2, 3, 4, 5, 6),
new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals("2", result.toString());
}
/*
var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [2, 4, 6]
*/
@Test
public void filter() {
final List<Integer> result = _.filter(asList(1, 2, 3, 4, 5, 6),
new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals("[2, 4, 6]", result.toString());
}
/*
var evens = _.reject([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [2, 4, 6]
*/
@Test
public void reject() {
final List<Integer> result = _.reject(asList(1, 2, 3, 4, 5, 6),
new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals("[1, 3, 5]", result.toString());
final Set<Integer> resultSet = _.reject(new LinkedHashSet(asList(1, 2, 3, 4, 5, 6)),
new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals("[1, 3, 5]", resultSet.toString());
}
/*
var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [2, 4, 6]
*/
@Test
public void select() {
final List<Integer> result = _.select(asList(1, 2, 3, 4, 5, 6),
new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals("[2, 4, 6]", result.toString());
final Set<Integer> resultSet = _.select(new LinkedHashSet(asList(1, 2, 3, 4, 5, 6)),
new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals("[2, 4, 6]", resultSet.toString());
}
@Test
public void all() {
final Boolean result1 = _.all(asList(1, 2, 3, 4),
new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
final Boolean result2 = _.all(asList(1, 2, 3, 4),
new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item < 5;
}
});
assertFalse(result1);
assertTrue(result2);
}
@Test
public void any() {
final Boolean result1 = _.any(asList(1, 2, 3, 4),
new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
final Boolean result2 = _.any(asList(1, 2, 3, 4),
new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item == 5;
}
});
assertTrue(result1);
assertFalse(result2);
}
/*
_.include([1, 2, 3], 3); // true
*/
@Test
public void include() {
final Boolean result = _.include(asList(1, 2, 3), 3);
assertTrue(result);
}
/*
_.invoke([" foo ", " bar"], "trim"); // ["foo", "bar"]
*/
@Test
public void invoke() throws Exception {
assertEquals(_.invoke(asList(" foo ", " bar"), "trim"), asList("foo", "bar"));
assertEquals(_.invoke(asList("foo", "bar"), "concat", Arrays.<Object>asList("1")), asList("foo1", "bar1"));
}
@Test(expected = IllegalArgumentException.class)
public void invoke2() throws Exception {
_.invoke(asList("foo", 123), "concat", Arrays.<Object>asList("1"));
}
@Test
public void where() {
class Book {
public final String title;
public final String author;
public final Integer year;
public Book(final String title, final String author, final Integer year) {
this.title = title;
this.author = author;
this.year = year;
}
public String toString() {
return "title: " + title + ", author: " + author + ", year: " + year;
}
};
List<Book> listOfPlays =
new ArrayList<Book>() {{
add(new Book("Cymbeline2", "Shakespeare", 1614));
add(new Book("Cymbeline", "Shakespeare", 1611));
add(new Book("The Tempest", "Shakespeare", 1611));
}};
assertEquals("[title: Cymbeline, author: Shakespeare, year: 1611,"
+ " title: The Tempest, author: Shakespeare, year: 1611]",
_.where(listOfPlays, asList(
Tuple.<String, Object>create("author", "Shakespeare"),
Tuple.<String, Object>create("year", Integer.valueOf(1611)))).toString());
assertEquals("[title: Cymbeline, author: Shakespeare, year: 1611,"
+ " title: The Tempest, author: Shakespeare, year: 1611]",
_.where(listOfPlays, asList(
Tuple.<String, Object>create("author", "Shakespeare"),
Tuple.<String, Object>create("author2", "Shakespeare"),
Tuple.<String, Object>create("year", Integer.valueOf(1611)))).toString());
assertEquals("[title: Cymbeline, author: Shakespeare, year: 1611,"
+ " title: The Tempest, author: Shakespeare, year: 1611]",
_.where(new LinkedHashSet<Book>(listOfPlays), asList(
Tuple.<String, Object>create("author", "Shakespeare"),
Tuple.<String, Object>create("year", Integer.valueOf(1611)))).toString());
assertEquals("[title: Cymbeline, author: Shakespeare, year: 1611,"
+ " title: The Tempest, author: Shakespeare, year: 1611]",
_.where(new LinkedHashSet<Book>(listOfPlays), asList(
Tuple.<String, Object>create("author", "Shakespeare"),
Tuple.<String, Object>create("author2", "Shakespeare"),
Tuple.<String, Object>create("year", Integer.valueOf(1611)))).toString());
}
@Test
public void findWhere() {
class Book {
public final String title;
public final String author;
public final Integer year;
public Book(final String title, final String author, final Integer year) {
this.title = title;
this.author = author;
this.year = year;
}
public String toString() {
return "title: " + title + ", author: " + author + ", year: " + year;
}
};
List<Book> listOfPlays =
new ArrayList<Book>() {{
add(new Book("Cymbeline2", "Shakespeare", 1614));
add(new Book("Cymbeline", "Shakespeare", 1611));
add(new Book("The Tempest", "Shakespeare", 1611));
}};
assertEquals("title: Cymbeline, author: Shakespeare, year: 1611",
_.findWhere(listOfPlays, asList(
Tuple.<String, Object>create("author", "Shakespeare"),
Tuple.<String, Object>create("year", Integer.valueOf(1611)))).toString());
assertEquals("title: Cymbeline, author: Shakespeare, year: 1611",
_.findWhere(listOfPlays, asList(
Tuple.<String, Object>create("author", "Shakespeare"),
Tuple.<String, Object>create("author2", "Shakespeare"),
Tuple.<String, Object>create("year", Integer.valueOf(1611)))).toString());
}
/*
_.first([5, 4, 3, 2, 1]);
=> 5
_.first([5, 4, 3, 2, 1], 2);
=> [5, 4]
*/
@Test
public void first() {
final Integer result = _.first(asList(5, 4, 3, 2, 1));
assertEquals("5", result.toString());
final Object resultChain = _.chain(asList(5, 4, 3, 2, 1)).first().item();
assertEquals("5", resultChain.toString());
final Object resultChainTwo = _.chain(asList(5, 4, 3, 2, 1)).first(2).value();
assertEquals("[5, 4]", resultChainTwo.toString());
final List<Integer> resultList = _.first(asList(5, 4, 3, 2, 1), 2);
assertEquals("[5, 4]", resultList.toString());
final int resultInt = _.first(new Integer[] {5, 4, 3, 2, 1});
assertEquals(5, resultInt);
}
/*
_.head([5, 4, 3, 2, 1]);
=> 5
_.head([5, 4, 3, 2, 1], 2);
=> [5, 4]
*/
@Test
public void head() {
final Integer result = _.head(asList(5, 4, 3, 2, 1));
assertEquals("5", result.toString());
final Integer resultObj = new _<Integer>(asList(5, 4, 3, 2, 1)).head();
assertEquals("5", resultObj.toString());
final List<Integer> resultList = _.head(asList(5, 4, 3, 2, 1), 2);
assertEquals("[5, 4]", resultList.toString());
final List<Integer> resultListObj = new _<Integer>(asList(5, 4, 3, 2, 1)).head(2);
assertEquals("[5, 4]", resultListObj.toString());
final int resultInt = _.head(new Integer[] {5, 4, 3, 2, 1});
assertEquals(5, resultInt);
}
/*
_.initial([5, 4, 3, 2, 1]);
=> [5, 4, 3, 2]
_.initial([5, 4, 3, 2, 1], 2);
=> [5, 4, 3]
*/
@Test
public void initial() {
final List<Integer> result = _.initial(asList(5, 4, 3, 2, 1));
assertEquals("[5, 4, 3, 2]", result.toString());
final List<Integer> resultChain = _.chain(asList(5, 4, 3, 2, 1)).initial().value();
assertEquals("[5, 4, 3, 2]", resultChain.toString());
final List<Integer> resultList = _.initial(asList(5, 4, 3, 2, 1), 2);
assertEquals("[5, 4, 3]", resultList.toString());
final List<Integer> resultListChain = _.chain(asList(5, 4, 3, 2, 1)).initial(2).value();
assertEquals("[5, 4, 3]", resultListChain.toString());
final Integer[] resultArray = _.initial(new Integer[] {5, 4, 3, 2, 1});
assertEquals("[5, 4, 3, 2]", asList(resultArray).toString());
final Integer[] resultListArray = _.initial(new Integer[] {5, 4, 3, 2, 1}, 2);
assertEquals("[5, 4, 3]", asList(resultListArray).toString());
}
/*
_.last([5, 4, 3, 2, 1]);
=> 1
*/
@Test
public void last() {
final Integer result = _.last(asList(5, 4, 3, 2, 1));
assertEquals("1", result.toString());
final List<Integer> resultTwo = _.last(asList(5, 4, 3, 2, 1), 2);
assertEquals("[2, 1]", resultTwo.toString());
final Object resultChain = _.chain(asList(5, 4, 3, 2, 1)).last().item();
assertEquals("1", resultChain.toString());
final Object resultChainTwo = _.chain(asList(5, 4, 3, 2, 1)).last(2).value();
assertEquals("[2, 1]", resultChainTwo.toString());
final Integer resultArray = _.last(new Integer[] {5, 4, 3, 2, 1});
assertEquals("1", resultArray.toString());
}
/*
_.tail([5, 4, 3, 2, 1]);
=> [4, 3, 2, 1]
_.tail([5, 4, 3, 2, 1], 2);
=> [3, 2, 1]
*/
@Test
public void tail() {
final List<Integer> result = _.tail(asList(5, 4, 3, 2, 1));
assertEquals("[4, 3, 2, 1]", result.toString());
final List<Integer> result2 = _.tail(asList(5, 4, 3, 2, 1), 2);
assertEquals("[3, 2, 1]", result2.toString());
final Object[] resultArray = _.tail(new Integer[] {5, 4, 3, 2, 1});
assertEquals("[4, 3, 2, 1]", asList(resultArray).toString());
final List<Integer> resultArrayObj = new _<Integer>(asList(5, 4, 3, 2, 1)).tail();
assertEquals("[4, 3, 2, 1]", resultArrayObj.toString());
final Object[] resultArray2 = _.tail(new Integer[] {5, 4, 3, 2, 1}, 2);
assertEquals("[3, 2, 1]", asList(resultArray2).toString());
final List<Integer> resultArray2Obj = new _<Integer>(asList(5, 4, 3, 2, 1)).tail(2);
assertEquals("[3, 2, 1]", resultArray2Obj.toString());
}
/*
_.drop([5, 4, 3, 2, 1]);
=> [4, 3, 2, 1]
_.drop([5, 4, 3, 2, 1], 2);
=> [3, 2, 1]
*/
@Test
public void drop() {
final List<Integer> result = _.drop(asList(5, 4, 3, 2, 1));
assertEquals("[4, 3, 2, 1]", result.toString());
final List<Integer> result2 = _.drop(asList(5, 4, 3, 2, 1), 2);
assertEquals("[3, 2, 1]", result2.toString());
final Object[] resultArray = _.drop(new Integer[] {5, 4, 3, 2, 1});
assertEquals("[4, 3, 2, 1]", asList(resultArray).toString());
final Object[] resultArray2 = _.drop(new Integer[] {5, 4, 3, 2, 1}, 2);
assertEquals("[3, 2, 1]", asList(resultArray2).toString());
}
/*
_.rest([5, 4, 3, 2, 1]);
=> [4, 3, 2, 1]
_.rest([5, 4, 3, 2, 1], 2);
=> [3, 2, 1]
*/
@Test
public void rest() {
final List<Integer> result = _.rest(asList(5, 4, 3, 2, 1));
assertEquals("[4, 3, 2, 1]", result.toString());
final List<Integer> resultChain = _.chain(asList(5, 4, 3, 2, 1)).rest().value();
assertEquals("[4, 3, 2, 1]", resultChain.toString());
final List<Integer> result2 = _.rest(asList(5, 4, 3, 2, 1), 2);
assertEquals("[3, 2, 1]", result2.toString());
final List<Integer> result2Chain = _.chain(asList(5, 4, 3, 2, 1)).rest(2).value();
assertEquals("[3, 2, 1]", result2Chain.toString());
final Object[] resultArray = _.rest(new Integer[] {5, 4, 3, 2, 1});
assertEquals("[4, 3, 2, 1]", asList(resultArray).toString());
final Object[] resultArray2 = _.rest(new Integer[] {5, 4, 3, 2, 1}, 2);
assertEquals("[3, 2, 1]", asList(resultArray2).toString());
}
/*
_.flatten([1, [2], [3, [[4]]]]);
=> [1, 2, 3, 4];
*/
@Test
public void flatten() {
final List<Integer> result = _.flatten(asList(1, asList(2, asList(3, asList(asList(4))))));
assertEquals("[1, 2, 3, 4]", result.toString());
final List<Integer> result2 = _.flatten(asList(1, asList(2, asList(3, asList(asList(4))))), true);
assertEquals("[1, 2, [3, [[4]]]]", result2.toString());
final List<Integer> resultObj = new _(asList(1, asList(2, asList(3, asList(asList(4)))))).flatten();
assertEquals("[1, 2, 3, 4]", resultObj.toString());
final List<Integer> resultObj2 = new _(asList(1, asList(2, asList(3, asList(asList(4)))))).flatten(true);
assertEquals("[1, 2, [3, [[4]]]]", resultObj2.toString());
}
/*
_.compact([0, 1, false, 2, '', 3]);
=> [1, 2, 3]
*/
@Test
public void compact() {
final List<?> result = _.compact(asList(0, 1, false, 2, "", 3));
assertEquals("[1, 2, 3]", result.toString());
final List<?> result2 = _.compact(asList(0, 1, false, 2, "", 3), 1);
assertEquals("[0, false, 2, , 3]", result2.toString());
final List<?> result3 = new _(asList(0, 1, false, 2, "", 3)).compact();
assertEquals("[1, 2, 3]", result3.toString());
final List<?> result4 = new _(asList(0, 1, false, 2, "", 3)).compact(1);
assertEquals("[0, false, 2, , 3]", result4.toString());
final Object[] resultArray = _.compact(new Object[] {0, 1, false, 2, "", 3});
assertEquals("[1, 2, 3]", asList(resultArray).toString());
final Object[] resultArray2 = _.compact(new Object[] {0, 1, false, 2, "", 3}, 1);
assertEquals("[0, false, 2, , 3]", asList(resultArray2).toString());
}
/*
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
=> [2, 3, 4]
*/
@Test
public void without() {
final List<Integer> result = _.without(asList(1, 2, 1, 0, 3, 1, 4), 0, 1);
assertEquals("[2, 3, 4]", result.toString());
final List<Integer> result2 = _.without(asList(1, 2, 1, 0, 3, 1, 4), 1);
assertEquals("[2, 0, 3, 4]", result2.toString());
final Object[] resultArray = _.without(new Integer[] {1, 2, 1, 0, 3, 1, 4}, 0, 1);
assertEquals("[2, 3, 4]", asList(resultArray).toString());
final Object[] resultArray2 = _.without(new Integer[] {1, 2, 1, 0, 3, 1, 4}, 1);
assertEquals("[2, 0, 3, 4]", asList(resultArray2).toString());
}
/*
var numbers = [10, 5, 100, 2, 1000];
_.max(numbers);
=> 1000
*/
@Test
public void max() {
final Integer result = _.max(asList(10, 5, 100, 2, 1000));
assertEquals("1000", result.toString());
final Integer resultComp = _.max(asList(10, 5, 100, 2, 1000),
new Function1<Integer, Integer>() {
public Integer apply(Integer item) {
return -item;
}
});
assertEquals("2", resultComp.toString());
class Person {
public final String name;
public final Integer age;
public Person(final String name, final Integer age) {
this.name = name;
this.age = age;
}
};
final Person resultPerson = _.max(asList(new Person("moe", 40), new Person("larry", 50), new Person("curly", 60)),
new Function1<Person, Integer>() {
public Integer apply(Person item) {
return item.age;
}
});
assertEquals("curly", resultPerson.name);
assertEquals(60, resultPerson.age);
}
/*
var numbers = [10, 5, 100, 2, 1000];
_.min(numbers);
=> 2
*/
@Test
public void min() {
final Integer result = _.min(asList(10, 5, 100, 2, 1000));
assertEquals("2", result.toString());
final Integer resultComp = _.min(asList(10, 5, 100, 2, 1000),
new Function1<Integer, Integer>() {
public Integer apply(Integer item) {
return -item;
}
});
assertEquals("1000", resultComp.toString());
class Person {
public final String name;
public final Integer age;
public Person(final String name, final Integer age) {
this.name = name;
this.age = age;
}
};
final Person resultPerson = _.min(asList(new Person("moe", 40), new Person("larry", 50), new Person("curly", 60)),
new Function1<Person, Integer>() {
public Integer apply(Person item) {
return item.age;
}
});
assertEquals("moe", resultPerson.name);
assertEquals(40, resultPerson.age);
}
/*
_.shuffle([1, 2, 3, 4, 5, 6]);
=> [4, 1, 6, 3, 5, 2]
*/
@Test
public void shuffle() {
final List<Integer> result = _.shuffle(asList(1, 2, 3, 4, 5, 6));
assertEquals(6, result.size());
}
/*
_.sample([1, 2, 3, 4, 5, 6]);
=> 4
_.sample([1, 2, 3, 4, 5, 6], 3);
=> [1, 6, 2]
*/
@Test
public void sample() {
final Integer result = _.sample(asList(1, 2, 3, 4, 5, 6));
assertTrue(result >= 1 && result <= 6);
final Set<Integer> resultList = _.sample(asList(1, 2, 3, 4, 5, 6), 3);
assertEquals(3, resultList.size());
}
/*
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.pluck(stooges, 'name');
=> ["moe", "larry", "curly"]
*/
@Test
public void pluck() throws Exception {
class Person {
public final String name;
public final Integer age;
public Person(final String name, final Integer age) {
this.name = name;
this.age = age;
}
};
final List<?> resultEmpty =
_.pluck(asList(), "name");
assertEquals("[]", resultEmpty.toString());
final List<?> result =
_.pluck(asList(new Person("moe", 40), new Person("larry", 50), new Person("curly", 40)), "name");
assertEquals("[moe, larry, curly]", result.toString());
final Set<?> resultEmpty2 =
_.pluck(new LinkedHashSet(asList()), "name");
assertEquals("[]", resultEmpty2.toString());
final Set<?> resultSet =
_.pluck(new LinkedHashSet(asList(new Person("moe", 40), new Person("larry", 50), new Person("curly", 40))), "name");
assertEquals("[moe, larry, curly]", resultSet.toString());
}
@Test(expected = IllegalArgumentException.class)
public void pluck2() throws Exception {
class Person {
public final String name;
public final Integer age;
public Person(final String name, final Integer age) {
this.name = name;
this.age = age;
}
};
_.pluck(asList(new Person("moe", 40), new Person("larry", 50), new Person("curly", 40)), "name2");
}
@Test(expected = IllegalArgumentException.class)
public void pluck3() throws Exception {
class Person {
public final String name;
public final Integer age;
public Person(final String name, final Integer age) {
this.name = name;
this.age = age;
}
};
_.pluck(new LinkedHashSet(asList(new Person("moe", 40), new Person("larry", 50), new Person("curly", 40))), "name2");
}
/*
_.sortBy([1, 2, 3, 4, 5, 6], function(num){ return Math.sin(num); });
=> [5, 4, 6, 3, 1, 2]
*/
@Test
public void sortBy() throws Exception {
final List<Integer> result =
_.sortBy(asList(1, 2, 3, 4, 5, 6),
new Function1<Integer, Integer>() {
public Integer apply(Integer item) {
return Double.valueOf(Math.sin(item) * 1000).intValue();
}
});
assertEquals("[5, 4, 6, 3, 1, 2]", result.toString());
}
/*
_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
=> {1: [1.3], 2: [2.1, 2.4]}
*/
@Test
public void groupBy() throws Exception {
final Map<Double, List<Double>> result =
_.groupBy(asList(1.3, 2.1, 2.4),
new Function1<Double, Double>() {
public Double apply(Double num) {
return Math.floor(num);
}
});
assertEquals("{1.0=[1.3], 2.0=[2.1, 2.4]}", result.toString());
}
/*
var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.indexBy(stooges, 'age');
=> {
"40": {name: 'moe', age: 40},
"50": {name: 'larry', age: 50},
"60": {name: 'curly', age: 60}
}
*/
@Test
public void indexBy() throws Exception {
class Person {
public final String name;
public final Integer age;
public Person(final String name, final Integer age) {
this.name = name;
this.age = age;
}
public String toString() {
return name + ", " + age;
}
};
final Map<String, List<Person>> result =
_.indexBy(asList(new Person("moe", 40), new Person("larry", 50), new Person("curly", 60)), "age");
assertEquals("{40=[moe, 40], 50=[larry, 50], 60=[curly, 60]}", result.toString());
final Map<String, List<Person>> result2 =
_.indexBy(asList(new Person("moe", 40), new Person("larry", 50), new Person("curly", 60)), "age2");
assertEquals("{null=[moe, 40, larry, 50, curly, 60]}", result2.toString());
}
/*
var stooges = [{name: 'moe', age: 40}, {name: 'moe', age: 50}, {name: 'curly', age: 60}];
_.countBy(stooges, 'age');
=> {moe: 2, curly: 1}
*/
@Test
public void countBy() throws Exception {
class Person {
public final String name;
public final Integer age;
public Person(final String name, final Integer age) {
this.name = name;
this.age = age;
}
public String toString() {
return name + ", " + age;
}
};
final Map<String, Integer> result =
_.countBy(asList(new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)),
new Function1<Person, String>() {
public String apply(Person person) {
return person.name;
}
});
assertEquals("{moe=2, curly=1}", result.toString());
}
/*
(function(){ return _.toArray(arguments).slice(1); })(1, 2, 3, 4);
=> [2, 3, 4]
*/
@Test
public void toArray() throws Exception {
final Object[] result = _.<Integer>toArray(asList(1, 2, 3, 4));
assertEquals("1", result[0].toString());
}
/*
_.size({one: 1, two: 2, three: 3});
=> 3
*/
@Test
public void size() throws Exception {
final int result = _.size(asList(1, 2, 3, 4));
assertEquals(4, result);
}
/*
_.union([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2, 3, 101, 10]
*/
@Test
public void union() throws Exception {
final List<Integer> result = _.union(asList(1, 2, 3), asList(101, 2, 1, 10), asList(2, 1));
assertEquals("[1, 2, 3, 101, 10]", result.toString());
final Object[] resultArray = _.union(new Integer[] {1, 2, 3}, new Integer[] {101, 2, 1, 10});
assertEquals("[[1, 2, 3, 101, 10]]", asList(result).toString());
}
/*
_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2]
*/
@Test
public void intersection() throws Exception {
final List<Integer> result = _.intersection(asList(1, 2, 3), asList(101, 2, 1, 10), asList(2, 1));
assertEquals("[1, 2]", result.toString());
final Object[] resultArray = _.intersection(new Integer[] {1, 2, 3}, new Integer[] {101, 2, 1, 10});
assertEquals("[1, 2]", asList(resultArray).toString());
}
/*
_.difference([1, 2, 3, 4, 5], [5, 2, 10]);
=> [1, 3, 4]
*/
@Test
public void difference() throws Exception {
final List<Integer> result = _.difference(asList(1, 2, 3, 4, 5), asList(5, 2, 10));
assertEquals("[1, 3, 4]", result.toString());
final Object[] resultArray = _.difference(new Integer[] {1, 2, 3, 4, 5}, new Integer[] {5, 2, 10});
assertEquals("[1, 3, 4]", asList(resultArray).toString());
}
/*
_.uniq([1, 2, 1, 3, 1, 4]);
=> [1, 2, 3, 4]
*/
@Test
public void uniq() throws Exception {
final List<Integer> result = _.uniq(asList(1, 2, 1, 3, 1, 4));
assertEquals("[1, 2, 3, 4]", result.toString());
final Object[] resultArray = _.uniq(new Integer[] {1, 2, 1, 3, 1, 4});
assertEquals("[1, 2, 3, 4]", asList(resultArray).toString());
class Person {
public final String name;
public final Integer age;
public Person(final String name, final Integer age) {
this.name = name;
this.age = age;
}
public String toString() {
return name + ", " + age;
}
};
final Collection<Person> resultObject =
_.uniq(asList(new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)),
new Function1<Person, String>() {
public String apply(Person person) {
return person.name;
}
});
assertEquals("[moe, 50, curly, 60]", resultObject.toString());
final List<Person> resultObjectChain =
_.chain(asList(new Person("moe", 40), new Person("moe", 50), new Person("curly", 60))).uniq(
new Function1<Person, String>() {
public String apply(Person person) {
return person.name;
}
}).value();
assertEquals("[moe, 50, curly, 60]", resultObjectChain.toString());
final Object[] resultObjectArray =
_.uniq(asList(new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)).toArray(new Person[]{}),
new Function1<Person, String>() {
public String apply(Person person) {
return person.name;
}
});
assertEquals("[moe, 50, curly, 60]", asList(resultObjectArray).toString());
}
/*
_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);
=> [["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]
*/
@Test
public void zip() throws Exception {
final List<List<String>> result = _.zip(
asList("moe", "larry", "curly"), asList("30", "40", "50"), asList("true", "false", "false"));
assertEquals("[[moe, 30, true], [larry, 40, false], [curly, 50, false]]", result.toString());
}
/*
_.object(['moe', 'larry', 'curly'], [30, 40, 50]);
=> {moe: 30, larry: 40, curly: 50}
*/
@Test
public void object() throws Exception {
final List<Tuple<String, String>> result = _.object(
asList("moe", "larry", "curly"), asList("30", "40", "50"));
assertEquals("[(moe, 30), (larry, 40), (curly, 50)]", result.toString());
}
/*
_.indexOf([1, 2, 3], 2);
=> 1
*/
@Test
public void indexOf() throws Exception {
final Integer result = _.indexOf(asList(1, 2, 3), 2);
assertEquals(1, result);
final Integer resultArray = _.indexOf(new Integer[] {1, 2, 3}, 2);
assertEquals(1, resultArray);
}
/*
_.lastIndexOf([1, 2, 3, 1, 2, 3], 2);
=> 4
*/
@Test
public void lastIndexOf() throws Exception {
final Integer result = _.lastIndexOf(asList(1, 2, 3, 1, 2, 3), 2);
assertEquals(4, result);
final Integer resultArray = _.lastIndexOf(new Integer[] {1, 2, 3, 1, 2, 3}, 2);
assertEquals(4, resultArray);
}
@Test
public void findIndex() throws Exception {
final Integer result = _.findIndex(asList(1, 2, 3), new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals(1, result);
final Integer resultNotFound = _.findIndex(asList(1, 2, 3), new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item > 3;
}
});
assertEquals(-1, resultNotFound);
final Integer resultArray = _.findIndex(new Integer[] {1, 2, 3}, new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals(1, resultArray);
}
@Test
public void findKey() throws Exception {
final Integer result = _.findKey(asList(1, 2, 3), new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals(2, result);
final Integer resultNotFound = _.findKey(asList(1, 2, 3), new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item > 3;
}
});
assertNull(resultNotFound);
final Integer resultArray = _.findKey(new Integer[] {1, 2, 3}, new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals(2, resultArray);
}
@Test
public void findLastIndex() throws Exception {
final Integer result = _.findLastIndex(asList(1, 2, 3, 4, 5), new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals(3, result);
final Integer resultNotFound = _.findLastIndex(asList(1, 2, 3, 4, 5), new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item > 5;
}
});
assertEquals(-1, resultNotFound);
final Integer resultArray = _.findLastIndex(new Integer[] {1, 2, 3, 4, 5}, new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals(3, resultArray);
}
@Test
public void findLastKey() throws Exception {
final Integer result = _.findLastKey(asList(1, 2, 3, 4, 5), new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals(4, result);
final Integer resultNotFound = _.findLastKey(asList(1, 2, 3, 4, 5), new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item > 5;
}
});
assertNull(resultNotFound);
final Integer resultArray = _.findLastKey(new Integer[] {1, 2, 3, 4, 5}, new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals(4, resultArray);
}
/*
_.sortedIndex([10, 20, 30, 40, 50], 35);
=> 3
*/
@Test
public void sortedIndex() throws Exception {
final Integer result = _.sortedIndex(asList(10, 20, 30, 40, 50), 35);
assertEquals(3, result);
final Integer result2 = _.sortedIndex(new Integer[] {10, 20, 30, 40, 50}, 35);
assertEquals(3, result2);
final Integer result3 = _.sortedIndex(asList(10, 20, 30, 40, 50), 60);
assertEquals(-1, result3);
}
@Test
public void sortedIndex2() throws Exception {
class Person implements Comparable<Person> {
public final String name;
public final Integer age;
public Person(final String name, final Integer age) {
this.name = name;
this.age = age;
}
public int compareTo(Person person) {
return person.age - this.age;
}
public String toString() {
return name + ", " + age;
}
};
final int result =
_.<Person>sortedIndex(asList(new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)), new Person("moe", 50), "age");
assertEquals(1, result);
final int result2 =
_.<Person>sortedIndex(asList(new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)), new Person("moe", 70), "age");
assertEquals(-1, result2);
final int resultArray =
_.<Person>sortedIndex(new Person[] {new Person("moe", 40), new Person("moe", 50), new Person("curly", 60)}, new Person("moe", 50), "age");
assertEquals(1, resultArray);
}
/*
_.range(10);
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
_.range(1, 11);
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_.range(0, 30, 5);
=> [0, 5, 10, 15, 20, 25]
_.range(0, -10, -1);
=> [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
_.range(0);
=> []
*/
@Test
public void range() throws Exception {
final int[] result = _.range(10);
assertArrayEquals(new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, result);
final int[] result2 = _.range(1, 11);
assertArrayEquals(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, result2);
final int[] result3 = _.range(0, 30, 5);
assertArrayEquals(new int[] {0, 5, 10, 15, 20, 25}, result3);
final int[] result4 = _.range(0, -10, -1);
assertArrayEquals(new int[] {0, -1, -2, -3, -4, -5, -6, -7, -8, -9}, result4);
final int[] result5 = _.range(0);
assertArrayEquals(new int[] {}, result5);
}
/*
_.partition([0, 1, 2, 3, 4, 5], isOdd);
=> [[1, 3, 5], [0, 2, 4]]
*/
@Test
public void partition() throws Exception {
final List<List<Integer>> result = _.partition(asList(0, 1, 2, 3, 4, 5), new Predicate<Integer>() {
public Boolean apply(final Integer item) {
return item % 2 == 1;
}
});
assertEquals("[1, 3, 5]", result.get(0).toString());
assertEquals("[0, 2, 4]", result.get(1).toString());
final List<Integer>[] resultArray = _.partition(new Integer[] {0, 1, 2, 3, 4, 5}, new Predicate<Integer>() {
public Boolean apply(final Integer item) {
return item % 2 == 1;
}
});
assertEquals("[1, 3, 5]", resultArray[0].toString());
assertEquals("[0, 2, 4]", resultArray[1].toString());
}
/*
var stooges = [{name: 'curly', age: 25}, {name: 'moe', age: 21}, {name: 'larry', age: 23}];
var youngest = _.chain(stooges)
.sortBy(function(stooge){ return stooge.age; })
.map(function(stooge){ return stooge.name + ' is ' + stooge.age; })
.first()
.value();
=> "moe is 21"
*/
@Test
public void chain() throws Exception {
final List<Map<String, Object>> stooges = new ArrayList<Map<String, Object>>() {{
add(new LinkedHashMap<String, Object>() {{ put("name", "curly"); put("age", 25); }});
add(new LinkedHashMap<String, Object>() {{ put("name", "moe"); put("age", 21); }});
add(new LinkedHashMap<String, Object>() {{ put("name", "larry"); put("age", 23); }});
}};
final String youngest = _.chain(stooges)
.sortBy(
new Function1<Map<String, Object>, String>() {
public String apply(Map<String, Object> item) {
return item.get("age").toString();
}
})
.map(
new Function1<Map<String, Object>, String>() {
public String apply(Map<String, Object> item) {
return item.get("name") + " is " + item.get("age");
}
})
.first().item().toString();
assertEquals("moe is 21", youngest);
}
@Test
public void chainSet() throws Exception {
final Set<Map<String, Object>> stooges = new HashSet<Map<String, Object>>() {{
add(new LinkedHashMap<String, Object>() {{ put("name", "curly"); put("age", 25); }});
add(new LinkedHashMap<String, Object>() {{ put("name", "moe"); put("age", 21); }});
add(new LinkedHashMap<String, Object>() {{ put("name", "larry"); put("age", 23); }});
}};
final String youngest = _.chain(stooges)
.sortBy(
new Function1<Map<String, Object>, String>() {
public String apply(Map<String, Object> item) {
return item.get("age").toString();
}
})
.map(
new Function1<Map<String, Object>, String>() {
public String apply(Map<String, Object> item) {
return item.get("name") + " is " + item.get("age");
}
})
.first().item().toString();
assertEquals("moe is 21", youngest);
}
@Test
public void chainArray() throws Exception {
final List<Map<String, Object>> stooges = new ArrayList<Map<String, Object>>() {{
add(new LinkedHashMap<String, Object>() {{ put("name", "curly"); put("age", 25); }});
add(new LinkedHashMap<String, Object>() {{ put("name", "moe"); put("age", 21); }});
add(new LinkedHashMap<String, Object>() {{ put("name", "larry"); put("age", 23); }});
}};
final String youngest = _.chain(stooges.toArray())
.sortBy(
new Function1<Map<String, Object>, String>() {
public String apply(Map<String, Object> item) {
return item.get("age").toString();
}
})
.map(
new Function1<Map<String, Object>, String>() {
public String apply(Map<String, Object> item) {
return item.get("name") + " is " + item.get("age");
}
})
.first().item().toString();
assertEquals("moe is 21", youngest);
}
/*
var lyrics = [
{line: 1, words: "I'm a lumberjack and I'm okay"},
{line: 2, words: "I sleep all night and I work all day"},
{line: 3, words: "He's a lumberjack and he's okay"},
{line: 4, words: "He sleeps all night and he works all day"}
];
_.chain(lyrics)
.map(function(line) { return line.words.split(' '); })
.flatten()
.reduce(function(counts, word) {
counts[word] = (counts[word] || 0) + 1;
return counts;
}, {})
.value();
=> {lumberjack: 2, all: 4, night: 2 ... }
*/
@Test
public void chain2() throws Exception {
final List<Map<String, Object>> lyrics = new ArrayList<Map<String, Object>>() {{
add(new LinkedHashMap<String, Object>() {{ put("line", 1); put("words", "I'm a lumberjack and I'm okay"); }});
add(new LinkedHashMap<String, Object>() {{ put("line", 2); put("words", "I sleep all night and I work all day"); }});
add(new LinkedHashMap<String, Object>() {{ put("line", 3); put("words", "He's a lumberjack and he's okay"); }});
add(new LinkedHashMap<String, Object>() {{ put("line", 4); put("words", "He sleeps all night and he works all day"); }});
}};
final String result = _.chain(lyrics)
.map(
new Function1<Map<String, Object>, List<String>>() {
public List<String> apply(Map<String, Object> item) {
return asList(String.valueOf(item.get("words")).split(" "));
}
})
.flatten()
.reduce(
new FunctionAccum<Map<String, Object>, String>() {
public Map<String, Object> apply(Map<String, Object> accum, String item) {
if (accum.get(item) == null) {
accum.put(item, 1);
} else {
accum.put(item, ((Integer) accum.get(item)) + 1);
}
return accum;
}
},
new LinkedHashMap<String, Object>()
)
.item().toString();
assertEquals("{I'm=2, a=2, lumberjack=2, and=4, okay=2, I=2, sleep=1, all=4, night=2, work=1, day=2, He's=1,"
+ " he's=1, He=1, sleeps=1, he=1, works=1}", result);
}
/*
var lyrics = [
{line: 1, words: "I'm a lumberjack and I'm okay"},
{line: 2, words: "I sleep all night and I work all day"},
{line: 3, words: "He's a lumberjack and he's okay"},
{line: 4, words: "He sleeps all night and he works all day"}
];
_.chain(lyrics)
.map(function(line) { return line.words.split(' '); })
.flatten()
.reduceRight(function(counts, word) {
counts[word] = (counts[word] || 0) + 1;
return counts;
}, {})
.value();
=> {day=2, all=4, works=1 ... }
*/
@Test
public void chain3() throws Exception {
final List<Map<String, Object>> lyrics = new ArrayList<Map<String, Object>>() {{
add(new LinkedHashMap<String, Object>() {{ put("line", 1); put("words", "I'm a lumberjack and I'm okay"); }});
add(new LinkedHashMap<String, Object>() {{ put("line", 2); put("words", "I sleep all night and I work all day"); }});
add(new LinkedHashMap<String, Object>() {{ put("line", 3); put("words", "He's a lumberjack and he's okay"); }});
add(new LinkedHashMap<String, Object>() {{ put("line", 4); put("words", "He sleeps all night and he works all day"); }});
}};
final String result = _.chain(lyrics)
.map(
new Function1<Map<String, Object>, List<String>>() {
public List<String> apply(Map<String, Object> item) {
return asList(String.valueOf(item.get("words")).split(" "));
}
})
.flatten()
.reduceRight(
new FunctionAccum<Map<String, Object>, String>() {
public Map<String, Object> apply(Map<String, Object> accum, String item) {
if (accum.get(item) == null) {
accum.put(item, 1);
} else {
accum.put(item, ((Integer) accum.get(item)) + 1);
}
return accum;
}
},
new LinkedHashMap<String, Object>()
)
.item().toString();
assertEquals("{day=2, all=4, works=1, he=1, and=4, night=2, sleeps=1,"
+ " He=1, okay=2, he's=1, lumberjack=2, a=2, He's=1, work=1, I=2, sleep=1, I'm=2}", result);
}
/*
var doctors = [
{ number: 1, actor: "William Hartnell", begin: 1963, end: 1966 },
{ number: 9, actor: "Christopher Eccleston", begin: 2005, end: 2005 },
{ number: 10, actor: "David Tennant", begin: 2005, end: 2010 }
];
_.chain(doctors)
.filter(function(doctor) {
return doctor.begin > 2000;
})
.reject(function(doctor) {
return doctor.begin > 2009;
})
.map(function(doctor) {
return {
doctorNumber: "#" + doctor.number,
playedBy: doctor.actor,
yearsPlayed: doctor.end - doctor.begin + 1
};
})
.value();
=> [{ doctorNumber: "#9", playedBy: "Christopher Eccleston", yearsPlayed: 1 }]
*/
@Test
public void chain4() throws Exception {
final List<Map<String, Object>> doctors = new ArrayList<Map<String, Object>>() {{
add(new LinkedHashMap<String, Object>() {{ put("number", 1); put("actor", "William Hartnell"); put("begin", 1963); put("end", 1966); }});
add(new LinkedHashMap<String, Object>() {{ put("number", 9); put("actor", "Christopher Eccleston"); put("begin", 2005); put("end", 2005); }});
add(new LinkedHashMap<String, Object>() {{ put("number", 10); put("actor", "David Tennant"); put("begin", 2005); put("end", 2010); }});
}};
final String result = _.chain(doctors)
.filter(
new Predicate<Map<String, Object>>() {
public Boolean apply(Map<String, Object> item) {
return (Integer) item.get("begin") > 2000;
}
})
.reject(
new Predicate<Map<String, Object>>() {
public Boolean apply(Map<String, Object> item) {
return (Integer) item.get("end") > 2009;
}
})
.map(
new Function1<Map<String, Object>, Map<String, Object>>() {
public Map<String, Object> apply(final Map<String, Object> item) {
return new LinkedHashMap<String, Object>() {{
put("doctorNumber", "#" + item.get("number"));
put("playedBy", item.get("actor"));
put("yearsPlayed", (Integer) item.get("end") - (Integer) item.get("begin") + 1);
}};
}
})
.value().toString();
assertEquals("[{doctorNumber=#9, playedBy=Christopher Eccleston, yearsPlayed=1}]", result);
}
/*
var compiled = _.template("hello: <%= name %>");
compiled({name: 'moe'});
=> "hello: moe"
*/
@Test
public void template() throws Exception {
Template<Set<Map.Entry<String,Object>>> compiled = _.template("hello: <%= name %>");
assertEquals("hello: moe", compiled.apply(new LinkedHashMap<String, Object>() {{ put("name", "moe"); }}.entrySet()));
}
@Test
public void template2() throws Exception {
Template<Set<Map.Entry<String,Object>>> compiled = _.template("hello: <%= name %>, hello2: <%= name %>");
assertEquals("hello: moe, hello2: moe", compiled.apply(new LinkedHashMap<String, Object>() {{ put("name", "moe"); }}.entrySet()));
}
@Test
public void template3() throws Exception {
Template<Set<Map.Entry<String,Object>>> compiled = _.template("hello: <%= name %>, hello2: <%= name2 %>");
assertEquals("hello: moe, hello2: moe2", compiled.apply(
new LinkedHashMap<String, Object>() {{ put("name", "moe"); put("name2", "moe2"); }}.entrySet()));
}
/*
var list = "<% _.each(people, function(name) { %> <li><%= name %></li> <% }); %>";
_.template(list, {people: ['moe', 'curly', 'larry']});
=> "<li>moe</li><li>curly</li><li>larry</li>"
*/
@Test
public void templateEach() throws Exception {
String list = "<% _.each(people, function(name) { %> <li><%= name %></li> <% }); %>";
Template<Set<Map.Entry<String,Object>>> compiled = _.template(list);
assertEquals(" <li>moe</li> <li>curly</li> <li>larry</li> ",
compiled.apply(new LinkedHashMap<String, Object>() {{ put("people", asList("moe", "curly", "larry")); }}.entrySet()));
}
/*
var template = _.template("<b><%- value %></b>");
template({value: '<script>'});
=> "<b><script></b>"
*/
@Test
public void templateValue() throws Exception {
Template<Set<Map.Entry<String,Object>>> template = _.template("<b><%- value %></b>");
assertEquals("<b><script></b>",
template.apply(new LinkedHashMap<String, Object>() {{ put("value", "<script>"); }}.entrySet()));
}
@Test
public void templateValue2() throws Exception {
Template<Set<Map.Entry<String,Object>>> template = _.template("hello: <%= name %>, <b><%- value %></b>");
assertEquals("hello: moe, <b><script></b>",
template.apply(new LinkedHashMap<String, Object>() {{ put("name", "moe"); put("value", "<script>"); }}.entrySet()));
}
/*
var compiled = _.template("<% print('Hello ' + epithet); %>");
compiled({epithet: "stooge"});
=> "Hello stooge"
*/
@Test
public void templatePrint() throws Exception {
Template<Set<Map.Entry<String,Object>>> compiled = _.template("<% print('Hello ' + epithet); %>");
assertEquals("Hello stooge",
compiled.apply(new LinkedHashMap<String, Object>() {{ put("epithet", "stooge"); }}.entrySet()));
}
/*
_.escape('Curly, Larry & Moe');
=> "Curly, Larry & Moe"
*/
@Test
public void escape() throws Exception {
assertEquals("Curly, Larry & Moe", _.escape("Curly, Larry & Moe"));
}
/*
_.unescape('Curly, Larry & Moe');
=> "Curly, Larry & Moe"
*/
@Test
public void unescape() throws Exception {
assertEquals("Curly, Larry & Moe", _.unescape("Curly, Larry & Moe"));
}
/*
var object = {cheese: 'crumpets', stuff: function(){ return 'nonsense'; }};
_.result(object, 'cheese');
=> "crumpets"
_.result(object, 'stuff');
=> "nonsense"
*/
@Test
public void result() throws Exception {
Map<String, Object> object = new LinkedHashMap<String, Object>() {{
put("cheese", "crumpets");
put("stuff", new Function<String>() { public String apply() { return "nonsense"; }});
}};
assertEquals("crumpets", _.result(object.entrySet(), new Predicate<Map.Entry<String, Object>>() {
public Boolean apply(Map.Entry<String, Object> item) {
return item.getKey().equals("cheese");
}
}));
assertEquals("nonsense", _.result(object.entrySet(), new Predicate<Map.Entry<String, Object>>() {
public Boolean apply(Map.Entry<String, Object> item) {
return item.getKey().equals("stuff");
}
}));
assertEquals("result1", _.result(asList("result1", "result2"), new Predicate<String>() {
public Boolean apply(String item) {
return item.equals("result1");
}
}));
assertEquals(null, _.result(asList("result1", "result2"), new Predicate<String>() {
public Boolean apply(String item) {
return item.equals("result3");
}
}));
}
/*
var counter = 0;
var incr = function(){ counter++; };
var debouncedIncr = _.debounce(incr, 32);
debouncedIncr(); debouncedIncr();
_.delay(debouncedIncr, 16);
_.delay(function(){ equal(counter, 1, 'incr was debounced'); }, 96);
*/
@Test
public void debounce() throws Exception {
final Integer[] counter = new Integer[] {0};
Function<Void> incr = new Function<Void>() { public Void apply() { counter[0]++; return null; }};
Function<Void> debouncedIncr = _.debounce(incr, 50);
debouncedIncr.apply();
debouncedIncr.apply();
_.delay(debouncedIncr, 16);
_.delay(new Function<Void>() {
public Void apply() {
assertEquals("incr was debounced", 1, counter[0]);
return null;
}
}, 32);
Thread.sleep(120);
}
@Test
public void main() throws Exception {
_.main(new String[] {});
}
/*
['some', 'words', 'example'].sort();
=> ['example', 'some', 'words']
*/
@Test
public void sort() throws Exception {
assertEquals("[example, some, words]", _.sort(asList("some", "words", "example")).toString());
assertEquals("[example, some, words]", asList(_.sort(new String[] {"some", "words", "example"})).toString());
}
/*
['some', 'words', 'example'].join('-');
=> 'some-words-example'
*/
@Test
public void join() throws Exception {
assertEquals("some-words-example", _.join(asList("some", "words", "example"), "-"));
assertEquals("some-words-example", _.join(new String[] {"some", "words", "example"}, "-"));
}
@Test
public void compareStrings() throws Exception {
assertEquals(_.sort("CAT".split("")), _.sort("CTA".split("")));
}
/*
_.concat([1, 2], [3, 4]);
=> [1, 2, 3, 4]
*/
@Test
public void concat() throws Exception {
assertEquals(asList(1, 2, 3, 4), asList(_.concat(new Integer[] {1, 2}, new Integer[] {3, 4})));
assertEquals(asList(1, 2, 3, 4), _.concat(asList(1, 2), asList(3, 4)));
assertEquals("[1, 2, 3, 4]", _.chain(asList(1, 2)).concat(asList(3, 4)).value().toString());
assertEquals(asList(1, 2, 3, 4), asList(_.concat(new Integer[] {1, 2}, new Integer[] {3}, new Integer[] {4})));
assertEquals(asList(1, 2, 3, 4), _.concat(asList(1, 2), asList(3), asList(4)));
}
@Test
public void classForName_without_guava() {
_.classForName = new _.ClassForName() {
public Class<?> call(final String name) throws Exception {
throw new Exception();
}
};
final List<Integer> result1 = _.filter(asList(1, 2, 3, 4, 5, 6),
new Predicate<Integer>() {
public Boolean apply(Integer item) {
return item % 2 == 0;
}
});
assertEquals("[2, 4, 6]", result1.toString());
final List<Integer> result2 = _.shuffle(asList(1, 2, 3, 4, 5, 6));
assertEquals(6, result2.size());
List<Integer> result3 = _.map(asList(1, 2, 3), new Function1<Integer, Integer>() {
public Integer apply(Integer item) {
return item * 3;
}
});
assertEquals("[3, 6, 9]", result3.toString());
final Set<Integer> result4 =
_.map(new LinkedHashMap<Integer, String>() {{ put(1, "one"); put(2, "two"); put(3, "three"); }}.entrySet(),
new Function1<Map.Entry<Integer, String>, Integer>() {
public Integer apply(Map.Entry<Integer, String> item) {
return item.getKey() * 3;
}
});
assertEquals("[3, 6, 9]", result4.toString());
final List<Integer> result5 = _.union(asList(1, 2, 3), asList(101, 2, 1, 10), asList(2, 1));
assertEquals("[1, 2, 3, 101, 10]", result5.toString());
final Map<Double, List<Double>> result6 =
_.groupBy(asList(1.3, 2.1, 2.4),
new Function1<Double, Double>() {
public Double apply(Double num) {
return Math.floor(num);
}
});
assertEquals("{1.0=[1.3], 2.0=[2.1, 2.4]}", result6.toString());
final List<Integer> result7 = _.uniq(asList(1, 2, 1, 3, 1, 4));
assertEquals("[1, 2, 3, 4]", result7.toString());
}
} |
package innovimax.mixthem;
import innovimax.mixthem.arguments.Arguments;
import innovimax.mixthem.arguments.ArgumentException;
import java.io.IOException;
import java.util.zip.ZipException;
import org.junit.Assert;
import org.junit.Test;
public class BasicTest {
@Test
public final void testPrintUsage() {
Arguments.printUsage();
Assert.assertTrue(true);
}
@Test(expected=ArgumentException.class)
public final void testEmptyArgs() throws ArgumentException, IOException, ZipException {
try {
final String args[] = {};
final Arguments mixArgs = Arguments.checkArguments(args);
} catch (ArgumentException e) {
System.out.println("testEmptyArgs: " + e.getMessage());
throw e;
}
}
@Test(expected=ArgumentException.class)
public final void testWrongArgs() throws ArgumentException, IOException, ZipException {
try {
final String args[] = { "ghost1", "ghost2" };
final Arguments mixArgs = Arguments.checkArguments(args);
} catch (ArgumentException e) {
System.out.println("testWrongArgs: " + e.getMessage());
throw e;
}
}
@Test
public final void testNoRule() throws ArgumentException, IOException, ZipException {
final String args[] = { getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() };
final Arguments mixArgs = Arguments.checkArguments(args);
Assert.assertTrue(true);
}
@Test
public final void test1Rule() throws ArgumentException, IOException, ZipException {
final String args[] = { "-1", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() };
final Arguments mixArgs = Arguments.checkArguments(args);
Assert.assertTrue(true);
}
@Test(expected=ArgumentException.class)
public final void testUnknownRule() throws ArgumentException, IOException, ZipException {
try {
final String args[] = { "-x", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() };
final Arguments mixArgs = Arguments.checkArguments(args);
} catch (ArgumentException e) {
System.out.println("testUnknownRule: " + e.getMessage());
throw e;
}
}
@Test(expected=ArgumentException.class)
public final void testUnexpectedParam() throws ArgumentException, IOException, ZipException {
try {
final String args[] = { "-1", "#val", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() };
final Arguments mixArgs = Arguments.checkArguments(args);
} catch (ArgumentException e) {
System.out.println("testUnexpectedParam: " + e.getMessage());
throw e;
}
}
@Test(expected=ArgumentException.class)
public final void testWrongSeedParam() throws ArgumentException, IOException, ZipException {
try {
final String args[] = { "-random-alt-line", "#val", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() };
final Arguments mixArgs = Arguments.checkArguments(args);
} catch (ArgumentException e) {
System.out.println("testWrongSeedParam: " + e.getMessage());
throw e;
}
}
@Test
public final void testValidSeedParam() throws ArgumentException, IOException, ZipException {
final String args[] = { "-random-alt-line", "#1789", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() };
Arguments mixArgs = Arguments.checkArguments(args);
Assert.assertTrue(true);
}
@Test(expected=ArgumentException.class)
public final void testNotAParam() throws ArgumentException, IOException, ZipException {
try {
final String args[] = { "-random-alt-line", "1789", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() };
final Arguments mixArgs = Arguments.checkArguments(args);
} catch (ArgumentException e) {
System.out.println("testNotAParam: " + e.getMessage());
throw e;
}
}
@Test
public final void testOptionalParam() throws ArgumentException, IOException, ZipException {
final String args[] = { "-random-alt-line", getClass().getResource("test001_file1.txt").getFile(), getClass().getResource("test001_file2.txt").getFile() };
final Arguments mixArgs = Arguments.checkArguments(args);
Assert.assertTrue(true);
}
@Test(expected=ArgumentException.class)
public final void testZipEmptyArgs() throws ArgumentException, IOException, ZipException {
try {
final String args[] = { "--zip" };
Arguments mixArgs = Arguments.checkArguments(args);
} catch (ArgumentException e) {
System.out.println("testZipEmptyArgs: " + e.getMessage());
throw e;
}
}
@Test(expected=ArgumentException.class)
public final void testZipWrongArgs() throws ArgumentException, IOException, ZipException {
try {
final String args[] = { "--zip", "zip/ghost1" };
final Arguments mixArgs = Arguments.checkArguments(args);
} catch (ArgumentException e) {
System.out.println("testZipWrongArgs: " + e.getMessage());
throw e;
}
}
@Test
public final void testZipNoRule() throws ArgumentException, IOException, ZipException {
final String args[] = { "--zip", getClass().getResource("zip/test001.zip").getFile() };
final Arguments mixArgs = Arguments.checkArguments(args);
Assert.assertTrue(true);
}
@Test
public final void testJar1Rule() throws ArgumentException, IOException, ZipException {
final String args[] = { "-1", "--jar", getClass().getResource("zip/test001.jar").getFile() };
final Arguments mixArgs = Arguments.checkArguments(args);
Assert.assertTrue(true);
}
@Test(expected=ArgumentException.class)
public final void testZipOneFile() throws ArgumentException, IOException, ZipException {
try {
final String args[] = { "--zip", getClass().getResource("zip/wrong.zip").getFile() };
final Arguments mixArgs = Arguments.checkArguments(args);
} catch (ArgumentException e) {
System.out.println("testZipOneFile: " + e.getMessage());
throw e;
}
}
@Test(expected=ArgumentException.class)
public final void testJarEmpty() throws ArgumentException, IOException, ZipException {
try {
final String args[] = { "--jar", getClass().getResource("zip/empty.jar").getFile() };
final Arguments mixArgs = Arguments.checkArguments(args);
} catch (ArgumentException e) {
System.out.println("testJarEmpty: " + e.getMessage());
throw e;
}
}
} |
package io.cloudslang.content.active_directory.actions.groups;
import com.hp.oo.sdk.content.annotations.Action;
import com.hp.oo.sdk.content.annotations.Output;
import com.hp.oo.sdk.content.annotations.Param;
import com.hp.oo.sdk.content.annotations.Response;
import com.hp.oo.sdk.content.plugin.ActionMetadata.MatchType;
import com.hp.oo.sdk.content.plugin.ActionMetadata.ResponseType;
import io.cloudslang.content.constants.ResponseNames;
import io.cloudslang.content.constants.ReturnCodes;
import io.cloudslang.content.active_directory.constants.InputNames;
import io.cloudslang.content.active_directory.constants.OutputNames;
import io.cloudslang.content.active_directory.entities.AddRemoveUserInput;
import io.cloudslang.content.active_directory.services.groups.RemoveUserFromGroupService;
import io.cloudslang.content.active_directory.utils.ResultUtils;
import java.util.Map;
import static io.cloudslang.content.active_directory.constants.Constants.*;
import static io.cloudslang.content.active_directory.constants.Descriptions.Common.*;
import static io.cloudslang.content.active_directory.constants.Descriptions.RemoveUserFromGroup.*;
import static io.cloudslang.content.active_directory.constants.TlsVersions.TLSv1_2;
import static org.apache.commons.lang3.StringUtils.defaultIfEmpty;
public class RemoveUserFromGroupAction {
@Action(name = "Remove User From Group", description = REMOVE_USER_FROM_GROUP,
outputs = {
@Output(value = OutputNames.RETURN_RESULT, description = RETURN_RESULT_DESC),
@Output(value = OutputNames.RETURN_CODE, description = RETURN_CODE_DESC),
@Output(value = OutputNames.EXCEPTION, description = EXCEPTION_DESC)
},
responses = {
@Response(text = ResponseNames.SUCCESS, field = OutputNames.RETURN_CODE, value = ReturnCodes.SUCCESS,
matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED, description = SUCCESS_DESC),
@Response(text = ResponseNames.FAILURE, field = OutputNames.RETURN_CODE,
value = ReturnCodes.FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, description = FAILURE_DESC)
})
public Map<String, String> execute(
@Param(value = InputNames.HOST, required = true, description = HOST_DESC) String host,
@Param(value = InputNames.PROTOCOL, description = PROTOCOL_DESC) String protocol,
@Param(value = InputNames.USERNAME, required = true, description = USERNAME_DESC) String username,
@Param(value = InputNames.PASSWORD, encrypted = true, required = true, description = PASSWORD_DESC) String password,
@Param(value = InputNames.GROUP_DISTINGUISHED_NAME, required = true, description = DISTINGUISHED_NAME_DESC) String groupDistinguishedName,
@Param(value = InputNames.USER_DISTINGUISHED_NAME, required = true, description = USER_DISTINGUISHED_NAME_DESC) String userDistinguishedName,
@Param(value = InputNames.PROXY_HOST, description = PROXY_HOST_DESC) String proxyHost,
@Param(value = InputNames.PROXY_PORT, description = PROXY_PORT_DESC) String proxyPort,
@Param(value = InputNames.PROXY_USERNAME, description = PROXY_USERNAME_DESC) String proxyUsername,
@Param(value = InputNames.PROXY_PASSWORD, description = PROXY_PASSWORD_DESC) String proxyPassword,
@Param(value = InputNames.TLS_VERSION, description = TLS_VERSION_DESC) String tlsVersion,
@Param(value = InputNames.ALLOWED_CIPHERS, description = ALLOWED_CIPHERS_DESC) String allowedCiphers,
@Param(value = InputNames.X_509_HOSTNAME_VERIFIER, description = X_509_DESC) String x509HostnameVerifier,
@Param(value = InputNames.TRUST_ALL_ROOTS, description = TRUST_ALL_ROOTS_DESC) String trustAllRoots,
@Param(value = InputNames.TRUST_KEYSTORE, description = TRUST_KEYSTORE_DESC) String trustKeystore,
@Param(value = InputNames.TRUST_PASSWORD, encrypted = true, description = TRUST_PASSWORD_DESC) String trustPassword,
@Param(value = InputNames.TIMEOUT, description = TIMEOUT_DESC) String timeout) {
protocol = defaultIfEmpty(protocol, HTTPS);
proxyPort = defaultIfEmpty(proxyPort, DEFAULT_PROXY_PORT);
tlsVersion = defaultIfEmpty(tlsVersion, TLSv1_2);
allowedCiphers = defaultIfEmpty(allowedCiphers, ALLOWED_CIPHERS_LIST);
x509HostnameVerifier = defaultIfEmpty(x509HostnameVerifier, STRICT);
trustAllRoots = defaultIfEmpty(trustAllRoots, BOOLEAN_FALSE);
trustPassword = defaultIfEmpty(trustPassword, DEFAULT_PASSWORD_FOR_STORE);
timeout = defaultIfEmpty(timeout, TIMEOUT_VALUE);
AddRemoveUserInput.Builder inputBuilder = new AddRemoveUserInput.Builder()
.host(host)
.groupDistinguishedName(groupDistinguishedName)
.userDistinguishedName(userDistinguishedName)
.username(username)
.password(password)
.protocol(protocol)
.proxyHost(proxyHost)
.proxyPort(proxyPort)
.proxyUsername(proxyUsername)
.proxyPassword(proxyPassword)
.tlsVersion(tlsVersion)
.allowedCiphers(allowedCiphers)
.x509HostnameVerifier(x509HostnameVerifier)
.trustAllRoots(trustAllRoots)
.trustKeystore(trustKeystore)
.trustPassword(trustPassword)
.timeout(timeout);
try {
return new RemoveUserFromGroupService().execute(inputBuilder.build());
} catch (Exception e) {
return ResultUtils.fromException(e);
}
}
} |
package com.jmex.bui;
import com.jmex.bui.base.BaseTest2;
import com.jmex.bui.layout.BorderLayout;
/**
* @author torr
* @since Apr 10, 2009 - 2:44:23 PM
*/
public class ChatTest extends BaseTest2 {
@Override
protected void createWindows() {
BWindow window = new BWindow(BuiSystem.getStyle(), new BorderLayout(1, 2));
window.add(new BChatComponent(), BorderLayout.WEST);
window.add(new BChatComponent(), BorderLayout.EAST);
window.setBounds(20, 140, 400, 250);
BuiSystem.addWindow(window);
}
public static void main(String[] args) {
new ChatTest().start();
}
} |
package de.itemis.xtext.utils.jface.viewers;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.jface.text.IDocumentPartitioner;
import org.eclipse.jface.text.source.AnnotationModel;
import org.eclipse.jface.text.source.ICharacterPairMatcher;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.SourceViewer;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.StructuredViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.BusyIndicator;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.internal.editors.text.EditorsPlugin;
import org.eclipse.ui.texteditor.AbstractDecoratedTextEditor;
import org.eclipse.ui.texteditor.AnnotationPreference;
import org.eclipse.ui.texteditor.DefaultMarkerAnnotationAccess;
import org.eclipse.ui.texteditor.MarkerAnnotationPreferences;
import org.eclipse.ui.texteditor.SourceViewerDecorationSupport;
import org.eclipse.xtext.Constants;
import org.eclipse.xtext.parser.IParseResult;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.ui.editor.XtextEditor;
import org.eclipse.xtext.ui.editor.XtextSourceViewer;
import org.eclipse.xtext.ui.editor.XtextSourceViewer.Factory;
import org.eclipse.xtext.ui.editor.XtextSourceViewerConfiguration;
import org.eclipse.xtext.ui.editor.bracketmatching.BracketMatchingPreferencesInitializer;
import org.eclipse.xtext.ui.editor.model.XtextDocument;
import org.eclipse.xtext.ui.editor.preferences.IPreferenceStoreAccess;
import org.eclipse.xtext.ui.editor.quickfix.IssueResolutionProvider;
import org.eclipse.xtext.ui.editor.validation.AnnotationIssueProcessor;
import org.eclipse.xtext.ui.editor.validation.ValidationJob;
import org.eclipse.xtext.ui.resource.IResourceSetProvider;
import org.eclipse.xtext.util.concurrent.IUnitOfWork;
import org.eclipse.xtext.validation.CheckMode;
import org.eclipse.xtext.validation.IResourceValidator;
import org.eclipse.xtext.validation.Issue;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Provider;
import com.google.inject.name.Named;
import de.itemis.xtext.utils.jface.viewers.util.ActiveProjectResolver;
/**
* This class integrates xText Features into a {@link StyledText} and can be
* used i.e. as {@link CellEditor}s in jface {@link StructuredViewer}s or in GMF
* EditParts via DirectEditManager.
*
* The current implementation supports, code completion, syntax highlighting and
* validation
*
* Some code is initially copied from xText.
*
* @author andreas.muelder@itemis.de
* @author alexander.nyssen@itemis.de
* @author patrick.koenemann@itemis.de
*/
// TODO: Check if we can use the XTextDocumentProvider instead of creating own
// XTextDocument + setup
@SuppressWarnings("restriction")
public class XtextStyledText {
/**
* Key listener executed content assist operation on CTRL+Space
*/
private final KeyListener keyListener = new KeyListener() {
public void keyPressed(KeyEvent e) {
// CONTENTASSIST_PROPOSALS
if ((e.keyCode == 32) && ((e.stateMask & SWT.CTRL) != 0)) {
BusyIndicator.showWhile(Display.getDefault(), new Runnable() {
public void run() {
sourceviewer
.doOperation(ISourceViewer.CONTENTASSIST_PROPOSALS);
}
});
}
}
public void keyReleased(KeyEvent e) {
}
};
/**
* The sourceViewer, that provides additional functions to the styled text
* widget
*/
protected XtextSourceViewer sourceviewer;
private ValidationJob validationJob;
private IssueResolutionProvider resolutionProvider = new IssueResolutionProvider.NullImpl();
@Inject
private IPreferenceStoreAccess preferenceStoreAccess;
@Inject
private ICharacterPairMatcher characterPairMatcher;
@Inject
private XtextSourceViewerConfiguration configuration;
@Inject
private Factory sourceViewerFactory;
@Inject
private XtextResource fakeResource;
@Inject
private IResourceValidator validator;
@Inject
private Provider<IDocumentPartitioner> documentPartitioner;
@Inject
private @Named(Constants.FILE_EXTENSIONS)
String fileExtension;
@Inject
private XtextDocument document;
@Inject
private IResourceSetProvider resourceSetProvider;
private Resource contextResource;
private final int style;
private Composite parent;
private IProject activeProject;
private StyledText styledText;
private ResourceSet resourceSet;
/**
* C'tor to create a new Instance.
*
* No specific contextResource is set for xtext! If you need a
* contextResource, use
* {@link XtextStyledText#XtextStyledText(Composite, int, Injector, Resource)}
* !
*
* <b>Please note:</b> Since the text control has content assist proposals
* enabled via a listener, <code>dispose</code> must be called to unregister
* the listener!
*
* @param style
* The SWT styles for this text widget.
* @param injector
* For xtext dependency injection.
*/
public XtextStyledText(Composite parent, int style, Injector injector) {
this(parent, style, injector, null);
}
/**
* C'tor to create a new Instance.
*
* In contrast to
* {@link XtextStyledText#XtextStyledText(Composite, int, Injector)}, this
* constructor uses a specific contextResource for xtext.
*
* <b>Please note:</b> Since the text control has content assist proposals
* enabled via a listener, <code>dispose</code> must be called to unregister
* the listener!
*
* @param style
* The SWT styles for this text widget.
* @param injector
* For xtext dependency injection.
* @param contextResource
* A contextResource for xtext. May be null.
*/
public XtextStyledText(Composite parent, int style, Injector injector,
Resource context) {
this.style = style;
this.parent = parent;
if (injector == null)
throw new IllegalArgumentException("Injector must not be null!");
injector.injectMembers(this);
if (sourceViewerFactory == null)
throw new IllegalArgumentException(
"Dependency injection did not work!");
// create resource set
resourceSet = createXtextResourceSet();
// context may be null (can be passed in lazily as well)
if (context != null) {
setContextResource(context);
}
}
/**
* Creates decoration support for the sourceViewer. code is entirely copied
* from {@link XtextEditor} and its super class
* {@link AbstractDecoratedTextEditor}.
*
*/
private void configureSourceViewerDecorationSupport(
SourceViewerDecorationSupport support) {
MarkerAnnotationPreferences annotationPreferences = new MarkerAnnotationPreferences();
@SuppressWarnings("unchecked")
List<AnnotationPreference> prefs = annotationPreferences
.getAnnotationPreferences();
for (AnnotationPreference annotationPreference : prefs) {
support.setAnnotationPreference(annotationPreference);
}
support.setCharacterPairMatcher(characterPairMatcher);
support.setMatchingCharacterPainterPreferenceKeys(
BracketMatchingPreferencesInitializer.IS_ACTIVE_KEY,
BracketMatchingPreferencesInitializer.COLOR_KEY);
support.install(preferenceStoreAccess.getPreferenceStore());
}
protected void createContextFakeResource() {
// deep copy context resource contents, because simply loading the
// fakeResource will
// not reflect the current edit state, but the last saved state.
Resource contextResourceCopy = resourceSet
.createResource(contextResource.getURI());
contextResourceCopy.getContents().addAll(
EcoreUtil.copyAll(contextResource.getContents()));
resourceSet.getResources().add(contextResourceCopy);
}
private URI createFakeResourceBaseFragment(String activeProject) {
return URI.createPlatformResourceURI(activeProject + "/embedded", true);
}
private URI createFakeResourceUri(String activeProject) {
return createFakeResourceBaseFragment(activeProject)
.appendFileExtension(fileExtension);
}
/**
* Creates an {@link SourceViewer} and returns the {@link StyledText} widget
* of the viewer as the cell editors control. Some code is copied from
* {@link XtextEditor}.
*/
protected void createStyledText() {
// initialize contents of fake resource
initXtextFakeResource();
// connect xtext document to fake resource
initXtextDocument();
// connect xtext document to xtext source viewer
createXtextSourceViewer();
validationJob = createValidationJob();
document.setValidationJob(validationJob);
styledText = sourceviewer.getTextWidget();
styledText.addKeyListener(keyListener);
styledText.setFont(parent.getFont());
styledText.setBackground(parent.getBackground());
styledText.setText("");
}
private ValidationJob createValidationJob() {
return new ValidationJob(validator, document,
new AnnotationIssueProcessor(document, sourceviewer
.getAnnotationModel(), resolutionProvider),
CheckMode.ALL);
}
protected ResourceSet createXtextResourceSet() {
ResourceSet resourceSet = resourceSetProvider.get(getActiveProject());
return resourceSet;
}
protected void createXtextSourceViewer() {
sourceviewer = sourceViewerFactory.createSourceViewer(parent, null,
null, false, style);
sourceviewer.configure(configuration);
sourceviewer.setDocument(document, new AnnotationModel());
SourceViewerDecorationSupport support = new SourceViewerDecorationSupport(
sourceviewer, null, new DefaultMarkerAnnotationAccess(),
EditorsPlugin.getDefault().getSharedTextColors());
configureSourceViewerDecorationSupport(support);
}
public void dispose() {
styledText.removeKeyListener(keyListener);
document.disposeInput();
}
protected IProject getActiveProject() {
if (activeProject == null) {
ActiveProjectResolver activeProjectResolver = new ActiveProjectResolver();
Display.getDefault().syncExec(activeProjectResolver);
activeProject = activeProjectResolver.getResult();
}
return activeProject;
}
protected Resource getContextResource() {
return contextResource;
}
protected XtextDocument getDocument() {
return document;
}
protected XtextResource getFakeResource() {
return fakeResource;
}
protected String getFileExtension() {
return fileExtension;
}
public List<Issue> getIssues() {
return validationJob.createIssues(new NullProgressMonitor());
}
public IParseResult getParseResult() {
return document
.readOnly(new IUnitOfWork<IParseResult, XtextResource>() {
public IParseResult exec(XtextResource state)
throws Exception {
return state.getParseResult();
}
});
}
protected ResourceSet getResourceSet() {
return resourceSet;
}
protected XtextSourceViewer getSourceviewer() {
return sourceviewer;
}
/**
* @return The actual {@link StyledText} control.
*/
public StyledText getStyledText() {
if (styledText == null) {
createStyledText();
}
return styledText;
}
protected IResourceValidator getValidator() {
return validator;
}
private void initXtextDocument() {
document.setInput(fakeResource);
IDocumentPartitioner partitioner = documentPartitioner.get();
partitioner.connect(document);
document.setDocumentPartitioner(partitioner);
}
protected void initXtextFakeResource() {
// add the fake resource (add an uri to it, first)
String activeProject = getActiveProject().getName();
fakeResource.setURI(createFakeResourceUri(activeProject));
resourceSet.getResources().add(fakeResource);
}
public void resetVisibleRegion() {
sourceviewer.resetVisibleRegion();
}
/**
* Update the contextResource for the styled text.
*/
public void setContextResource(Resource contextResource) {
// remove any other resources that may have been created earlier
List<Resource> staleResources = new ArrayList<Resource>();
for (Resource r : resourceSet.getResources()) {
if (r != fakeResource) {
staleResources.add(r);
r.unload();
}
}
resourceSet.getResources().removeAll(staleResources);
// create context fake resource
if (contextResource != null) {
createContextFakeResource();
}
this.contextResource = contextResource;
}
public void setVisibleRegion(int start, int length) {
sourceviewer.setVisibleRegion(start, length);
}
} |
package org.phenoscape.ws.resource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.json.JSONException;
import org.json.JSONObject;
import org.phenoscape.obd.model.Phenotype;
import org.phenoscape.obd.model.PhenotypeVariationSet;
import org.phenoscape.obd.model.TaxonTerm;
import org.phenoscape.obd.model.Vocab.TTO;
import org.phenoscape.obd.query.AnnotationsQueryConfig;
import org.phenoscape.obd.query.QueryException;
import org.restlet.data.Status;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.ResourceException;
public class PhenotypeVariationResource extends AbstractPhenoscapeResource {
private String taxonID;
private boolean excludeGivenQuality;
private boolean excludeUnannotatedTaxa;
private AnnotationsQueryConfig phenotype;
@Override
protected void doInit() throws ResourceException {
super.doInit();
this.taxonID = this.getFirstQueryValue("taxon");
this.excludeGivenQuality = this.getBooleanQueryValue("exclude_attribute", true);
this.excludeUnannotatedTaxa = this.getBooleanQueryValue("exclude_unannotated", true);
try {
this.phenotype = this.initializeQueryConfig(this.getJSONQueryValue("query", new JSONObject()));
if (this.phenotype.getPhenotypes().size() != 1) {
log().error("Only one phenotype should be included.");
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Only one phenotype should be included.");
}
} catch (QueryException e) {
log().error("Incorrectly formatted phenotype query", e);
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, e);
} catch (JSONException e) {
log().error("Incorrectly formatted phenotype query", e);
throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, e);
}
}
@Get("json")
public Representation getJSONRepresentation() {
if ("suggest".equals(this.taxonID)) {
return this.getSuggestedTaxa();
} else {
try {
if (this.taxonID == null) {
this.taxonID = TTO.ROOT;
}
final Set<PhenotypeVariationSet> phenotypeSets = this.getDataStore().getPhenotypeSetsForChildren(taxonID, this.phenotype.getPhenotypes().get(0), false, this.excludeGivenQuality, this.excludeUnannotatedTaxa);
final JSONObject json = new JSONObject();
final List<JSONObject> jsonSets = new ArrayList<JSONObject>();
for (PhenotypeVariationSet variationSet : phenotypeSets) {
jsonSets.add(this.translate(variationSet));
}
json.put("phenotype_sets", jsonSets);
json.put("parent_taxon", this.taxonID);
return new JsonRepresentation(json);
} catch (SQLException e) {
log().error("Database error querying for phenotype variation", e);
this.setStatus(Status.SERVER_ERROR_INTERNAL, e);
return null;
} catch (JSONException e) {
log().error("Failed to create JSON object for phenotype variation", e);
this.setStatus(Status.SERVER_ERROR_INTERNAL, e);
return null;
}
}
}
private Representation getSuggestedTaxa() {
try {
//FIXME this is hardcoded to return the children of Otophysi
// this is just a stub result
final TaxonTerm parent = this.getDataStore().getTaxonTerm("TTO:352", true, false);
final JSONObject json = new JSONObject();
final List<JSONObject> taxa = new ArrayList<JSONObject>();
for (TaxonTerm taxon : parent.getChildren()) {
taxa.add(TermResourceUtil.translateMinimal(taxon));
}
json.put("taxa", taxa);
return new JsonRepresentation(json);
} catch (SQLException e) {
log().error("Database error querying for suggested taxa", e);
this.setStatus(Status.SERVER_ERROR_INTERNAL, e);
return null;
} catch (JSONException e) {
log().error("Failed to create JSON object for suggested taxa", e);
this.setStatus(Status.SERVER_ERROR_INTERNAL, e);
return null;
}
}
private JSONObject translate(PhenotypeVariationSet variationSet) throws JSONException {
final JSONObject json = new JSONObject();
json.put("taxa", variationSet.getTaxa());
final List<JSONObject> phenotypes = new ArrayList<JSONObject>();
for (Phenotype phenotype : variationSet.getPhenotypes()) {
phenotypes.add(this.translate(phenotype));
}
json.put("phenotypes", phenotypes);
return json;
}
private JSONObject translate(Phenotype phenotype) throws JSONException {
final JSONObject json = new JSONObject();
final JSONObject entity = TermResourceUtil.translateMinimal(phenotype.getEntity());
json.put("entity", entity);
final JSONObject quality = TermResourceUtil.translateMinimal(phenotype.getQuality());
json.put("quality", quality);
if (phenotype.getRelatedEntity() != null) {
final JSONObject relatedEntity = TermResourceUtil.translateMinimal(phenotype.getRelatedEntity());
json.put("related_entity", relatedEntity);
}
return json;
}
} |
package org.chtijbug.drools.platform.web;
import com.google.common.base.Function;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.chtijbug.drools.platform.persistence.PlatformRuntimeInstanceRepository;
import org.chtijbug.drools.platform.persistence.SessionExecutionRepository;
import org.chtijbug.drools.platform.persistence.pojo.*;
import org.chtijbug.drools.platform.web.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Nullable;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.Arrays;
import java.util.List;
@Controller
@RequestMapping(value = "/runtime")
public class RuntimeResource {
private static Logger logger = LoggerFactory.getLogger(RuntimeResource.class);
@Autowired
PlatformRuntimeInstanceRepository platformRuntimeInstanceRepository;
@Autowired
SessionExecutionRepository sessionExecutionRepository;
@RequestMapping(method = RequestMethod.GET, value = "/{packageName:.+}")
@Consumes(value = MediaType.APPLICATION_JSON)
@Produces(value = MediaType.APPLICATION_JSON)
@ResponseBody
@Transactional
public List<RuntimeInstance> findActivePlatformRuntimeInstance(@PathVariable String packageName) {
return Lists.transform(platformRuntimeInstanceRepository.findByPackageNameActiveRuntime(packageName),
new Function<PlatformRuntimeInstance, RuntimeInstance>() {
@Nullable
@Override
public RuntimeInstance apply(@Nullable PlatformRuntimeInstance platformRuntimeInstance) {
String url = "http://" + platformRuntimeInstance.getHostname() + ":" + platformRuntimeInstance.getPort() + platformRuntimeInstance.getEndPoint();
String rulePackage = null;
String version = null;
PlatformRuntimeDefinition platformRuntimeDefinition = platformRuntimeInstance.getPlatformRuntimeDefinition();
if (!platformRuntimeDefinition.getDroolsRessourcesDefinition().isEmpty()) {
DroolsResource guvnorResource = platformRuntimeDefinition.getDroolsRessourcesDefinition().get(0);
rulePackage = guvnorResource.getGuvnor_packageName();
version = guvnorResource.getGuvnor_packageVersion();
}
return new RuntimeInstance(platformRuntimeInstance.getId(), platformRuntimeInstance.getRuleBaseID(), url, rulePackage, version);
}
}
);
}
@RequestMapping(method = RequestMethod.GET, value = "/all/{packageName:.+}")
@Consumes(value = MediaType.APPLICATION_JSON)
@Produces(value = MediaType.APPLICATION_JSON)
@ResponseBody
public List<PlatformRuntimeInstance> findAllPlatformRuntimeInstance(@PathVariable String packageName) {
return platformRuntimeInstanceRepository.findByPackageNameAllRuntime(packageName);
}
@RequestMapping(method = RequestMethod.GET, value = "/session/{ruleBaseID:.+}/{sessionId:.+}")
@Consumes(value = MediaType.APPLICATION_JSON)
@Produces(value = MediaType.APPLICATION_JSON)
@ResponseBody
public SessionExecutionDetailsResource findSessionExecutionDetails(@PathVariable int ruleBaseID, @PathVariable int sessionId) {
logger.debug(">> findSessionExecutionDetails(sessionId= {})", sessionId);
try {
final SessionExecution sessionExecution = sessionExecutionRepository.findByRuleBaseIDAndSessionIdAndEndDateIsNull(ruleBaseID, sessionId);
// final SessionExecution sessionExecution = sessionExecutionRepository.findDetailsBySessionId(sessionID);
SessionExecutionDetailsResource executionDetailsResource = new SessionExecutionDetailsResource();
ProcessExecution processExecution = sessionExecution.getProcessExecutions().get(0);
ProcessDetails processDetails = new ProcessDetails();
List<Fact> inputFactList = Lists.newArrayList(sessionExecution.getFactsByType(FactType.INPUTDATA));
List<Fact> outputFactList = Lists.newArrayList(sessionExecution.getFactsByType(FactType.OUTPUTDATA));
if (sessionExecution.getProcessExecutions().size() != 0) {
processDetails.setProcessName(processExecution.getProcessName());
if (processExecution.getProcessVersion() != null) {
processDetails.setProcessVersion(processExecution.getProcessVersion());
} else {
processDetails.setProcessVersion("");
}
processDetails.setProcessExecutionStatus(processExecution.getProcessExecutionStatus().toString());
processDetails.setProcessType(processExecution.getProcessType());
executionDetailsResource.setProcessDetails(processDetails);
for (RuleflowGroup ruleFlowGroup : processExecution.getRuleflowGroups()) {
RuleFlowGroupDetails ruleFlowGroupDetails = new RuleFlowGroupDetails();
ruleFlowGroupDetails.setRuleflowGroup(ruleFlowGroup.getRuleflowGroup());
for (RuleExecution ruleExecution : ruleFlowGroup.getRuleExecutionList()) {
RuleExecutionDetails ruleExecutionDetails = new RuleExecutionDetails();
ruleExecutionDetails.setPackageName(ruleExecution.getPackageName());
ruleExecutionDetails.setRuleName(ruleExecution.getRuleName());
ruleExecutionDetails.setWhenFacts(ruleExecution.getWhenFacts());
ruleExecutionDetails.setThenFacts(ruleExecution.getThenFacts());
ruleFlowGroupDetails.addRuleExecution(ruleExecutionDetails); //Ajout de la ruleExecutionDetails dans la liste
}
executionDetailsResource.addRuleFlowGroup(ruleFlowGroupDetails);
}
for (Fact inputFact : inputFactList) {
executionDetailsResource.setInputObject(inputFact.getJsonFact());
}
for (Fact outputFact : outputFactList) {
executionDetailsResource.setOutputObject(outputFact.getJsonFact());
}
//logger.debug("Skipping this entry {}", sessionId);
}
return executionDetailsResource;
} finally {
logger.debug("<< findSessionExecutionDetails()");
}
}
@RequestMapping(method = RequestMethod.POST, value = "/filter")
@Consumes(MediaType.APPLICATION_JSON)
@ResponseBody
public List<SessionExecutionResource> findPlatformRuntimeInstanceByFilters(@RequestBody final PlatformRuntimeFilter runtimeFilter) {
logger.debug(">> findAllPlatformRuntimeInstanceByFilter(runtimeFilter= {})", runtimeFilter);
try {
final List<SessionExecution> allSessionExecutions = platformRuntimeInstanceRepository.findAllPlatformRuntimeInstanceByFilter(runtimeFilter);
List<SessionExecutionResource> result = Lists.transform(allSessionExecutions, new Function<SessionExecution, SessionExecutionResource>() {
@Nullable
@Override
public SessionExecutionResource apply(@Nullable SessionExecution sessionExecution) {
// TODO
SessionExecutionResource output = new SessionExecutionResource();
PlatformRuntimeInstance runtimeInstance = sessionExecution.getPlatformRuntimeInstance();
DroolsResource guvnorResource = sessionExecution.getPlatformRuntimeInstance().getPlatformRuntimeDefinition().getDroolsRessourcesDefinition().get(0);
assert sessionExecution != null;
output.setRuleBaseID(sessionExecution.getPlatformRuntimeInstance().getRuleBaseID());
output.setSessionId(sessionExecution.getSessionId());
if (guvnorResource.getEndDate() == null) {
String guvnorUrl = guvnorResource.getGuvnor_url() + guvnorResource.getGuvnor_appName();
output.setGuvnorUrl(guvnorUrl);
output.setRulePackage(guvnorResource.getGuvnor_packageName());
output.setVersion(guvnorResource.getGuvnor_packageVersion());
}
output.setRuntimeURL(runtimeInstance.getHostname() + ":" + runtimeInstance.getPort() + runtimeInstance.getEndPoint());
output.setHostname(runtimeInstance.getHostname() + ":" + runtimeInstance.getPort() + runtimeInstance.getEndPoint());
output.setStatus(runtimeInstance.getStatus().toString());
//output.setStatus(sessionExecution.getSessionExecutionStatus().toString());
output.setStartDate(sessionExecution.getStartDate().toString());
//sessionExecution.getFacts();
if (sessionExecution.getEndDate() != null)
output.setEndDate(sessionExecution.getEndDate().toString());
return output;
}
});
return Lists.newArrayList(Iterables.filter(result, Predicates.notNull()));
} finally {
logger.debug("<< findAllPlatformRuntimeInstanceByFilter()");
}
}
@RequestMapping(method = RequestMethod.GET, value = "/all/statuses")
@Produces(value = MediaType.APPLICATION_JSON)
@ResponseBody
public List<RuntimeStatusObject> getAllStatuses() {
RuntimeStatusObject initmode = new RuntimeStatusObject(PlatformRuntimeInstanceStatus.INITMODE, "INITMODE");
RuntimeStatusObject started = new RuntimeStatusObject(PlatformRuntimeInstanceStatus.STARTED, "STARTED");
RuntimeStatusObject notJoignable = new RuntimeStatusObject(PlatformRuntimeInstanceStatus.NOT_JOINGNABLE, "NOT_JOIGNABLE");
RuntimeStatusObject stopped = new RuntimeStatusObject(PlatformRuntimeInstanceStatus.STOPPED, "STOPPED");
RuntimeStatusObject crashed = new RuntimeStatusObject(PlatformRuntimeInstanceStatus.CRASHED, "CRASHED");
return Arrays.asList(initmode, started, notJoignable, stopped, crashed);
}
} |
package org.zstack.kvm;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestClientException;
import org.springframework.web.util.UriComponentsBuilder;
import org.zstack.compute.cluster.ClusterGlobalConfig;
import org.zstack.compute.host.HostBase;
import org.zstack.compute.host.HostGlobalConfig;
import org.zstack.compute.host.HostSystemTags;
import org.zstack.compute.host.MigrateNetworkExtensionPoint;
import org.zstack.compute.vm.*;
import org.zstack.core.CoreGlobalProperty;
import org.zstack.core.MessageCommandRecorder;
import org.zstack.core.Platform;
import org.zstack.core.agent.AgentConstant;
import org.zstack.core.ansible.*;
import org.zstack.core.cloudbus.CloudBusCallBack;
import org.zstack.core.cloudbus.CloudBusGlobalProperty;
import org.zstack.core.componentloader.PluginRegistry;
import org.zstack.core.db.Q;
import org.zstack.core.db.SimpleQuery;
import org.zstack.core.db.SimpleQuery.Op;
import org.zstack.core.thread.*;
import org.zstack.core.timeout.ApiTimeoutManager;
import org.zstack.core.workflow.FlowChainBuilder;
import org.zstack.core.workflow.ShareFlow;
import org.zstack.header.Constants;
import org.zstack.header.allocator.HostAllocatorConstant;
import org.zstack.header.cluster.ClusterVO;
import org.zstack.header.cluster.ReportHostCapacityMessage;
import org.zstack.header.core.*;
import org.zstack.header.core.progress.TaskProgressRange;
import org.zstack.header.core.workflow.*;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.errorcode.ErrorCodeList;
import org.zstack.header.errorcode.OperationFailureException;
import org.zstack.header.errorcode.SysErrors;
import org.zstack.header.exception.CloudRuntimeException;
import org.zstack.header.host.*;
import org.zstack.header.host.MigrateVmOnHypervisorMsg.StorageMigrationPolicy;
import org.zstack.header.image.ImageBootMode;
import org.zstack.header.image.ImagePlatform;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.Message;
import org.zstack.header.message.MessageReply;
import org.zstack.header.message.NeedReplyMessage;
import org.zstack.header.network.l2.*;
import org.zstack.header.network.l3.L3NetworkInventory;
import org.zstack.header.network.l3.L3NetworkVO;
import org.zstack.header.rest.JsonAsyncRESTCallback;
import org.zstack.header.rest.RESTFacade;
import org.zstack.header.storage.primary.*;
import org.zstack.header.storage.snapshot.VolumeSnapshotInventory;
import org.zstack.header.tag.SystemTagInventory;
import org.zstack.header.vm.*;
import org.zstack.header.volume.VolumeInventory;
import org.zstack.header.volume.VolumeType;
import org.zstack.header.volume.VolumeVO;
import org.zstack.kvm.KVMAgentCommands.*;
import org.zstack.kvm.KVMConstant.KvmVmState;
import org.zstack.network.l3.NetworkGlobalProperty;
import org.zstack.resourceconfig.ResourceConfig;
import org.zstack.resourceconfig.ResourceConfigFacade;
import org.zstack.tag.SystemTag;
import org.zstack.tag.SystemTagCreator;
import org.zstack.tag.TagManager;
import org.zstack.utils.*;
import org.zstack.utils.gson.JSONObjectUtil;
import org.zstack.utils.logging.CLogger;
import org.zstack.utils.network.NetworkUtils;
import org.zstack.utils.path.PathUtil;
import org.zstack.utils.ssh.Ssh;
import org.zstack.utils.ssh.SshException;
import org.zstack.utils.ssh.SshResult;
import org.zstack.utils.ssh.SshShell;
import org.zstack.utils.tester.ZTester;
import javax.persistence.TypedQuery;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static org.zstack.core.Platform.*;
import static org.zstack.core.progress.ProgressReportService.*;
import static org.zstack.kvm.KVMHostFactory.allGuestOsCharacter;
import static org.zstack.utils.CollectionDSL.e;
import static org.zstack.utils.CollectionDSL.map;
import static org.zstack.utils.StringDSL.ln;
public class KVMHost extends HostBase implements Host {
private static final CLogger logger = Utils.getLogger(KVMHost.class);
private static final ZTester tester = Utils.getTester();
@Autowired
@Qualifier("KVMHostFactory")
private KVMHostFactory factory;
@Autowired
private RESTFacade restf;
@Autowired
private KVMExtensionEmitter extEmitter;
@Autowired
private TagManager tagmgr;
@Autowired
private ApiTimeoutManager timeoutManager;
@Autowired
private PluginRegistry pluginRegistry;
@Autowired
private ThreadFacade thdf;
@Autowired
private AnsibleFacade asf;
@Autowired
private ResourceConfigFacade rcf;
@Autowired
private DeviceBootOrderOperator deviceBootOrderOperator;
@Autowired
private VmNicManager nicManager;
private KVMHostContext context;
// ///////////////////// REST URL //////////////////////////
private String baseUrl;
private String connectPath;
private String pingPath;
private String updateHostConfigurationPath;
private String checkPhysicalNetworkInterfacePath;
private String startVmPath;
private String stopVmPath;
private String pauseVmPath;
private String resumeVmPath;
private String rebootVmPath;
private String destroyVmPath;
private String attachDataVolumePath;
private String detachDataVolumePath;
private String echoPath;
private String attachNicPath;
private String detachNicPath;
private String migrateVmPath;
private String snapshotPath;
private String mergeSnapshotPath;
private String hostFactPath;
private String attachIsoPath;
private String detachIsoPath;
private String updateNicPath;
private String checkVmStatePath;
private String getConsolePortPath;
private String onlineIncreaseCpuPath;
private String onlineIncreaseMemPath;
private String deleteConsoleFirewall;
private String updateHostOSPath;
private String updateDependencyPath;
private String shutdownHost;
private String updateVmPriorityPath;
private String updateSpiceChannelConfigPath;
private String cancelJob;
private String getVmFirstBootDevicePath;
private String getVmDeviceAddressPath;
private String scanVmPortPath;
private String getDevCapacityPath;
private String configPrimaryVmPath;
private String configSecondaryVmPath;
private String startColoSyncPath;
private String registerPrimaryVmHeartbeatPath;
private String agentPackageName = KVMGlobalProperty.AGENT_PACKAGE_NAME;
private String hostTakeOverFlagPath = KVMGlobalProperty.TAKEVOERFLAGPATH;
public KVMHost(KVMHostVO self, KVMHostContext context) {
super(self);
this.context = context;
baseUrl = context.getBaseUrl();
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_CONNECT_PATH);
connectPath = ub.build().toUriString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_PING_PATH);
pingPath = ub.build().toUriString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_UPDATE_HOST_CONFIGURATION_PATH);
updateHostConfigurationPath = ub.build().toUriString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_CHECK_PHYSICAL_NETWORK_INTERFACE_PATH);
checkPhysicalNetworkInterfacePath = ub.build().toUriString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_START_VM_PATH);
startVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_STOP_VM_PATH);
stopVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_PAUSE_VM_PATH);
pauseVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_RESUME_VM_PATH);
resumeVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_REBOOT_VM_PATH);
rebootVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DESTROY_VM_PATH);
destroyVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_ATTACH_VOLUME);
attachDataVolumePath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DETACH_VOLUME);
detachDataVolumePath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_ECHO_PATH);
echoPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_ATTACH_NIC_PATH);
attachNicPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DETACH_NIC_PATH);
detachNicPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_MIGRATE_VM_PATH);
migrateVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_TAKE_VOLUME_SNAPSHOT_PATH);
snapshotPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_MERGE_SNAPSHOT_PATH);
mergeSnapshotPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_HOST_FACT_PATH);
hostFactPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_ATTACH_ISO_PATH);
attachIsoPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DETACH_ISO_PATH);
detachIsoPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_UPDATE_NIC_PATH);
updateNicPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_VM_CHECK_STATE);
checkVmStatePath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_GET_VNC_PORT_PATH);
getConsolePortPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_VM_ONLINE_INCREASE_CPU);
onlineIncreaseCpuPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_VM_ONLINE_INCREASE_MEMORY);
onlineIncreaseMemPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_DELETE_CONSOLE_FIREWALL_PATH);
deleteConsoleFirewall = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_UPDATE_HOST_OS_PATH);
updateHostOSPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_HOST_UPDATE_DEPENDENCY_PATH);
updateDependencyPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.HOST_SHUTDOWN);
shutdownHost = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_VM_UPDATE_PRIORITY_PATH);
updateVmPriorityPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.HOST_UPDATE_SPICE_CHANNEL_CONFIG_PATH);
updateSpiceChannelConfigPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(AgentConstant.CANCEL_JOB);
cancelJob = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_GET_VM_FIRST_BOOT_DEVICE_PATH);
getVmFirstBootDevicePath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.GET_VM_DEVICE_ADDRESS_PATH);
getVmDeviceAddressPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_SCAN_VM_PORT_STATUS);
scanVmPortPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.GET_DEV_CAPACITY);
getDevCapacityPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_CONFIG_PRIMARY_VM_PATH);
configPrimaryVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_CONFIG_SECONDARY_VM_PATH);
configSecondaryVmPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_START_COLO_SYNC_PATH);
startColoSyncPath = ub.build().toString();
ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.path(KVMConstant.KVM_REGISTER_PRIMARY_VM_HEARTBEAT);
registerPrimaryVmHeartbeatPath = ub.build().toString();
}
class Http<T> {
String path;
AgentCommand cmd;
Class<T> responseClass;
String commandStr;
public Http(String path, String cmd, Class<T> rspClz) {
this.path = path;
this.commandStr = cmd;
this.responseClass = rspClz;
}
public Http(String path, AgentCommand cmd, Class<T> rspClz) {
this.path = path;
this.cmd = cmd;
this.responseClass = rspClz;
}
void call(ReturnValueCompletion<T> completion) {
call(null, completion);
}
void call(String resourceUuid, ReturnValueCompletion<T> completion) {
Map<String, String> header = new HashMap<>();
header.put(Constants.AGENT_HTTP_HEADER_RESOURCE_UUID, resourceUuid == null ? self.getUuid() : resourceUuid);
runBeforeAsyncJsonPostExts(header);
if (commandStr != null) {
restf.asyncJsonPost(path, commandStr, header, new JsonAsyncRESTCallback<T>(completion) {
@Override
public void fail(ErrorCode err) {
completion.fail(err);
}
@Override
public void success(T ret) {
if (dbf.isExist(self.getUuid(), HostVO.class)) {
completion.success(ret);
} else {
completion.fail(operr("host[uuid:%s] has been deleted", self.getUuid()));
}
}
@Override
public Class<T> getReturnClass() {
return responseClass;
}
}, TimeUnit.MILLISECONDS, timeoutManager.getTimeout());
} else {
restf.asyncJsonPost(path, cmd, header, new JsonAsyncRESTCallback<T>(completion) {
@Override
public void fail(ErrorCode err) {
completion.fail(err);
}
@Override
public void success(T ret) {
if (dbf.isExist(self.getUuid(), HostVO.class)) {
completion.success(ret);
} else {
completion.fail(operr("host[uuid:%s] has been deleted", self.getUuid()));
}
}
@Override
public Class<T> getReturnClass() {
return responseClass;
}
}); // DO NOT pass unit, timeout here, they are null
}
}
void runBeforeAsyncJsonPostExts(Map<String, String> header) {
if (commandStr == null) {
commandStr = JSONObjectUtil.toJsonString(cmd);
}
if (commandStr == null || commandStr.isEmpty()) {
logger.warn(String.format("commandStr is empty, path: %s, header: %s", path, header));
return;
}
LinkedHashMap commandMap = JSONObjectUtil.toObject(commandStr, LinkedHashMap.class);
LinkedHashMap kvmHostAddon = new LinkedHashMap();
for (KVMBeforeAsyncJsonPostExtensionPoint extp : pluginRegistry.getExtensionList(KVMBeforeAsyncJsonPostExtensionPoint.class)) {
LinkedHashMap tmpHashMap = extp.kvmBeforeAsyncJsonPostExtensionPoint(path, commandMap, header);
if (tmpHashMap != null && !tmpHashMap.isEmpty()) {
tmpHashMap.keySet().stream().forEachOrdered((key -> {
kvmHostAddon.put(key, tmpHashMap.get(key));
}));
}
}
if (commandStr.equals("{}")) {
commandStr = commandStr.replaceAll("\\}$",
String.format("\"%s\":%s}", KVMConstant.KVM_HOST_ADDONS, JSONObjectUtil.toJsonString(kvmHostAddon)));
} else {
commandStr = commandStr.replaceAll("\\}$",
String.format(",\"%s\":%s}", KVMConstant.KVM_HOST_ADDONS, JSONObjectUtil.toJsonString(kvmHostAddon)));
}
}
}
@Override
protected void handleApiMessage(APIMessage msg) {
super.handleApiMessage(msg);
}
@Override
protected void handleLocalMessage(Message msg) {
if (msg instanceof CheckNetworkPhysicalInterfaceMsg) {
handle((CheckNetworkPhysicalInterfaceMsg) msg);
} else if (msg instanceof BatchCheckNetworkPhysicalInterfaceMsg) {
handle((BatchCheckNetworkPhysicalInterfaceMsg) msg);
} else if (msg instanceof StartVmOnHypervisorMsg) {
handle((StartVmOnHypervisorMsg) msg);
} else if (msg instanceof CreateVmOnHypervisorMsg) {
handle((CreateVmOnHypervisorMsg) msg);
} else if (msg instanceof UpdateSpiceChannelConfigMsg) {
handle((UpdateSpiceChannelConfigMsg) msg);
} else if (msg instanceof StopVmOnHypervisorMsg) {
handle((StopVmOnHypervisorMsg) msg);
} else if (msg instanceof RebootVmOnHypervisorMsg) {
handle((RebootVmOnHypervisorMsg) msg);
} else if (msg instanceof DestroyVmOnHypervisorMsg) {
handle((DestroyVmOnHypervisorMsg) msg);
} else if (msg instanceof AttachVolumeToVmOnHypervisorMsg) {
handle((AttachVolumeToVmOnHypervisorMsg) msg);
} else if (msg instanceof DetachVolumeFromVmOnHypervisorMsg) {
handle((DetachVolumeFromVmOnHypervisorMsg) msg);
} else if (msg instanceof VmAttachNicOnHypervisorMsg) {
handle((VmAttachNicOnHypervisorMsg) msg);
} else if (msg instanceof VmUpdateNicOnHypervisorMsg) {
handle((VmUpdateNicOnHypervisorMsg) msg);
} else if (msg instanceof MigrateVmOnHypervisorMsg) {
handle((MigrateVmOnHypervisorMsg) msg);
} else if (msg instanceof TakeSnapshotOnHypervisorMsg) {
handle((TakeSnapshotOnHypervisorMsg) msg);
} else if (msg instanceof MergeVolumeSnapshotOnKvmMsg) {
handle((MergeVolumeSnapshotOnKvmMsg) msg);
} else if (msg instanceof KVMHostAsyncHttpCallMsg) {
handle((KVMHostAsyncHttpCallMsg) msg);
} else if (msg instanceof KVMHostSyncHttpCallMsg) {
handle((KVMHostSyncHttpCallMsg) msg);
} else if (msg instanceof DetachNicFromVmOnHypervisorMsg) {
handle((DetachNicFromVmOnHypervisorMsg) msg);
} else if (msg instanceof AttachIsoOnHypervisorMsg) {
handle((AttachIsoOnHypervisorMsg) msg);
} else if (msg instanceof DetachIsoOnHypervisorMsg) {
handle((DetachIsoOnHypervisorMsg) msg);
} else if (msg instanceof CheckVmStateOnHypervisorMsg) {
handle((CheckVmStateOnHypervisorMsg) msg);
} else if (msg instanceof UpdateVmPriorityMsg) {
handle((UpdateVmPriorityMsg) msg);
} else if (msg instanceof GetVmConsoleAddressFromHostMsg) {
handle((GetVmConsoleAddressFromHostMsg) msg);
} else if (msg instanceof KvmRunShellMsg) {
handle((KvmRunShellMsg) msg);
} else if (msg instanceof VmDirectlyDestroyOnHypervisorMsg) {
handle((VmDirectlyDestroyOnHypervisorMsg) msg);
} else if (msg instanceof IncreaseVmCpuMsg) {
handle((IncreaseVmCpuMsg) msg);
} else if (msg instanceof IncreaseVmMemoryMsg) {
handle((IncreaseVmMemoryMsg) msg);
} else if (msg instanceof PauseVmOnHypervisorMsg) {
handle((PauseVmOnHypervisorMsg) msg);
} else if (msg instanceof ResumeVmOnHypervisorMsg) {
handle((ResumeVmOnHypervisorMsg) msg);
} else if (msg instanceof GetKVMHostDownloadCredentialMsg) {
handle((GetKVMHostDownloadCredentialMsg) msg);
} else if (msg instanceof ShutdownHostMsg) {
handle((ShutdownHostMsg) msg);
} else if (msg instanceof CancelHostTaskMsg) {
handle((CancelHostTaskMsg) msg);
} else if (msg instanceof GetVmFirstBootDeviceOnHypervisorMsg) {
handle((GetVmFirstBootDeviceOnHypervisorMsg) msg);
} else if (msg instanceof GetVmDeviceAddressMsg) {
handle((GetVmDeviceAddressMsg) msg);
} else if (msg instanceof CheckHostCapacityMsg) {
handle((CheckHostCapacityMsg) msg);
} else if (msg instanceof ConfigPrimaryVmMsg) {
handle((ConfigPrimaryVmMsg) msg);
} else if (msg instanceof ConfigSecondaryVmMsg) {
handle((ConfigSecondaryVmMsg) msg);
} else if (msg instanceof StartColoSyncMsg) {
handle((StartColoSyncMsg) msg);
} else if (msg instanceof RegisterColoPrimaryCheckMsg) {
handle((RegisterColoPrimaryCheckMsg) msg);
} else {
super.handleLocalMessage(msg);
}
}
private void handle(CheckHostCapacityMsg msg) {
CheckHostCapacityReply re = new CheckHostCapacityReply();
KVMHostAsyncHttpCallMsg kmsg = new KVMHostAsyncHttpCallMsg();
kmsg.setHostUuid(msg.getHostUuid());
kmsg.setPath(KVMConstant.KVM_HOST_CAPACITY_PATH);
kmsg.setNoStatusCheck(true);
kmsg.setCommand(new HostCapacityCmd());
bus.makeTargetServiceIdByResourceUuid(kmsg, HostConstant.SERVICE_ID, msg.getHostUuid());
bus.send(kmsg, new CloudBusCallBack(msg) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
throw new OperationFailureException(operr("check host capacity failed, because:%s", reply.getError()));
}
KVMHostAsyncHttpCallReply r = reply.castReply();
HostCapacityResponse rsp = r.toResponse(HostCapacityResponse.class);
if (!rsp.isSuccess()) {
throw new OperationFailureException(operr("operation error, because:%s", rsp.getError()));
}
long reservedSize = SizeUtils.sizeStringToBytes(rcf.getResourceConfigValue(KVMGlobalConfig.RESERVED_MEMORY_CAPACITY, msg.getHostUuid(), String.class));
if (rsp.getTotalMemory() < reservedSize) {
throw new OperationFailureException(operr("The host[uuid:%s]'s available memory capacity[%s] is lower than the reserved capacity[%s]",
msg.getHostUuid(), rsp.getTotalMemory(), reservedSize));
}
ReportHostCapacityMessage rmsg = new ReportHostCapacityMessage();
rmsg.setHostUuid(msg.getHostUuid());
rmsg.setCpuNum((int) rsp.getCpuNum());
rmsg.setUsedCpu(rsp.getUsedCpu());
rmsg.setTotalMemory(rsp.getTotalMemory());
rmsg.setUsedMemory(rsp.getUsedMemory());
rmsg.setCpuSockets(rsp.getCpuSockets());
rmsg.setServiceId(bus.makeLocalServiceId(HostAllocatorConstant.SERVICE_ID));
bus.send(rmsg, new CloudBusCallBack(msg) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
re.setError(reply.getError());
}
bus.reply(msg, re);
}
});
}
});
}
private void handle(RegisterColoPrimaryCheckMsg msg) {
inQueue().name(String.format("register-vm-heart-beat-on-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> registerPrimaryVmHeartbeat(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void registerPrimaryVmHeartbeat(RegisterColoPrimaryCheckMsg msg, NoErrorCompletion completion) {
RegisterPrimaryVmHeartbeatCmd cmd = new RegisterPrimaryVmHeartbeatCmd();
cmd.setHostUuid(msg.getHostUuid());
cmd.setVmInstanceUuid(msg.getVmInstanceUuid());
cmd.setHeartbeatPort(msg.getHeartbeatPort());
cmd.setTargetHostIp(msg.getTargetHostIp());
cmd.setColoPrimary(msg.isColoPrimary());
cmd.setRedirectNum(msg.getRedirectNum());
VmInstanceVO vm = dbf.findByUuid(msg.getVmInstanceUuid(), VmInstanceVO.class);
List<VolumeInventory> volumes = vm.getAllVolumes().stream().filter(v -> v.getType() == VolumeType.Data || v.getType() == VolumeType.Root).map(VolumeInventory::valueOf).collect(Collectors.toList());
cmd.setVolumes(VolumeTO.valueOf(volumes, KVMHostInventory.valueOf(getSelf())));
new Http<>(registerPrimaryVmHeartbeatPath, cmd, AgentResponse.class).call(new ReturnValueCompletion<AgentResponse>(msg, completion) {
@Override
public void success(AgentResponse ret) {
final StartColoSyncReply reply = new StartColoSyncReply();
if (!ret.isSuccess()) {
reply.setError(operr("unable to register colo heartbeat for vm[uuid:%s] on kvm host [uuid:%s, ip:%s], because %s",
msg.getVmInstanceUuid(), self.getUuid(), self.getManagementIp(), ret.getError()));
} else {
logger.debug(String.format("unable to register colo heartbeat for vm[uuid:%s] on kvm host[uuid:%s] success", msg.getVmInstanceUuid(), self.getUuid()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
final StartColoSyncReply reply = new StartColoSyncReply();
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(StartColoSyncMsg msg) {
inQueue().name(String.format("start-colo-sync-vm-%s-on-%s", msg.getVmInstanceUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> startColoSync(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void startColoSync(StartColoSyncMsg msg, NoErrorCompletion completion) {
StartColoSyncCmd cmd = new StartColoSyncCmd();
cmd.setVmInstanceUuid(msg.getVmInstanceUuid());
cmd.setBlockReplicationPort(msg.getBlockReplicationPort());
cmd.setNbdServerPort(msg.getNbdServerPort());
cmd.setSecondaryVmHostIp(msg.getSecondaryVmHostIp());
cmd.setCheckpointDelay(msg.getCheckpointDelay());
cmd.setFullSync(msg.isFullSync());
cmd.setNicNumber(msg.getNicNumber());
VmInstanceVO vm = dbf.findByUuid(msg.getVmInstanceUuid(), VmInstanceVO.class);
List<VolumeInventory> volumes = vm.getAllVolumes().stream().filter(v -> v.getType() == VolumeType.Data || v.getType() == VolumeType.Root).map(VolumeInventory::valueOf).collect(Collectors.toList());
cmd.setVolumes(VolumeTO.valueOf(volumes, KVMHostInventory.valueOf(getSelf())));
new Http<>(startColoSyncPath, cmd, AgentResponse.class).call(new ReturnValueCompletion<AgentResponse>(msg, completion) {
@Override
public void success(AgentResponse ret) {
final StartColoSyncReply reply = new StartColoSyncReply();
if (!ret.isSuccess()) {
reply.setError(operr("unable to start colo sync vm[uuid:%s] on kvm host [uuid:%s, ip:%s], because %s",
msg.getVmInstanceUuid(), self.getUuid(), self.getManagementIp(), ret.getError()));
} else {
logger.debug(String.format("unable to start colo sync vm[uuid:%s] on kvm host[uuid:%s] success", msg.getVmInstanceUuid(), self.getUuid()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
final StartColoSyncReply reply = new StartColoSyncReply();
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(ConfigSecondaryVmMsg msg) {
inQueue().name(String.format("config-secondary-vm-%s-on-%s", msg.getVmInstanceUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> configSecondaryVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void handle(ConfigPrimaryVmMsg msg) {
inQueue().name(String.format("config-primary-vm-%s-on-%s", msg.getVmInstanceUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> configPrimaryVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void configSecondaryVm(ConfigSecondaryVmMsg msg, NoErrorCompletion completion) {
checkStatus();
ConfigSecondaryVmCmd cmd = new ConfigSecondaryVmCmd();
cmd.setVmInstanceUuid(msg.getVmInstanceUuid());
cmd.setPrimaryVmHostIp(msg.getPrimaryVmHostIp());
cmd.setNbdServerPort(msg.getNbdServerPort());
new Http<>(configSecondaryVmPath, cmd, AgentResponse.class).call(new ReturnValueCompletion<AgentResponse>(msg, completion) {
@Override
public void success(AgentResponse ret) {
final ConfigPrimaryVmReply reply = new ConfigPrimaryVmReply();
if (!ret.isSuccess()) {
reply.setError(operr("unable to config secondary vm[uuid:%s] on kvm host [uuid:%s, ip:%s], because %s",
msg.getVmInstanceUuid(), self.getUuid(), self.getManagementIp(), ret.getError()));
} else {
logger.debug(String.format("config secondary vm[uuid:%s] on kvm host[uuid:%s] success", msg.getVmInstanceUuid(), self.getUuid()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
final ConfigPrimaryVmReply reply = new ConfigPrimaryVmReply();
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void configPrimaryVm(ConfigPrimaryVmMsg msg, NoErrorCompletion completion) {
checkStatus();
ConfigPrimaryVmCmd cmd = new ConfigPrimaryVmCmd();
cmd.setConfigs(msg.getConfigs().stream().sorted(Comparator.comparing(VmNicRedirectConfig::getDeviceId)).collect(Collectors.toList()));
cmd.setHostIp(msg.getHostIp());
cmd.setVmInstanceUuid(msg.getVmInstanceUuid());
new Http<>(configPrimaryVmPath, cmd, AgentResponse.class).call(new ReturnValueCompletion<AgentResponse>(msg, completion) {
@Override
public void success(AgentResponse ret) {
final ConfigPrimaryVmReply reply = new ConfigPrimaryVmReply();
if (!ret.isSuccess()) {
reply.setError(operr("unable to config primary vm[uuid:%s] on kvm host [uuid:%s, ip:%s], because %s",
msg.getVmInstanceUuid(), self.getUuid(), self.getManagementIp(), ret.getError()));
} else {
logger.debug(String.format("config primary vm[uuid:%s] on kvm host[uuid:%s] success", msg.getVmInstanceUuid(), self.getUuid()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
final ConfigPrimaryVmReply reply = new ConfigPrimaryVmReply();
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(GetVmFirstBootDeviceOnHypervisorMsg msg) {
inQueue().name(String.format("get-first-boot-device-of-vm-%s-on-kvm-%s", msg.getVmInstanceUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> getVmFirstBootDevice(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void getVmFirstBootDevice(final GetVmFirstBootDeviceOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
GetVmFirstBootDeviceCmd cmd = new GetVmFirstBootDeviceCmd();
cmd.setUuid(msg.getVmInstanceUuid());
new Http<>(getVmFirstBootDevicePath, cmd, GetVmFirstBootDeviceResponse.class).call(new ReturnValueCompletion<GetVmFirstBootDeviceResponse>(msg, completion) {
@Override
public void success(GetVmFirstBootDeviceResponse ret) {
final GetVmFirstBootDeviceOnHypervisorReply reply = new GetVmFirstBootDeviceOnHypervisorReply();
if (!ret.isSuccess()) {
reply.setError(operr("unable to get first boot dev of vm[uuid:%s] on kvm host [uuid:%s, ip:%s], because %s",
msg.getVmInstanceUuid(), self.getUuid(), self.getManagementIp(), ret.getError()));
} else {
reply.setFirstBootDevice(ret.getFirstBootDevice());
logger.debug(String.format("first boot dev of vm[uuid:%s] on kvm host[uuid:%s] is %s",
msg.getVmInstanceUuid(), self.getUuid(), ret.getFirstBootDevice()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
final GetVmFirstBootDeviceOnHypervisorReply reply = new GetVmFirstBootDeviceOnHypervisorReply();
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(GetVmDeviceAddressMsg msg) {
inQueue().name(String.format("get-device-address-of-vm-%s-on-kvm-%s", msg.getVmInstanceUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> getVmDeviceAddress(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void getVmDeviceAddress(final GetVmDeviceAddressMsg msg, final NoErrorCompletion completion) {
checkStatus();
GetVmDeviceAddressReply reply = new GetVmDeviceAddressReply();
GetVmDeviceAddressCmd cmd = new GetVmDeviceAddressCmd();
cmd.setUuid(msg.getVmInstanceUuid());
for (Map.Entry<String, List> e : msg.getInventories().entrySet()) {
String resourceType = e.getKey();
cmd.putDevice(resourceType, KVMVmDeviceType.fromResourceType(resourceType)
.getDeviceTOs(e.getValue(), KVMHostInventory.valueOf(getSelf()))
);
}
new Http<>(getVmDeviceAddressPath, cmd, GetVmDeviceAddressRsp.class).call(new ReturnValueCompletion<GetVmDeviceAddressRsp>(msg, completion) {
@Override
public void success(GetVmDeviceAddressRsp rsp) {
for (String resourceType : msg.getInventories().keySet()) {
reply.putAddresses(resourceType, rsp.getAddresses(resourceType).stream().map(it -> {
VmDeviceAddress address = new VmDeviceAddress();
address.setAddress(it.getAddress());
address.setAddressType(it.getAddressType());
address.setDeviceType(it.getDeviceType());
address.setResourceUuid(it.getUuid());
address.setResourceType(resourceType);
return address;
}).collect(Collectors.toList()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(GetKVMHostDownloadCredentialMsg msg) {
final GetKVMHostDownloadCredentialReply reply = new GetKVMHostDownloadCredentialReply();
String key = asf.getPrivateKey();
String hostname = null;
if (Strings.isNotEmpty(msg.getDataNetworkCidr())) {
String dataNetworkAddress = getDataNetworkAddress(self.getUuid(), msg.getDataNetworkCidr());
if (dataNetworkAddress != null) {
hostname = dataNetworkAddress;
}
}
reply.setHostname(hostname == null ? getSelf().getManagementIp() : hostname);
reply.setUsername(getSelf().getUsername());
reply.setSshPort(getSelf().getPort());
reply.setSshKey(key);
bus.reply(msg, reply);
}
protected static String getDataNetworkAddress(String hostUuid, String cidr) {
final String extraIps = HostSystemTags.EXTRA_IPS.getTokenByResourceUuid(
hostUuid, HostSystemTags.EXTRA_IPS_TOKEN);
if (extraIps == null) {
logger.debug(String.format("Host [uuid:%s] has no IPs in data network", hostUuid));
return null;
}
final String[] ips = extraIps.split(",");
for (String ip: ips) {
if (NetworkUtils.isIpv4InCidr(ip, cidr)) {
return ip;
}
}
return null;
}
private void handle(final IncreaseVmCpuMsg msg) {
IncreaseVmCpuReply reply = new IncreaseVmCpuReply();
IncreaseCpuCmd cmd = new IncreaseCpuCmd();
cmd.setVmUuid(msg.getVmInstanceUuid());
cmd.setCpuNum(msg.getCpuNum());
new Http<>(onlineIncreaseCpuPath, cmd, IncreaseCpuResponse.class).call(new ReturnValueCompletion<IncreaseCpuResponse>(msg) {
@Override
public void success(IncreaseCpuResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("failed to increase vm cpu, error details: %s", ret.getError()));
} else {
reply.setCpuNum(ret.getCpuNum());
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final IncreaseVmMemoryMsg msg) {
IncreaseVmMemoryReply reply = new IncreaseVmMemoryReply();
IncreaseMemoryCmd cmd = new IncreaseMemoryCmd();
cmd.setVmUuid(msg.getVmInstanceUuid());
cmd.setMemorySize(msg.getMemorySize());
new Http<>(onlineIncreaseMemPath, cmd, IncreaseMemoryResponse.class).call(new ReturnValueCompletion<IncreaseMemoryResponse>(msg) {
@Override
public void success(IncreaseMemoryResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
} else {
reply.setMemorySize(ret.getMemorySize());
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void directlyDestroy(final VmDirectlyDestroyOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmDirectlyDestroyOnHypervisorReply reply = new VmDirectlyDestroyOnHypervisorReply();
DestroyVmCmd cmd = new DestroyVmCmd();
cmd.setUuid(msg.getVmUuid());
extEmitter.beforeDirectlyDestroyVmOnKvm(cmd);
new Http<>(destroyVmPath, cmd, DestroyVmResponse.class).call(new ReturnValueCompletion<DestroyVmResponse>(completion) {
@Override
public void success(DestroyVmResponse ret) {
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_DESTROY_VM_ON_HYPERVISOR, ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
protected class RunInKVMHostQueue {
private String name;
private List<AsyncBackup> asyncBackups = new ArrayList<>();
public RunInKVMHostQueue name(String v) {
name = v;
return this;
}
public RunInKVMHostQueue asyncBackup(AsyncBackup v) {
asyncBackups.add(v);
return this;
}
public void run(Consumer<SyncTaskChain> consumer) {
DebugUtils.Assert(name != null, "name() must be called");
DebugUtils.Assert(!asyncBackups.isEmpty(), "asyncBackup must be called");
AsyncBackup one = asyncBackups.get(0);
AsyncBackup[] rest = asyncBackups.size() > 1 ?
asyncBackups.subList(1, asyncBackups.size()).toArray(new AsyncBackup[asyncBackups.size()-1]) :
new AsyncBackup[0];
thdf.chainSubmit(new ChainTask(one, rest) {
@Override
public String getSyncSignature() {
return id;
}
@Override
public void run(SyncTaskChain chain) {
consumer.accept(chain);
}
@Override
protected int getSyncLevel() {
return getHostSyncLevel();
}
@Override
public String getName() {
return name;
}
});
}
}
protected RunInKVMHostQueue inQueue() {
return new RunInKVMHostQueue();
}
private void handle(final VmDirectlyDestroyOnHypervisorMsg msg) {
inQueue().name(String.format("directly-delete-vm-%s-msg-on-kvm-%s", msg.getVmUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> directlyDestroy(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private SshResult runShell(String script) {
Ssh ssh = new Ssh();
ssh.setHostname(self.getManagementIp());
ssh.setPort(getSelf().getPort());
ssh.setUsername(getSelf().getUsername());
ssh.setPassword(getSelf().getPassword());
ssh.shell(script);
return ssh.runAndClose();
}
private void handle(KvmRunShellMsg msg) {
SshResult result = runShell(msg.getScript());
KvmRunShellReply reply = new KvmRunShellReply();
if (result.isSshFailure()) {
reply.setError(operr("unable to connect to KVM[ip:%s, username:%s, sshPort:%d ] to do DNS check," +
" please check if username/password is wrong; %s",
self.getManagementIp(), getSelf().getUsername(),
getSelf().getPort(), result.getExitErrorMessage()));
} else {
reply.setStdout(result.getStdout());
reply.setStderr(result.getStderr());
reply.setReturnCode(result.getReturnCode());
}
bus.reply(msg, reply);
}
private void handle(final GetVmConsoleAddressFromHostMsg msg) {
final GetVmConsoleAddressFromHostReply reply = new GetVmConsoleAddressFromHostReply();
GetVncPortCmd cmd = new GetVncPortCmd();
cmd.setVmUuid(msg.getVmInstanceUuid());
new Http<>(getConsolePortPath, cmd, GetVncPortResponse.class).call(new ReturnValueCompletion<GetVncPortResponse>(msg) {
@Override
public void success(GetVncPortResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
} else {
reply.setHostIp(self.getManagementIp());
reply.setProtocol(ret.getProtocol());
reply.setPort(ret.getPort());
VdiPortInfo vdiPortInfo = new VdiPortInfo();
if (ret.getVncPort() != null) {
vdiPortInfo.setVncPort(ret.getVncPort());
}
if (ret.getSpicePort() != null) {
vdiPortInfo.setSpicePort(ret.getSpicePort());
}
if (ret.getSpiceTlsPort() != null) {
vdiPortInfo.setSpiceTlsPort(ret.getSpiceTlsPort());
}
reply.setVdiPortInfo(vdiPortInfo);
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final UpdateVmPriorityMsg msg) {
final UpdateVmPriorityReply reply = new UpdateVmPriorityReply();
if (self.getStatus() != HostStatus.Connected) {
reply.setError(operr("the host[uuid:%s, status:%s] is not Connected", self.getUuid(), self.getStatus()));
bus.reply(msg, reply);
return;
}
UpdateVmPriorityCmd cmd = new UpdateVmPriorityCmd();
cmd.priorityConfigStructs = msg.getPriorityConfigStructs();
new Http<>(updateVmPriorityPath, cmd, UpdateVmPriorityRsp.class).call(new ReturnValueCompletion<UpdateVmPriorityRsp>(msg) {
@Override
public void success(UpdateVmPriorityRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
protected void handle(final CheckVmStateOnHypervisorMsg msg) {
final CheckVmStateOnHypervisorReply reply = new CheckVmStateOnHypervisorReply();
if (self.getStatus() != HostStatus.Connected) {
reply.setError(operr("the host[uuid:%s, status:%s] is not Connected", self.getUuid(), self.getStatus()));
bus.reply(msg, reply);
return;
}
// NOTE: don't run this message in the sync task
// there can be many such kind of messages
// running in the sync task may cause other tasks starved
CheckVmStateCmd cmd = new CheckVmStateCmd();
cmd.vmUuids = msg.getVmInstanceUuids();
cmd.hostUuid = self.getUuid();
extEmitter.beforeCheckVmState((KVMHostInventory) getSelfInventory(), msg, cmd);
new Http<>(checkVmStatePath, cmd, CheckVmStateRsp.class).call(new ReturnValueCompletion<CheckVmStateRsp>(msg) {
@Override
public void success(CheckVmStateRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
} else {
Map<String, String> m = new HashMap<>();
for (Map.Entry<String, String> e : ret.states.entrySet()) {
m.put(e.getKey(), KvmVmState.valueOf(e.getValue()).toVmInstanceState().toString());
}
extEmitter.afterCheckVmState((KVMHostInventory) getSelfInventory(), m);
reply.setStates(m);
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final DetachIsoOnHypervisorMsg msg) {
inQueue().asyncBackup(msg)
.name(String.format("detach-iso-%s-on-host-%s", msg.getIsoUuid(), self.getUuid()))
.run(chain -> detachIso(msg, new NoErrorCompletion(msg, chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void detachIso(final DetachIsoOnHypervisorMsg msg, final NoErrorCompletion completion) {
final DetachIsoOnHypervisorReply reply = new DetachIsoOnHypervisorReply();
DetachIsoCmd cmd = new DetachIsoCmd();
cmd.isoUuid = msg.getIsoUuid();
cmd.vmUuid = msg.getVmInstanceUuid();
Integer deviceId = IsoOperator.getIsoDeviceId(msg.getVmInstanceUuid(), msg.getIsoUuid());
assert deviceId != null;
cmd.deviceId = deviceId;
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KVMPreDetachIsoExtensionPoint ext : pluginRgty.getExtensionList(KVMPreDetachIsoExtensionPoint.class)) {
ext.preDetachIsoExtensionPoint(inv, cmd);
}
new Http<>(detachIsoPath, cmd, DetachIsoRsp.class).call(new ReturnValueCompletion<DetachIsoRsp>(msg, completion) {
@Override
public void success(DetachIsoRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final AttachIsoOnHypervisorMsg msg) {
inQueue().asyncBackup(msg)
.name(String.format("attach-iso-%s-on-host-%s", msg.getIsoSpec().getImageUuid(), self.getUuid()))
.run(chain -> attachIso(msg, new NoErrorCompletion(msg, chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void attachIso(final AttachIsoOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final AttachIsoOnHypervisorReply reply = new AttachIsoOnHypervisorReply();
IsoTO iso = new IsoTO();
iso.setImageUuid(msg.getIsoSpec().getImageUuid());
iso.setPath(msg.getIsoSpec().getInstallPath());
iso.setDeviceId(msg.getIsoSpec().getDeviceId());
AttachIsoCmd cmd = new AttachIsoCmd();
cmd.vmUuid = msg.getVmInstanceUuid();
cmd.iso = iso;
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KVMPreAttachIsoExtensionPoint ext : pluginRgty.getExtensionList(KVMPreAttachIsoExtensionPoint.class)) {
ext.preAttachIsoExtensionPoint(inv, cmd);
}
new Http<>(attachIsoPath, cmd, AttachIsoRsp.class).call(new ReturnValueCompletion<AttachIsoRsp>(msg, completion) {
@Override
public void success(AttachIsoRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final DetachNicFromVmOnHypervisorMsg msg) {
inQueue().name("detach-nic-on-kvm-host-" + self.getUuid())
.asyncBackup(msg)
.run(chain -> detachNic(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
protected void detachNic(final DetachNicFromVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
final DetachNicFromVmOnHypervisorReply reply = new DetachNicFromVmOnHypervisorReply();
NicTO to = completeNicInfo(msg.getNic());
DetachNicCommand cmd = new DetachNicCommand();
cmd.setVmUuid(msg.getVmInstanceUuid());
cmd.setNic(to);
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KvmPreDetachNicExtensionPoint ext : pluginRgty.getExtensionList(KvmPreDetachNicExtensionPoint.class)) {
ext.preDetachNicExtensionPoint(inv, cmd);
}
new Http<>(detachNicPath, cmd, DetachNicRsp.class).call(new ReturnValueCompletion<DetachNicRsp>(msg, completion) {
@Override
public void success(DetachNicRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void doHandleKvmSyncMsg(final KVMHostSyncHttpCallMsg msg, SyncTaskChain outter) {
inQueue().name(String.format("execute-sync-http-call-on-kvm-host-%s", self.getUuid()))
.asyncBackup(msg)
.asyncBackup(outter)
.run(chain -> executeSyncHttpCall(msg, new NoErrorCompletion(chain, outter) {
@Override
public void done() {
chain.next();
outter.next();
}
}));
}
private static int getHostMaxThreadsNum() {
int n = (int)(KVMGlobalProperty.KVM_HOST_MAX_THREDS_RATIO * ThreadGlobalProperty.MAX_THREAD_NUM);
int m = ThreadGlobalProperty.MAX_THREAD_NUM / 5;
return Math.max(n, m);
}
private void handle(final KVMHostSyncHttpCallMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return "host-sync-control";
}
@Override
public void run(SyncTaskChain chain) {
doHandleKvmSyncMsg(msg, chain);
}
@Override
protected int getSyncLevel() {
return getHostMaxThreadsNum();
}
@Override
public String getName() {
return String.format("sync-call-on-kvm-%s", self.getUuid());
}
});
}
private void executeSyncHttpCall(KVMHostSyncHttpCallMsg msg, NoErrorCompletion completion) {
if (!msg.isNoStatusCheck()) {
checkStatus();
}
String url = buildUrl(msg.getPath());
MessageCommandRecorder.record(msg.getCommandClassName());
Map<String, String> headers = new HashMap<>();
headers.put(Constants.AGENT_HTTP_HEADER_RESOURCE_UUID, self.getUuid());
LinkedHashMap rsp = restf.syncJsonPost(url, msg.getCommand(), headers, LinkedHashMap.class);
KVMHostSyncHttpCallReply reply = new KVMHostSyncHttpCallReply();
reply.setResponse(rsp);
bus.reply(msg, reply);
completion.done();
}
private void doHandleKvmAsyncMsg(final KVMHostAsyncHttpCallMsg msg, SyncTaskChain outter) {
inQueue().name(String.format("execute-async-http-call-on-kvm-host-%s", self.getUuid()))
.asyncBackup(msg)
.asyncBackup(outter)
.run(chain -> executeAsyncHttpCall(msg, new NoErrorCompletion(chain, outter) {
@Override
public void done() {
chain.next();
outter.next();
}
}));
}
private void handle(final KVMHostAsyncHttpCallMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return "host-sync-control";
}
@Override
public void run(SyncTaskChain chain) {
doHandleKvmAsyncMsg(msg, chain);
}
@Override
protected int getSyncLevel() {
return getHostMaxThreadsNum();
}
@Override
public String getName() {
return String.format("async-call-on-kvm-%s", self.getUuid());
}
});
}
private String buildUrl(String path) {
UriComponentsBuilder ub = UriComponentsBuilder.newInstance();
ub.scheme(KVMGlobalProperty.AGENT_URL_SCHEME);
ub.host(self.getManagementIp());
ub.port(KVMGlobalProperty.AGENT_PORT);
if (!"".equals(KVMGlobalProperty.AGENT_URL_ROOT_PATH)) {
ub.path(KVMGlobalProperty.AGENT_URL_ROOT_PATH);
}
ub.path(path);
return ub.build().toUriString();
}
private void executeAsyncHttpCall(final KVMHostAsyncHttpCallMsg msg, final NoErrorCompletion completion) {
if (!msg.isNoStatusCheck()) {
checkStatus();
}
String url = buildUrl(msg.getPath());
MessageCommandRecorder.record(msg.getCommandClassName());
new Http<>(url, msg.getCommand(), LinkedHashMap.class)
.call(new ReturnValueCompletion<LinkedHashMap>(msg, completion) {
@Override
public void success(LinkedHashMap ret) {
KVMHostAsyncHttpCallReply reply = new KVMHostAsyncHttpCallReply();
reply.setResponse(ret);
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
KVMHostAsyncHttpCallReply reply = new KVMHostAsyncHttpCallReply();
if (err.isError(SysErrors.HTTP_ERROR, SysErrors.IO_ERROR)) {
reply.setError(err(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, err, "cannot do the operation on the KVM host"));
} else {
reply.setError(err);
}
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final MergeVolumeSnapshotOnKvmMsg msg) {
inQueue().name(String.format("merge-volume-snapshot-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> mergeVolumeSnapshot(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void mergeVolumeSnapshot(final MergeVolumeSnapshotOnKvmMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final MergeVolumeSnapshotOnKvmReply reply = new MergeVolumeSnapshotOnKvmReply();
VolumeInventory volume = msg.getTo();
if (volume.getVmInstanceUuid() != null) {
SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
q.select(VmInstanceVO_.state);
q.add(VmInstanceVO_.uuid, Op.EQ, volume.getVmInstanceUuid());
VmInstanceState state = q.findValue();
if (state != VmInstanceState.Stopped && state != VmInstanceState.Running && state != VmInstanceState.Paused && state != VmInstanceState.Destroyed) {
throw new OperationFailureException(operr("cannot do volume snapshot merge when vm[uuid:%s] is in state of %s." +
" The operation is only allowed when vm is Running or Stopped", volume.getUuid(), state));
}
if (state == VmInstanceState.Running) {
String libvirtVersion = KVMSystemTags.LIBVIRT_VERSION.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.LIBVIRT_VERSION_TOKEN);
if (new VersionComparator(KVMConstant.MIN_LIBVIRT_LIVE_BLOCK_COMMIT_VERSION).compare(libvirtVersion) > 0) {
throw new OperationFailureException(operr("live volume snapshot merge needs libvirt version greater than %s," +
" current libvirt version is %s. Please stop vm and redo the operation or detach the volume if it's data volume",
KVMConstant.MIN_LIBVIRT_LIVE_BLOCK_COMMIT_VERSION, libvirtVersion));
}
}
}
VolumeSnapshotInventory snapshot = msg.getFrom();
MergeSnapshotCmd cmd = new MergeSnapshotCmd();
cmd.setFullRebase(msg.isFullRebase());
cmd.setDestPath(volume.getInstallPath());
cmd.setSrcPath(snapshot.getPrimaryStorageInstallPath());
cmd.setVmUuid(volume.getVmInstanceUuid());
cmd.setVolume(VolumeTO.valueOf(volume, (KVMHostInventory) getSelfInventory()));
extEmitter.beforeMergeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd);
new Http<>(mergeSnapshotPath, cmd, MergeSnapshotRsp.class)
.call(new ReturnValueCompletion<MergeSnapshotRsp>(msg, completion) {
@Override
public void success(MergeSnapshotRsp ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
extEmitter.afterMergeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, reply.getError());
}
extEmitter.afterMergeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd);
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
extEmitter.afterMergeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, reply.getError());
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final TakeSnapshotOnHypervisorMsg msg) {
inQueue().name(String.format("take-snapshot-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> {
takeSnapshot(msg);
chain.next();
});
}
private void takeSnapshot(final TakeSnapshotOnHypervisorMsg msg) {
thdf.chainSubmit(new ChainTask(msg) {
@Override
public String getSyncSignature() {
return getName();
}
@Override
public void run(SyncTaskChain chain) {
doTakeSnapshot(msg, new NoErrorCompletion() {
@Override
public void done() {
chain.next();
}
});
}
@Override
protected int getSyncLevel() {
return KVMGlobalConfig.HOST_SNAPSHOT_SYNC_LEVEL.value(Integer.class);
}
@Override
public String getName() {
return String.format("take-snapshot-on-kvm-%s", self.getUuid());
}
});
}
protected void completeTakeSnapshotCmd(final TakeSnapshotOnHypervisorMsg msg, final TakeSnapshotCmd cmd) {
}
private void doTakeSnapshot(final TakeSnapshotOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final TakeSnapshotOnHypervisorReply reply = new TakeSnapshotOnHypervisorReply();
TakeSnapshotCmd cmd = new TakeSnapshotCmd();
if (msg.getVmUuid() != null) {
SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
q.select(VmInstanceVO_.state);
q.add(VmInstanceVO_.uuid, SimpleQuery.Op.EQ, msg.getVmUuid());
VmInstanceState vmState = q.findValue();
if (vmState != VmInstanceState.Running && vmState != VmInstanceState.Stopped && vmState != VmInstanceState.Paused) {
throw new OperationFailureException(operr("vm[uuid:%s] is not Running or Stopped, current state[%s]", msg.getVmUuid(), vmState));
}
if (!HostSystemTags.LIVE_SNAPSHOT.hasTag(self.getUuid())) {
if (vmState != VmInstanceState.Stopped) {
reply.setError(err(SysErrors.NO_CAPABILITY_ERROR,
"kvm host[uuid:%s, name:%s, ip:%s] doesn't not support live snapshot. please stop vm[uuid:%s] and try again",
self.getUuid(), self.getName(), self.getManagementIp(), msg.getVmUuid()
));
bus.reply(msg, reply);
completion.done();
return;
}
}
cmd.setVolumeUuid(msg.getVolume().getUuid());
cmd.setVmUuid(msg.getVmUuid());
cmd.setVolume(VolumeTO.valueOf(msg.getVolume(), (KVMHostInventory) getSelfInventory()));
}
cmd.setVolumeInstallPath(msg.getVolume().getInstallPath());
cmd.setInstallPath(msg.getInstallPath());
cmd.setFullSnapshot(msg.isFullSnapshot());
cmd.setVolumeUuid(msg.getVolume().getUuid());
completeTakeSnapshotCmd(msg, cmd);
FlowChain chain = FlowChainBuilder.newSimpleFlowChain();
chain.setName(String.format("take-snapshot-%s-for-volume-%s", msg.getSnapshotName(), msg.getVolume().getUuid()));
chain.then(new NoRollbackFlow() {
String __name__ = String.format("before-take-snapshot-%s-for-volume-%s", msg.getSnapshotName(), msg.getVolume().getUuid());
@Override
public void run(FlowTrigger trigger, Map data) {
extEmitter.beforeTakeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd, new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
}).then(new NoRollbackFlow() {
String __name__ = "do-take-snapshot-" + msg.getSnapshotName();
@Override
public void run(FlowTrigger trigger, Map data) {
new Http<>(snapshotPath, cmd, TakeSnapshotResponse.class).call(new ReturnValueCompletion<TakeSnapshotResponse>(msg, trigger) {
@Override
public void success(TakeSnapshotResponse ret) {
if (ret.isSuccess()) {
extEmitter.afterTakeSnapshot((KVMHostInventory) getSelfInventory(), msg, cmd, ret);
reply.setNewVolumeInstallPath(ret.getNewVolumeInstallPath());
reply.setSnapshotInstallPath(ret.getSnapshotInstallPath());
reply.setSize(ret.getSize());
} else {
ErrorCode err = operr("operation error, because:%s", ret.getError());
extEmitter.afterTakeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, ret, err);
reply.setError(err);
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
extEmitter.afterTakeSnapshotFailed((KVMHostInventory) getSelfInventory(), msg, cmd, null, errorCode);
reply.setError(errorCode);
trigger.fail(errorCode);
}
});
}
}).done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
bus.reply(msg, reply);
completion.done();
}
}).error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
reply.setError(errCode);
bus.reply(msg, reply);
completion.done();
}
}).start();
}
private void migrateVm(final MigrateStruct s, final Completion completion) {
final TaskProgressRange parentStage = getTaskStage();
final TaskProgressRange MIGRATE_VM_STAGE = new TaskProgressRange(0, 90);
final String dstHostMigrateIp, dstHostMnIp, dstHostUuid;
final String vmUuid;
final StorageMigrationPolicy storageMigrationPolicy;
final boolean migrateFromDestination;
final String srcHostMigrateIp, srcHostMnIp, srcHostUuid;
vmUuid = s.vmUuid;
dstHostMigrateIp = s.dstHostMigrateIp;
dstHostMnIp = s.dstHostMnIp;
dstHostUuid = s.dstHostUuid;
storageMigrationPolicy = s.storageMigrationPolicy;
migrateFromDestination = s.migrateFromDestition;
srcHostMigrateIp = s.srcHostMigrateIp;
srcHostMnIp = s.srcHostMnIp;
srcHostUuid = s.srcHostUuid;
SimpleQuery<VmInstanceVO> q = dbf.createQuery(VmInstanceVO.class);
q.select(VmInstanceVO_.internalId);
q.add(VmInstanceVO_.uuid, Op.EQ, vmUuid);
final Long vmInternalId = q.findValue();
List<VmNicVO> nics = Q.New(VmNicVO.class).eq(VmNicVO_.vmInstanceUuid, s.vmUuid)
.eq(VmNicVO_.type, "vDPA")
.list();
List<NicTO> nicTos = VmNicInventory.valueOf(nics).stream().map(this::completeNicInfo).collect(Collectors.toList());
List<NicTO> vDPANics = new ArrayList<NicTO>();
for (NicTO nicTo : nicTos) {
if (nicTo.getType().equals("vDPA")) {
vDPANics.add(nicTo);
}
}
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("migrate-vm-%s-on-kvm-host-%s", vmUuid, self.getUuid()));
chain.then(new ShareFlow() {
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "generate-vDPA-on-dst-host";
@Override
public void run(final FlowTrigger trigger, Map data) {
if (vDPANics.isEmpty()) {
trigger.next();
return;
}
GenerateVdpaCmd cmd = new GenerateVdpaCmd();
cmd.vmUuid = vmUuid;
cmd.setNics(nicTos);
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.host(dstHostMnIp);
ub.path(KVMConstant.KVM_GENERATE_VDPA_PATH);
String url = ub.build().toString();
new Http<>(url, cmd, GenerateVdpaResponse.class).call(dstHostUuid, new ReturnValueCompletion<GenerateVdpaResponse>(trigger) {
@Override
public void success(GenerateVdpaResponse ret) {
if (!ret.isSuccess()) {
logger.warn(String.format("generate vDPA for %s failed, %s", vmUuid, ret.getError()));
}
data.put("vDPA_paths", ret.getVdpaPaths());
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
logger.warn(String.format("generate vDPA for %s failed, %s", vmUuid, errorCode));
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "migrate-vm";
@Override
public void run(final FlowTrigger trigger, Map data) {
TaskProgressRange stage = markTaskStage(parentStage, MIGRATE_VM_STAGE);
boolean autoConverage = KVMGlobalConfig.MIGRATE_AUTO_CONVERGE.value(Boolean.class);
if (!autoConverage) {
autoConverage = s.strategy != null && s.strategy.equals("auto-converge");
}
boolean xbzrle = KVMGlobalConfig.MIGRATE_XBZRLE.value(Boolean.class);
MigrateVmCmd cmd = new MigrateVmCmd();
cmd.setDestHostIp(dstHostMigrateIp);
cmd.setSrcHostIp(srcHostMigrateIp);
cmd.setMigrateFromDestination(migrateFromDestination);
cmd.setStorageMigrationPolicy(storageMigrationPolicy == null ? null : storageMigrationPolicy.toString());
cmd.setVmUuid(vmUuid);
cmd.setAutoConverge(autoConverage);
cmd.setXbzrle(xbzrle);
cmd.setVdpaPaths((List<String>) data.get("vDPA_paths"));
cmd.setUseNuma(rcf.getResourceConfigValue(VmGlobalConfig.NUMA, vmUuid, Boolean.class));
cmd.setTimeout(timeoutManager.getTimeout());
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(migrateVmPath);
ub.host(migrateFromDestination ? dstHostMnIp : srcHostMnIp);
String migrateUrl = ub.build().toString();
new Http<>(migrateUrl, cmd, MigrateVmResponse.class).call(migrateFromDestination ? dstHostUuid : srcHostUuid, new ReturnValueCompletion<MigrateVmResponse>(trigger) {
@Override
public void success(MigrateVmResponse ret) {
if (!ret.isSuccess()) {
ErrorCode err = err(HostErrors.FAILED_TO_MIGRATE_VM_ON_HYPERVISOR,
"failed to migrate vm[uuid:%s] from kvm host[uuid:%s, ip:%s] to dest host[ip:%s], %s",
vmUuid, srcHostUuid, srcHostMigrateIp, dstHostMigrateIp, ret.getError()
);
trigger.fail(err);
} else {
String info = String.format("successfully migrated vm[uuid:%s] from kvm host[uuid:%s, ip:%s] to dest host[ip:%s]",
vmUuid, srcHostUuid, srcHostMigrateIp, dstHostMigrateIp);
logger.debug(info);
reportProgress(stage.getEnd().toString());
trigger.next();
}
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "harden-vm-console-on-dst-host";
@Override
public void run(final FlowTrigger trigger, Map data) {
HardenVmConsoleCmd cmd = new HardenVmConsoleCmd();
cmd.vmInternalId = vmInternalId;
cmd.vmUuid = vmUuid;
cmd.hostManagementIp = dstHostMnIp;
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.host(dstHostMnIp);
ub.path(KVMConstant.KVM_HARDEN_CONSOLE_PATH);
String url = ub.build().toString();
new Http<>(url, cmd, AgentResponse.class).call(dstHostUuid, new ReturnValueCompletion<AgentResponse>(trigger) {
@Override
public void success(AgentResponse ret) {
if (!ret.isSuccess()) {
//TODO: add GC
logger.warn(String.format("failed to harden VM[uuid:%s]'s console, %s", vmUuid, ret.getError()));
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
//TODO add GC
logger.warn(String.format("failed to harden VM[uuid:%s]'s console, %s", vmUuid, errorCode));
// continue
trigger.next();
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "delete-vm-console-firewall-on-source-host";
@Override
public void run(final FlowTrigger trigger, Map data) {
DeleteVmConsoleFirewallCmd cmd = new DeleteVmConsoleFirewallCmd();
cmd.vmInternalId = vmInternalId;
cmd.vmUuid = vmUuid;
cmd.hostManagementIp = srcHostMnIp;
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.host(srcHostMnIp);
ub.path(KVMConstant.KVM_DELETE_CONSOLE_FIREWALL_PATH);
String url = ub.build().toString();
new Http<>(url, cmd, AgentResponse.class).call(new ReturnValueCompletion<AgentResponse>(trigger) {
@Override
public void success(AgentResponse ret) {
if (!ret.isSuccess()) {
logger.warn(String.format("failed to delete console firewall rule for the vm[uuid:%s] on" +
" the source host[uuid:%s, ip:%s], %s", vmUuid, srcHostUuid, srcHostMigrateIp, ret.getError()));
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
//TODO
logger.warn(String.format("failed to delete console firewall rule for the vm[uuid:%s] on" +
" the source host[uuid:%s, ip:%s], %s", vmUuid, srcHostUuid, srcHostMigrateIp, errorCode));
trigger.next();
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "delete-vDPA-on-src-host";
@Override
public void run(final FlowTrigger trigger, Map data) {
if (vDPANics.isEmpty()) {
trigger.next();
return;
}
DeleteVdpaCmd cmd = new DeleteVdpaCmd();
cmd.vmUuid = vmUuid;
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(baseUrl);
ub.host(srcHostMnIp);
ub.path(KVMConstant.KVM_DELETE_VDPA_PATH);
String url = ub.build().toString();
new Http<>(url, cmd, AgentResponse.class).call(new ReturnValueCompletion<AgentResponse>(trigger) {
@Override
public void success(AgentResponse ret) {
if (!ret.isSuccess()) {
logger.warn(String.format("delete vDPA for %s failed, %s", vmUuid, ret.getError()));
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
logger.warn(String.format("delete vDPA for %s failed, %s", vmUuid, errorCode));
trigger.next();
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
String info = String.format("successfully migrated vm[uuid:%s] from kvm host[uuid:%s, ip:%s] to dest host[ip:%s]",
vmUuid, srcHostUuid, srcHostMigrateIp, dstHostMigrateIp);
logger.debug(info);
reportProgress(parentStage.getEnd().toString());
completion.success();
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
});
}
}).start();
}
private void handle(final MigrateVmOnHypervisorMsg msg) {
inQueue().name(String.format("migrate-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> migrateVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
class MigrateStruct {
String vmUuid;
String dstHostMigrateIp;
String strategy;
String dstHostMnIp;
String dstHostUuid;
StorageMigrationPolicy storageMigrationPolicy;
boolean migrateFromDestition;
String srcHostMigrateIp;
String srcHostMnIp;
String srcHostUuid;
}
private MigrateStruct buildMigrateStuct(final MigrateVmOnHypervisorMsg msg){
MigrateStruct s = new MigrateStruct();
s.vmUuid = msg.getVmInventory().getUuid();
s.srcHostUuid = msg.getSrcHostUuid();
s.dstHostUuid = msg.getDestHostInventory().getUuid();
s.storageMigrationPolicy = msg.getStorageMigrationPolicy();
s.migrateFromDestition = msg.isMigrateFromDestination();
s.strategy = msg.getStrategy();
MigrateNetworkExtensionPoint.MigrateInfo migrateIpInfo = null;
for (MigrateNetworkExtensionPoint ext: pluginRgty.getExtensionList(MigrateNetworkExtensionPoint.class)) {
MigrateNetworkExtensionPoint.MigrateInfo r = ext.getMigrationAddressForVM(s.srcHostUuid, s.dstHostUuid);
if (r == null) {
continue;
}
migrateIpInfo = r;
}
s.dstHostMnIp = msg.getDestHostInventory().getManagementIp();
s.dstHostMigrateIp = migrateIpInfo == null ? s.dstHostMnIp : migrateIpInfo.dstMigrationAddress;
s.srcHostMnIp = Q.New(HostVO.class).eq(HostVO_.uuid, msg.getSrcHostUuid()).select(HostVO_.managementIp).findValue();
s.srcHostMigrateIp = migrateIpInfo == null ? s.srcHostMnIp : migrateIpInfo.srcMigrationAddress;
return s;
}
private void migrateVm(final MigrateVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
MigrateStruct s = buildMigrateStuct(msg);
final MigrateVmOnHypervisorReply reply = new MigrateVmOnHypervisorReply();
migrateVm(s, new Completion(msg, completion) {
@Override
public void success() {
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final VmUpdateNicOnHypervisorMsg msg) {
inQueue().name(String.format("update-nic-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> updateNic(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void updateNic(VmUpdateNicOnHypervisorMsg msg, NoErrorCompletion completion) {
checkStateAndStatus();
final VmUpdateNicOnHypervisorReply reply = new VmUpdateNicOnHypervisorReply();
List<VmNicVO> nics = Q.New(VmNicVO.class).eq(VmNicVO_.vmInstanceUuid, msg.getVmInstanceUuid()).list();
UpdateNicCmd cmd = new UpdateNicCmd();
cmd.setVmInstanceUuid(msg.getVmInstanceUuid());
cmd.setNics(VmNicInventory.valueOf(nics).stream().map(this::completeNicInfo).collect(Collectors.toList()));
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KVMPreUpdateNicExtensionPoint ext : pluginRgty.getExtensionList(KVMPreUpdateNicExtensionPoint.class)) {
ext.preUpdateNic(inv, cmd);
}
new Http<>(updateNicPath, cmd, AttachNicResponse.class).call(new ReturnValueCompletion<AttachNicResponse>(msg, completion) {
@Override
public void success(AttachNicResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("failed to update nic[vm:%s] on kvm host[uuid:%s, ip:%s]," +
"because %s", msg.getVmInstanceUuid(), self.getUuid(), self.getManagementIp(), ret.getError()));
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final VmAttachNicOnHypervisorMsg msg) {
inQueue().name(String.format("attach-nic-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> attachNic(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
protected void attachNic(final VmAttachNicOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
NicTO to = completeNicInfo(msg.getNicInventory());
final VmAttachNicOnHypervisorReply reply = new VmAttachNicOnHypervisorReply();
AttachNicCommand cmd = new AttachNicCommand();
cmd.setVmUuid(msg.getNicInventory().getVmInstanceUuid());
cmd.setNic(to);
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KvmPreAttachNicExtensionPoint ext : pluginRgty.getExtensionList(KvmPreAttachNicExtensionPoint.class)) {
ext.preAttachNicExtensionPoint(inv, cmd);
}
new Http<>(attachNicPath, cmd, AttachNicResponse.class).call(new ReturnValueCompletion<AttachNicResponse>(msg, completion) {
@Override
public void success(AttachNicResponse ret) {
if (!ret.isSuccess()) {
if (ret.getError().contains("Device or resource busy")) {
reply.setError(operr("failed to attach nic[uuid:%s, vm:%s] on kvm host[uuid:%s, ip:%s]," +
"because %s, please try again or delete device[%s] by yourself", msg.getNicInventory().getUuid(), msg.getNicInventory().getVmInstanceUuid(),
self.getUuid(), self.getManagementIp(), ret.getError(), msg.getNicInventory().getInternalName()));
} else {
reply.setError(operr("failed to attach nic[uuid:%s, vm:%s] on kvm host[uuid:%s, ip:%s]," +
"because %s", msg.getNicInventory().getUuid(), msg.getNicInventory().getVmInstanceUuid(),
self.getUuid(), self.getManagementIp(), ret.getError()));
}
}
bus.reply(msg, reply);
if (ret.getPciAddress() != null) {
SystemTagCreator creator = KVMSystemTags.VMNIC_PCI_ADDRESS.newSystemTagCreator(msg.getNicInventory().getUuid());
creator.inherent = true;
creator.recreate = true;
creator.setTagByTokens(map(e(KVMSystemTags.VMNIC_PCI_ADDRESS_TOKEN, ret.getPciAddress().toString())));
creator.create();
}
completion.done();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final DetachVolumeFromVmOnHypervisorMsg msg) {
inQueue().name(String.format("detach-volume-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> detachVolume(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
protected void detachVolume(final DetachVolumeFromVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final VolumeInventory vol = msg.getInventory();
final VmInstanceInventory vm = msg.getVmInventory();
VolumeTO to = VolumeTO.valueOfWithOutExtension(vol, (KVMHostInventory) getSelfInventory(), vm.getPlatform());
final DetachVolumeFromVmOnHypervisorReply reply = new DetachVolumeFromVmOnHypervisorReply();
final DetachDataVolumeCmd cmd = new DetachDataVolumeCmd();
cmd.setVolume(to);
cmd.setVmUuid(vm.getUuid());
extEmitter.beforeDetachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd);
new Http<>(detachDataVolumePath, cmd, DetachDataVolumeResponse.class).call(new ReturnValueCompletion<DetachDataVolumeResponse>(msg, completion) {
@Override
public void success(DetachDataVolumeResponse ret) {
if (!ret.isSuccess()) {
ErrorCode err = operr("failed to detach data volume[uuid:%s, installPath:%s] from vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s",
vol.getUuid(), vol.getInstallPath(), vm.getUuid(), vm.getName(), getSelf().getUuid(), getSelf().getManagementIp(), ret.getError());
reply.setError(err);
extEmitter.detachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, reply.getError());
bus.reply(msg, reply);
completion.done();
} else {
extEmitter.afterDetachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd);
bus.reply(msg, reply);
completion.done();
}
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
extEmitter.detachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, reply.getError());
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final AttachVolumeToVmOnHypervisorMsg msg) {
inQueue().name(String.format("attach-volume-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> attachVolume(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
static String computeWwnIfAbsent(String volumeUUid) {
String wwn;
String tag = KVMSystemTags.VOLUME_WWN.getTag(volumeUUid);
if (tag != null) {
wwn = KVMSystemTags.VOLUME_WWN.getTokenByTag(tag, KVMSystemTags.VOLUME_WWN_TOKEN);
} else {
wwn = new WwnUtils().getRandomWwn();
SystemTagCreator creator = KVMSystemTags.VOLUME_WWN.newSystemTagCreator(volumeUUid);
creator.inherent = true;
creator.setTagByTokens(Collections.singletonMap(KVMSystemTags.VOLUME_WWN_TOKEN, wwn));
creator.create();
}
DebugUtils.Assert(new WwnUtils().isValidWwn(wwn), String.format("Not a valid wwn[%s] for volume[uuid:%s]", wwn, volumeUUid));
return wwn;
}
private String makeAndSaveVmSystemSerialNumber(String vmUuid) {
String serialNumber;
String tag = VmSystemTags.VM_SYSTEM_SERIAL_NUMBER.getTag(vmUuid);
if (tag != null) {
serialNumber = VmSystemTags.VM_SYSTEM_SERIAL_NUMBER.getTokenByTag(tag, VmSystemTags.VM_SYSTEM_SERIAL_NUMBER_TOKEN);
} else {
SystemTagCreator creator = VmSystemTags.VM_SYSTEM_SERIAL_NUMBER.newSystemTagCreator(vmUuid);
creator.ignoreIfExisting = true;
creator.inherent = true;
creator.setTagByTokens(map(e(VmSystemTags.VM_SYSTEM_SERIAL_NUMBER_TOKEN, UUID.randomUUID().toString())));
SystemTagInventory inv = creator.create();
serialNumber = VmSystemTags.VM_SYSTEM_SERIAL_NUMBER.getTokenByTag(inv.getTag(), VmSystemTags.VM_SYSTEM_SERIAL_NUMBER_TOKEN);
}
return serialNumber;
}
protected void attachVolume(final AttachVolumeToVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
KVMHostInventory host = (KVMHostInventory) getSelfInventory();
final VolumeInventory vol = msg.getInventory();
final VmInstanceInventory vm = msg.getVmInventory();
VolumeTO to = VolumeTO.valueOfWithOutExtension(vol, host, vm.getPlatform());
final AttachVolumeToVmOnHypervisorReply reply = new AttachVolumeToVmOnHypervisorReply();
final AttachDataVolumeCmd cmd = new AttachDataVolumeCmd();
cmd.setVolume(to);
cmd.setVmUuid(msg.getVmInventory().getUuid());
cmd.getAddons().put("attachedDataVolumes", VolumeTO.valueOf(msg.getAttachedDataVolumes(), host));
Map data = new HashMap();
extEmitter.beforeAttachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd, data);
new Http<>(attachDataVolumePath, cmd, AttachDataVolumeResponse.class).call(new ReturnValueCompletion<AttachDataVolumeResponse>(msg, completion) {
@Override
public void success(AttachDataVolumeResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("failed to attach data volume[uuid:%s, installPath:%s] to vm[uuid:%s, name:%s]" +
" on kvm host[uuid:%s, ip:%s], because %s", vol.getUuid(), vol.getInstallPath(), vm.getUuid(), vm.getName(),
getSelf().getUuid(), getSelf().getManagementIp(), ret.getError()));
extEmitter.attachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, reply.getError(), data);
} else {
extEmitter.afterAttachVolume((KVMHostInventory) getSelfInventory(), vm, vol, cmd);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
extEmitter.attachVolumeFailed((KVMHostInventory) getSelfInventory(), vm, vol, cmd, err, data);
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final DestroyVmOnHypervisorMsg msg) {
inQueue().name(String.format("destroy-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> destroyVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
protected void destroyVm(final DestroyVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
DestroyVmCmd cmd = new DestroyVmCmd();
cmd.setUuid(vminv.getUuid());
try {
extEmitter.beforeDestroyVmOnKvm(KVMHostInventory.valueOf(getSelf()), vminv, cmd);
} catch (KVMException e) {
ErrorCode err = operr("failed to destroy vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(),
self.getUuid(), self.getManagementIp(), e.getMessage());
throw new OperationFailureException(err);
}
new Http<>(destroyVmPath, cmd, DestroyVmResponse.class).call(new ReturnValueCompletion<DestroyVmResponse>(msg, completion) {
@Override
public void success(DestroyVmResponse ret) {
DestroyVmOnHypervisorReply reply = new DestroyVmOnHypervisorReply();
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_DESTROY_VM_ON_HYPERVISOR, "unable to destroy vm[uuid:%s, name:%s] on kvm host [uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()));
extEmitter.destroyVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError());
} else {
logger.debug(String.format("successfully destroyed vm[uuid:%s] on kvm host[uuid:%s]", vminv.getUuid(), self.getUuid()));
extEmitter.destroyVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), vminv);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
DestroyVmOnHypervisorReply reply = new DestroyVmOnHypervisorReply();
if (err.isError(SysErrors.HTTP_ERROR, SysErrors.IO_ERROR, SysErrors.TIMEOUT)) {
err = err(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, err, "unable to destroy a vm");
}
reply.setError(err);
extEmitter.destroyVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError());
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final RebootVmOnHypervisorMsg msg) {
inQueue().name(String.format("reboot-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> rebootVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private List<String> toKvmBootDev(List<String> order) {
List<String> ret = new ArrayList<String>();
for (String o : order) {
if (VmBootDevice.HardDisk.toString().equals(o)) {
ret.add(BootDev.hd.toString());
} else if (VmBootDevice.CdRom.toString().equals(o)) {
ret.add(BootDev.cdrom.toString());
} else if (VmBootDevice.Network.toString().equals(o)) {
ret.add(BootDev.network.toString());
} else {
throw new CloudRuntimeException(String.format("unknown boot device[%s]", o));
}
}
return ret;
}
private void rebootVm(final RebootVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
try {
extEmitter.beforeRebootVmOnKvm(KVMHostInventory.valueOf(getSelf()), vminv);
} catch (KVMException e) {
String err = String.format("failed to reboot vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(),
self.getUuid(), self.getManagementIp(), e.getMessage());
logger.warn(err, e);
throw new OperationFailureException(operr(err));
}
RebootVmCmd cmd = new RebootVmCmd();
long timeout = TimeUnit.MILLISECONDS.toSeconds(msg.getTimeout());
cmd.setUuid(vminv.getUuid());
cmd.setTimeout(timeout);
cmd.setBootDev(toKvmBootDev(msg.getBootOrders()));
new Http<>(rebootVmPath, cmd, RebootVmResponse.class).call(new ReturnValueCompletion<RebootVmResponse>(msg, completion) {
@Override
public void success(RebootVmResponse ret) {
RebootVmOnHypervisorReply reply = new RebootVmOnHypervisorReply();
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_REBOOT_VM_ON_HYPERVISOR, "unable to reboot vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()));
extEmitter.rebootVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError());
} else {
extEmitter.rebootVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), vminv);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
RebootVmOnHypervisorReply reply = new RebootVmOnHypervisorReply();
reply.setError(err);
extEmitter.rebootVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final StopVmOnHypervisorMsg msg) {
inQueue().name(String.format("stop-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> stopVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
protected void stopVm(final StopVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
StopVmCmd cmd = new StopVmCmd();
cmd.setUuid(vminv.getUuid());
cmd.setType(msg.getType());
cmd.setTimeout(120);
try {
extEmitter.beforeStopVmOnKvm(KVMHostInventory.valueOf(getSelf()), vminv, cmd);
} catch (KVMException e) {
ErrorCode err = operr("failed to stop vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(), vminv.getName(),
self.getUuid(), self.getManagementIp(), e.getMessage());
throw new OperationFailureException(err);
}
new Http<>(stopVmPath, cmd, StopVmResponse.class).call(new ReturnValueCompletion<StopVmResponse>(msg, completion) {
@Override
public void success(StopVmResponse ret) {
StopVmOnHypervisorReply reply = new StopVmOnHypervisorReply();
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR, "unable to stop vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()));
logger.warn(reply.getError().getDetails());
extEmitter.stopVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, reply.getError());
} else {
extEmitter.stopVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), vminv);
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
StopVmOnHypervisorReply reply = new StopVmOnHypervisorReply();
if (err.isError(SysErrors.IO_ERROR, SysErrors.HTTP_ERROR)) {
err = err(HostErrors.OPERATION_FAILURE_GC_ELIGIBLE, err, "unable to stop a vm");
}
reply.setError(err);
extEmitter.stopVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), vminv, err);
bus.reply(msg, reply);
completion.done();
}
});
}
@Transactional
private void setDataVolumeUseVirtIOSCSI(final VmInstanceSpec spec) {
String vmUuid = spec.getVmInventory().getUuid();
Map<String, Integer> diskOfferingUuid_Num = new HashMap<>();
List<Map<String, String>> tokenList = KVMSystemTags.DISK_OFFERING_VIRTIO_SCSI.getTokensOfTagsByResourceUuid(vmUuid);
for (Map<String, String> tokens : tokenList) {
String diskOfferingUuid = tokens.get(KVMSystemTags.DISK_OFFERING_VIRTIO_SCSI_TOKEN);
Integer num = Integer.parseInt(tokens.get(KVMSystemTags.DISK_OFFERING_VIRTIO_SCSI_NUM_TOKEN));
diskOfferingUuid_Num.put(diskOfferingUuid, num);
}
for (VolumeInventory volumeInv : spec.getDestDataVolumes()) {
if (volumeInv.getType().equals(VolumeType.Root.toString())) {
continue;
}
if (diskOfferingUuid_Num.containsKey(volumeInv.getDiskOfferingUuid())
&& diskOfferingUuid_Num.get(volumeInv.getDiskOfferingUuid()) > 0) {
tagmgr.createNonInherentSystemTag(volumeInv.getUuid(),
KVMSystemTags.VOLUME_VIRTIO_SCSI.getTagFormat(),
VolumeVO.class.getSimpleName());
diskOfferingUuid_Num.put(volumeInv.getDiskOfferingUuid(),
diskOfferingUuid_Num.get(volumeInv.getDiskOfferingUuid()) - 1);
}
}
}
@Transactional
private void setVmNicMultiqueueNum(final VmInstanceSpec spec) {
try {
if (!ImagePlatform.isType(spec.getImageSpec().getInventory().getPlatform(), ImagePlatform.Linux)) {
return;
}
if (!rcf.getResourceConfigValue(KVMGlobalConfig.AUTO_VM_NIC_MULTIQUEUE,
spec.getDestHost().getClusterUuid(), Boolean.class)) {
return;
}
ResourceConfig multiQueues = rcf.getResourceConfig(VmGlobalConfig.VM_NIC_MULTIQUEUE_NUM.getIdentity());
Integer queues = spec.getVmInventory().getCpuNum() > KVMConstant.DEFAULT_MAX_NIC_QUEUE_NUMBER ? KVMConstant.DEFAULT_MAX_NIC_QUEUE_NUMBER : spec.getVmInventory().getCpuNum();
multiQueues.updateValue(spec.getVmInventory().getUuid(), queues.toString());
} catch (Exception e) {
logger.warn(String.format("got exception when trying set nic multiqueue for vm: %s, %s", spec.getVmInventory().getUuid(), e));
}
}
private void handle(final CreateVmOnHypervisorMsg msg) {
inQueue().name(String.format("start-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> {
setDataVolumeUseVirtIOSCSI(msg.getVmSpec());
setVmNicMultiqueueNum(msg.getVmSpec());
startVm(msg.getVmSpec(), msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
});
});
}
private void handle(final UpdateSpiceChannelConfigMsg msg) {
UpdateSpiceChannelConfigReply reply = new UpdateSpiceChannelConfigReply();
UpdateSpiceChannelConfigCmd cmd = new UpdateSpiceChannelConfigCmd();
new Http<>(updateSpiceChannelConfigPath, cmd, UpdateSpiceChannelConfigResponse.class).call(new ReturnValueCompletion<UpdateSpiceChannelConfigResponse>(msg) {
@Override
public void success(UpdateSpiceChannelConfigResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("Host[%s] update spice channel config faild, because %s", msg.getHostUuid(), ret.getError()));
logger.warn(reply.getError().getDetails());
}
reply.setRestartLibvirt(ret.restartLibvirt);
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
}
});
}
private L2NetworkInventory getL2NetworkTypeFromL3NetworkUuid(String l3NetworkUuid) {
String sql = "select l2 from L2NetworkVO l2 where l2.uuid = (select l3.l2NetworkUuid from L3NetworkVO l3 where l3.uuid = :l3NetworkUuid)";
TypedQuery<L2NetworkVO> query = dbf.getEntityManager().createQuery(sql, L2NetworkVO.class);
query.setParameter("l3NetworkUuid", l3NetworkUuid);
L2NetworkVO l2vo = query.getSingleResult();
return L2NetworkInventory.valueOf(l2vo);
}
@Transactional(readOnly = true)
private NicTO completeNicInfo(VmNicInventory nic) {
/* all l3 networks of the nic has same l2 network */
L3NetworkInventory l3Inv = L3NetworkInventory.valueOf(dbf.findByUuid(nic.getL3NetworkUuid(), L3NetworkVO.class));
L2NetworkInventory l2inv = getL2NetworkTypeFromL3NetworkUuid(nic.getL3NetworkUuid());
KVMCompleteNicInformationExtensionPoint extp = factory.getCompleteNicInfoExtension(L2NetworkType.valueOf(l2inv.getType()));
NicTO to = extp.completeNicInformation(l2inv, l3Inv, nic);
if (to.getUseVirtio() == null) {
to.setUseVirtio(VmSystemTags.VIRTIO.hasTag(nic.getVmInstanceUuid()));
to.setIps(getCleanTrafficIp(nic));
}
if (!nic.getType().equals(VmInstanceConstant.VIRTUAL_NIC_TYPE)) {
return to;
}
// build vhost addon
if (to.getDriverType() == null) {
if (nic.getDriverType() != null) {
to.setDriverType(nic.getDriverType());
} else {
to.setDriverType(to.getUseVirtio() ? nicManager.getDefaultPVNicDriver() : nicManager.getDefaultNicDriver());
}
}
VHostAddOn vHostAddOn = new VHostAddOn();
if (to.getDriverType().equals(nicManager.getDefaultPVNicDriver())) {
vHostAddOn.setQueueNum(rcf.getResourceConfigValue(VmGlobalConfig.VM_NIC_MULTIQUEUE_NUM, nic.getVmInstanceUuid(), Integer.class));
} else {
vHostAddOn.setQueueNum(VmGlobalConfig.VM_NIC_MULTIQUEUE_NUM.defaultValue(Integer.class));
}
if (VmSystemTags.VM_VRING_BUFFER_SIZE.hasTag(nic.getVmInstanceUuid())) {
Map<String, String> tokens = VmSystemTags.VM_VRING_BUFFER_SIZE.getTokensByResourceUuid(nic.getVmInstanceUuid());
if (tokens.get(VmSystemTags.RX_SIZE_TOKEN) != null) {
vHostAddOn.setRxBufferSize(tokens.get(VmSystemTags.RX_SIZE_TOKEN));
}
if (tokens.get(VmSystemTags.TX_SIZE_TOKEN) != null) {
vHostAddOn.setTxBufferSize(tokens.get(VmSystemTags.TX_SIZE_TOKEN));
}
}
to.setvHostAddOn(vHostAddOn);
String pci = KVMSystemTags.VMNIC_PCI_ADDRESS.getTokenByResourceUuid(nic.getUuid(), KVMSystemTags.VMNIC_PCI_ADDRESS_TOKEN);
if (pci != null) {
to.setPci(PciAddressConfig.fromString(pci));
}
return to;
}
private List<String> getCleanTrafficIp(VmNicInventory nic) {
boolean isUserVm = Q.New(VmInstanceVO.class)
.eq(VmInstanceVO_.uuid, nic.getVmInstanceUuid()).select(VmInstanceVO_.type)
.findValue().equals(VmInstanceConstant.USER_VM_TYPE);
if (!isUserVm) {
return null;
}
String tagValue = VmSystemTags.CLEAN_TRAFFIC.getTokenByResourceUuid(nic.getVmInstanceUuid(), VmSystemTags.CLEAN_TRAFFIC_TOKEN);
if (Boolean.parseBoolean(tagValue) || (tagValue == null && VmGlobalConfig.VM_CLEAN_TRAFFIC.value(Boolean.class))) {
return VmNicHelper.getIpAddresses(nic);
}
return null;
}
static String getVolumeTOType(VolumeInventory vol) {
DebugUtils.Assert(vol.getInstallPath() != null, String.format("volume [%s] installPath is null, it has not been initialized", vol.getUuid()));
return vol.getInstallPath().startsWith("iscsi") ? VolumeTO.ISCSI : VolumeTO.FILE;
}
private void checkPlatformWithOther(VmInstanceSpec spec) {
int total = spec.getDestDataVolumes().size() + spec.getDestCacheVolumes().size() + spec.getCdRomSpecs().size();
if (total > 3) {
throw new OperationFailureException(operr("when the vm platform is Other, the number of dataVolumes and cdroms cannot exceed 3, currently %s", total));
}
}
protected void startVm(final VmInstanceSpec spec, final NeedReplyMessage msg, final NoErrorCompletion completion) {
checkStateAndStatus();
final StartVmCmd cmd = new StartVmCmd();
String platform = spec.getVmInventory().getPlatform() == null ? spec.getImageSpec().getInventory().getPlatform() :
spec.getVmInventory().getPlatform();
if(ImagePlatform.Other.toString().equals(platform)){
checkPlatformWithOther(spec);
}
String architecture = spec.getDestHost().getArchitecture();
int cpuNum = spec.getVmInventory().getCpuNum();
cmd.setCpuNum(cpuNum);
int socket;
int cpuOnSocket;
//TODO: this is a HACK!!!
if (ImagePlatform.Windows.toString().equals(platform) || ImagePlatform.WindowsVirtio.toString().equals(platform)) {
if (cpuNum == 1) {
socket = 1;
cpuOnSocket = 1;
} else if (cpuNum % 2 == 0) {
socket = 2;
cpuOnSocket = cpuNum / 2;
} else {
socket = cpuNum;
cpuOnSocket = 1;
}
} else {
socket = 1;
cpuOnSocket = cpuNum;
}
cmd.setImagePlatform(platform);
cmd.setImageArchitecture(architecture);
cmd.setSocketNum(socket);
cmd.setCpuOnSocket(cpuOnSocket);
cmd.setVmName(spec.getVmInventory().getName());
cmd.setVmInstanceUuid(spec.getVmInventory().getUuid());
cmd.setCpuSpeed(spec.getVmInventory().getCpuSpeed());
cmd.setMemory(spec.getVmInventory().getMemorySize());
cmd.setMaxMemory(self.getCapacity().getTotalPhysicalMemory());
cmd.setClock(ImagePlatform.isType(platform, ImagePlatform.Windows, ImagePlatform.WindowsVirtio) ? "localtime" : "utc");
if (VmSystemTags.CLOCK_TRACK.hasTag(spec.getVmInventory().getUuid())) {
cmd.setClockTrack(VmSystemTags.CLOCK_TRACK.getTokenByResourceUuid(spec.getVmInventory().getUuid(), VmInstanceVO.class, VmSystemTags.CLOCK_TRACK_TOKEN));
}
cmd.setVideoType(VmGlobalConfig.VM_VIDEO_TYPE.value(String.class));
if (VmSystemTags.QXL_MEMORY.hasTag(spec.getVmInventory().getUuid())) {
Map<String,String> qxlMemory = VmSystemTags.QXL_MEMORY.getTokensByResourceUuid(spec.getVmInventory().getUuid());
cmd.setQxlMemory(qxlMemory);
}
if (VmSystemTags.SOUND_TYPE.hasTag(spec.getVmInventory().getUuid())) {
cmd.setSoundType(VmSystemTags.SOUND_TYPE.getTokenByResourceUuid(spec.getVmInventory().getUuid(), VmInstanceVO.class, VmSystemTags.SOUND_TYPE_TOKEN));
}
cmd.setInstanceOfferingOnlineChange(VmSystemTags.INSTANCEOFFERING_ONLIECHANGE.getTokenByResourceUuid(spec.getVmInventory().getUuid(), VmSystemTags.INSTANCEOFFERING_ONLINECHANGE_TOKEN) != null);
cmd.setKvmHiddenState(rcf.getResourceConfigValue(VmGlobalConfig.KVM_HIDDEN_STATE, spec.getVmInventory().getUuid(), Boolean.class));
cmd.setSpiceStreamingMode(VmGlobalConfig.VM_SPICE_STREAMING_MODE.value(String.class));
cmd.setEmulateHyperV(!ImagePlatform.isType(platform, ImagePlatform.Linux) && rcf.getResourceConfigValue(VmGlobalConfig.EMULATE_HYPERV, spec.getVmInventory().getUuid(), Boolean.class));
cmd.setVendorId(rcf.getResourceConfigValue(VmGlobalConfig.VENDOR_ID, spec.getVmInventory().getUuid(), String.class));
cmd.setAdditionalQmp(VmGlobalConfig.ADDITIONAL_QMP.value(Boolean.class));
cmd.setApplianceVm(spec.getVmInventory().getType().equals("ApplianceVm"));
cmd.setSystemSerialNumber(makeAndSaveVmSystemSerialNumber(spec.getVmInventory().getUuid()));
if (!NetworkGlobalProperty.CHASSIS_ASSET_TAG.isEmpty()) {
cmd.setChassisAssetTag(NetworkGlobalProperty.CHASSIS_ASSET_TAG);
}
String machineType = VmSystemTags.MACHINE_TYPE.getTokenByResourceUuid(cmd.getVmInstanceUuid(),
VmInstanceVO.class, VmSystemTags.MACHINE_TYPE_TOKEN);
cmd.setMachineType(StringUtils.isNotEmpty(machineType) ? machineType : "pc");
if (KVMSystemTags.VM_PREDEFINED_PCI_BRIDGE_NUM.hasTag(spec.getVmInventory().getUuid())) {
cmd.setPredefinedPciBridgeNum(Integer.valueOf(KVMSystemTags.VM_PREDEFINED_PCI_BRIDGE_NUM.getTokenByResourceUuid(spec.getVmInventory().getUuid(), KVMSystemTags.VM_PREDEFINED_PCI_BRIDGE_NUM_TOKEN)));
}
if (VmMachineType.q35.toString().equals(machineType) || VmMachineType.virt.toString().equals(machineType)) {
cmd.setPciePortNums(VmGlobalConfig.PCIE_PORT_NUMS.value(Integer.class));
if (cmd.getPredefinedPciBridgeNum() == null) {
cmd.setPredefinedPciBridgeNum(1);
}
}
VmPriorityLevel level = new VmPriorityOperator().getVmPriority(spec.getVmInventory().getUuid());
VmPriorityConfigVO priorityVO = Q.New(VmPriorityConfigVO.class).eq(VmPriorityConfigVO_.level, level).find();
cmd.setPriorityConfigStruct(new PriorityConfigStruct(priorityVO, spec.getVmInventory().getUuid()));
VolumeTO rootVolume = new VolumeTO();
rootVolume.setInstallPath(spec.getDestRootVolume().getInstallPath());
rootVolume.setDeviceId(spec.getDestRootVolume().getDeviceId());
rootVolume.setDeviceType(getVolumeTOType(spec.getDestRootVolume()));
rootVolume.setVolumeUuid(spec.getDestRootVolume().getUuid());
rootVolume.setUseVirtio(VmSystemTags.VIRTIO.hasTag(spec.getVmInventory().getUuid()));
rootVolume.setUseVirtioSCSI(ImagePlatform.Other.toString().equals(platform) ? false : KVMSystemTags.VOLUME_VIRTIO_SCSI.hasTag(spec.getDestRootVolume().getUuid()));
rootVolume.setWwn(computeWwnIfAbsent(spec.getDestRootVolume().getUuid()));
rootVolume.setCacheMode(KVMGlobalConfig.LIBVIRT_CACHE_MODE.value());
cmd.setNestedVirtualization( rcf.getResourceConfigValue(KVMGlobalConfig.NESTED_VIRTUALIZATION, spec.getVmInventory().getUuid(), String.class) );
cmd.setRootVolume(rootVolume);
cmd.setUseBootMenu(VmGlobalConfig.VM_BOOT_MENU.value(Boolean.class));
List<VolumeTO> dataVolumes = new ArrayList<>(spec.getDestDataVolumes().size());
for (VolumeInventory data : spec.getDestDataVolumes()) {
VolumeTO v = VolumeTO.valueOfWithOutExtension(data, (KVMHostInventory) getSelfInventory(), spec.getVmInventory().getPlatform());
// except for platform = Other, always use virtio driver for data volume
v.setUseVirtio(!ImagePlatform.Other.toString().equals(platform));
dataVolumes.add(v);
}
dataVolumes.sort(Comparator.comparing(VolumeTO::getDeviceId));
cmd.setDataVolumes(dataVolumes);
List<VolumeTO> cacheVolumes = new ArrayList<>(spec.getDestCacheVolumes().size());
for (VolumeInventory data : spec.getDestCacheVolumes()) {
VolumeTO v = VolumeTO.valueOfWithOutExtension(data, (KVMHostInventory) getSelfInventory(), spec.getVmInventory().getPlatform());
// except for platform = Other, always use virtio driver for data volume
v.setUseVirtio(!ImagePlatform.Other.toString().equals(platform));
cacheVolumes.add(v);
}
cmd.setCacheVolumes(cacheVolumes);
cmd.setVmInternalId(spec.getVmInventory().getInternalId());
List<NicTO> nics = new ArrayList<>(spec.getDestNics().size());
for (VmNicInventory nic : spec.getDestNics()) {
NicTO to = completeNicInfo(nic);
nics.add(to);
}
nics = nics.stream().sorted(Comparator.comparing(NicTO::getDeviceId)).collect(Collectors.toList());
cmd.setNics(nics);
for (VmInstanceSpec.CdRomSpec cdRomSpec : spec.getCdRomSpecs()) {
CdRomTO cdRomTO = new CdRomTO();
cdRomTO.setPath(cdRomSpec.getInstallPath());
cdRomTO.setImageUuid(cdRomSpec.getImageUuid());
cdRomTO.setDeviceId(cdRomSpec.getDeviceId());
cdRomTO.setEmpty(cdRomSpec.getImageUuid() == null);
cmd.getCdRoms().add(cdRomTO);
}
String bootMode = VmSystemTags.BOOT_MODE.getTokenByResourceUuid(spec.getVmInventory().getUuid(), VmSystemTags.BOOT_MODE_TOKEN);
cmd.setBootMode(bootMode == null ? ImageBootMode.Legacy.toString() : bootMode);
deviceBootOrderOperator.updateVmDeviceBootOrder(cmd, spec);
cmd.setBootDev(toKvmBootDev(spec.getBootOrders()));
cmd.setHostManagementIp(self.getManagementIp());
cmd.setConsolePassword(spec.getConsolePassword());
cmd.setUsbRedirect(spec.getUsbRedirect());
cmd.setVDIMonitorNumber(Integer.valueOf(spec.getVDIMonitorNumber()));
cmd.setUseNuma(rcf.getResourceConfigValue(VmGlobalConfig.NUMA, spec.getVmInventory().getUuid(), Boolean.class));
cmd.setVmPortOff(VmGlobalConfig.VM_PORT_OFF.value(Boolean.class));
cmd.setConsoleMode("vnc");
cmd.setTimeout(TimeUnit.MINUTES.toSeconds(5));
cmd.setConsoleLogToFile(!VmInstanceConstant.USER_VM_TYPE.equals(spec.getVmInventory().getType()));
if (spec.isCreatePaused()) {
cmd.setCreatePaused(true);
}
String vmArchPlatformRelease = String.format("%s_%s_%s", spec.getVmInventory().getArchitecture(), spec.getVmInventory().getPlatform(), spec.getVmInventory().getGuestOsType());
if (allGuestOsCharacter.containsKey(vmArchPlatformRelease)) {
cmd.setAcpi(allGuestOsCharacter.get(vmArchPlatformRelease).getAcpi() != null && allGuestOsCharacter.get(vmArchPlatformRelease).getAcpi());
cmd.setHygonCpu(allGuestOsCharacter.get(vmArchPlatformRelease).getHygonCpu() != null && allGuestOsCharacter.get(vmArchPlatformRelease).getHygonCpu());
}
addons(spec, cmd);
KVMHostInventory khinv = KVMHostInventory.valueOf(getSelf());
extEmitter.beforeStartVmOnKvm(khinv, spec, cmd);
extEmitter.addOn(khinv, spec, cmd);
new Http<>(startVmPath, cmd, StartVmResponse.class).call(new ReturnValueCompletion<StartVmResponse>(msg, completion) {
@Override
public void success(StartVmResponse ret) {
StartVmOnHypervisorReply reply = new StartVmOnHypervisorReply();
if (ret.isSuccess()) {
String info = String.format("successfully start vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s]",
spec.getVmInventory().getUuid(), spec.getVmInventory().getName(),
self.getUuid(), self.getManagementIp());
logger.debug(info);
extEmitter.startVmOnKvmSuccess(KVMHostInventory.valueOf(getSelf()), spec);
} else {
reply.setError(err(HostErrors.FAILED_TO_START_VM_ON_HYPERVISOR, "failed to start vm[uuid:%s name:%s] on kvm host[uuid:%s, ip:%s], because %s",
spec.getVmInventory().getUuid(), spec.getVmInventory().getName(),
self.getUuid(), self.getManagementIp(), ret.getError()));
logger.warn(reply.getError().getDetails());
extEmitter.startVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), spec, reply.getError());
}
if (ret.getNicInfos() != null && !ret.getNicInfos().isEmpty()) {
Map<String, VmNicInventory> macNicMap = new HashMap<>();
for (VmNicInventory nic : spec.getDestNics()) {
macNicMap.put(nic.getMac(), nic);
}
for (VmNicInfo vmNicInfo : ret.getNicInfos()) {
VmNicInventory nic = macNicMap.get(vmNicInfo.getMacAddress());
if (nic == null) {
continue;
}
SystemTagCreator creator = KVMSystemTags.VMNIC_PCI_ADDRESS.newSystemTagCreator(nic.getUuid());
creator.inherent = true;
creator.recreate = true;
creator.setTagByTokens(map(e(KVMSystemTags.VMNIC_PCI_ADDRESS_TOKEN, vmNicInfo.getPciInfo().toString())));
creator.create();
}
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
StartVmOnHypervisorReply reply = new StartVmOnHypervisorReply();
reply.setError(err);
reply.setSuccess(false);
extEmitter.startVmOnKvmFailed(KVMHostInventory.valueOf(getSelf()), spec, err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void addons(final VmInstanceSpec spec, StartVmCmd cmd) {
KVMAddons.Channel chan = new KVMAddons.Channel();
chan.setSocketPath(makeChannelSocketPath(spec.getVmInventory().getUuid()));
chan.setTargetName("org.qemu.guest_agent.0");
cmd.getAddons().put(KVMAddons.Channel.NAME, chan);
logger.debug(String.format("make kvm channel device[path:%s, target:%s]", chan.getSocketPath(), chan.getTargetName()));
}
private String makeChannelSocketPath(String apvmuuid) {
return PathUtil.join(String.format("/var/lib/libvirt/qemu/%s", apvmuuid));
}
private void handle(final StartVmOnHypervisorMsg msg) {
inQueue().name(String.format("start-vm-on-kvm-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> startVmInQueue(msg, chain));
}
private void startVmInQueue(StartVmOnHypervisorMsg msg, SyncTaskChain outterChain) {
thdf.chainSubmit(new ChainTask(msg, outterChain) {
@Override
public String getSyncSignature() {
return getName();
}
@Override
public void run(final SyncTaskChain chain) {
startVm(msg.getVmSpec(), msg, new NoErrorCompletion(chain, outterChain) {
@Override
public void done() {
chain.next();
outterChain.next();
}
});
}
@Override
public String getName() {
return String.format("start-vm-on-kvm-%s-inner-queue", self.getUuid());
}
@Override
protected int getSyncLevel() {
return KVMGlobalConfig.VM_CREATE_CONCURRENCY.value(Integer.class);
}
});
}
private void handle(final CheckNetworkPhysicalInterfaceMsg msg) {
inQueue().name(String.format("check-network-physical-interface-on-host-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> checkPhysicalInterface(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void handle(final BatchCheckNetworkPhysicalInterfaceMsg msg) {
inQueue().name(String.format("check-network-physical-interface-on-host-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> batchCheckPhysicalInterface(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void pauseVm(final PauseVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
PauseVmOnHypervisorReply reply = new PauseVmOnHypervisorReply();
PauseVmCmd cmd = new PauseVmCmd();
cmd.setUuid(vminv.getUuid());
cmd.setTimeout(120);
new Http<>(pauseVmPath, cmd, PauseVmResponse.class).call(new ReturnValueCompletion<PauseVmResponse>(msg, completion) {
@Override
public void success(PauseVmResponse ret) {
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR, "unable to pause vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()));
logger.warn(reply.getError().getDetails());
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void handle(final PauseVmOnHypervisorMsg msg) {
inQueue().name(String.format("pause-vm-%s-on-host-%s", msg.getVmInventory().getUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> pauseVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void handle(final ResumeVmOnHypervisorMsg msg) {
inQueue().name(String.format("resume-vm-%s-on-host-%s", msg.getVmInventory().getUuid(), self.getUuid()))
.asyncBackup(msg)
.run(chain -> resumeVm(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void resumeVm(final ResumeVmOnHypervisorMsg msg, final NoErrorCompletion completion) {
checkStatus();
final VmInstanceInventory vminv = msg.getVmInventory();
ResumeVmOnHypervisorReply reply = new ResumeVmOnHypervisorReply();
ResumeVmCmd cmd = new ResumeVmCmd();
cmd.setUuid(vminv.getUuid());
cmd.setTimeout(120);
new Http<>(resumeVmPath, cmd, ResumeVmResponse.class).call(new ReturnValueCompletion<ResumeVmResponse>(msg, completion) {
@Override
public void success(ResumeVmResponse ret) {
if (!ret.isSuccess()) {
reply.setError(err(HostErrors.FAILED_TO_STOP_VM_ON_HYPERVISOR, "unable to resume vm[uuid:%s, name:%s] on kvm host[uuid:%s, ip:%s], because %s", vminv.getUuid(),
vminv.getName(), self.getUuid(), self.getManagementIp(), ret.getError()));
logger.warn(reply.getError().getDetails());
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
});
}
private void batchCheckPhysicalInterface(BatchCheckNetworkPhysicalInterfaceMsg msg, NoErrorCompletion completion) {
checkState();
CheckPhysicalNetworkInterfaceCmd cmd = new CheckPhysicalNetworkInterfaceCmd();
msg.getPhysicalInterfaces().forEach(cmd::addInterfaceName);
BatchCheckNetworkPhysicalInterfaceReply reply = new BatchCheckNetworkPhysicalInterfaceReply();
CheckPhysicalNetworkInterfaceResponse rsp = restf.syncJsonPost(checkPhysicalNetworkInterfacePath, cmd, CheckPhysicalNetworkInterfaceResponse.class);
if (!rsp.isSuccess()) {
if (rsp.getFailedInterfaceNames().isEmpty()) {
reply.setError(operr("operation error, because:%s", rsp.getError()));
} else {
reply.setError(operr("failed to check physical network interfaces[names : %s] on kvm host[uuid:%s, ip:%s]",
rsp.getFailedInterfaceNames(), context.getInventory().getUuid(), context.getInventory().getManagementIp()));
}
}
bus.reply(msg, reply);
completion.done();
}
private void checkPhysicalInterface(CheckNetworkPhysicalInterfaceMsg msg, NoErrorCompletion completion) {
checkState();
CheckPhysicalNetworkInterfaceCmd cmd = new CheckPhysicalNetworkInterfaceCmd();
cmd.addInterfaceName(msg.getPhysicalInterface());
CheckNetworkPhysicalInterfaceReply reply = new CheckNetworkPhysicalInterfaceReply();
CheckPhysicalNetworkInterfaceResponse rsp = restf.syncJsonPost(checkPhysicalNetworkInterfacePath, cmd, CheckPhysicalNetworkInterfaceResponse.class);
if (!rsp.isSuccess()) {
if (rsp.getFailedInterfaceNames().isEmpty()) {
reply.setError(operr("operation error, because:%s", rsp.getError()));
} else {
reply.setError(operr("failed to check physical network interfaces[names : %s] on kvm host[uuid:%s, ip:%s]",
msg.getPhysicalInterface(), context.getInventory().getUuid(), context.getInventory().getManagementIp()));
}
}
bus.reply(msg, reply);
completion.done();
}
@Override
public void handleMessage(Message msg) {
try {
if (msg instanceof APIMessage) {
handleApiMessage((APIMessage) msg);
} else {
handleLocalMessage(msg);
}
} catch (Exception e) {
bus.logExceptionWithMessageDump(msg, e);
bus.replyErrorByMessageType(msg, e);
}
}
@Override
public void changeStateHook(HostState current, HostStateEvent stateEvent, HostState next) {
}
@Override
public void deleteHook() {
}
@Override
protected HostInventory getSelfInventory() {
return KVMHostInventory.valueOf(getSelf());
}
private void doUpdateHostConfiguration() {
thdf.chainSubmit(new ChainTask(null) {
@Override
public String getSyncSignature() {
return String.format("update-kvm-host-configuration-%s", self.getUuid());
}
@Override
public void run(SyncTaskChain chain) {
UpdateHostConfigurationCmd cmd = new UpdateHostConfigurationCmd();
cmd.hostUuid = self.getUuid();
cmd.sendCommandUrl = restf.getSendCommandUrl();
restf.asyncJsonPost(updateHostConfigurationPath, cmd, new JsonAsyncRESTCallback<UpdateHostConfigurationResponse>(chain) {
@Override
public void fail(ErrorCode err) {
String info = "Failed to update host configuration request for host reconnect";
logger.warn(info);
changeConnectionState(HostStatusEvent.disconnected);
new HostDisconnectedCanonicalEvent(self.getUuid(), argerr(info)).fire();
ReconnectHostMsg rmsg = new ReconnectHostMsg();
rmsg.setHostUuid(self.getUuid());
bus.makeTargetServiceIdByResourceUuid(rmsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(rmsg);
chain.next();
}
@Override
public void success(UpdateHostConfigurationResponse rsp) {
logger.debug("Update host configuration success");
chain.next();
}
@Override
public Class<UpdateHostConfigurationResponse> getReturnClass() {
return UpdateHostConfigurationResponse.class;
}
}, TimeUnit.SECONDS, 30);
}
protected int getMaxPendingTasks() {
return 1;
}
protected String getDeduplicateString() {
return getSyncSignature();
}
@Override
public String getName() {
return getSyncSignature();
}
});
}
boolean needReconnectHost(PingResponse rsp) {
return !self.getUuid().equals(rsp.getHostUuid()) || !dbf.getDbVersion().equals(rsp.getVersion());
}
boolean needUpdateHostConfiguration(PingResponse rsp) {
// host uuid or send command url or version changed
return !restf.getSendCommandUrl().equals(rsp.getSendCommandUrl());
}
@Override
protected void pingHook(final Completion completion) {
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("ping-kvm-host-%s", self.getUuid()));
chain.then(new ShareFlow() {
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "ping-host";
@AfterDone
List<Runnable> afterDone = new ArrayList<>();
@Override
public void run(FlowTrigger trigger, Map data) {
PingCmd cmd = new PingCmd();
cmd.hostUuid = self.getUuid();
restf.asyncJsonPost(pingPath, cmd, new JsonAsyncRESTCallback<PingResponse>(trigger) {
@Override
public void fail(ErrorCode err) {
trigger.fail(err);
}
@Override
public void success(PingResponse ret) {
if (ret.isSuccess()) {
if (needUpdateHostConfiguration(ret)) {
afterDone.add(KVMHost.this::doUpdateHostConfiguration);
} else if (needReconnectHost(ret)) {
afterDone.add(() -> {
String info = i18n("detected abnormal status[host uuid change, expected: %s but: %s or agent version change, expected: %s but: %s] of kvmagent," +
"it's mainly caused by kvmagent restarts behind zstack management server. Report this to ping task, it will issue a reconnect soon",
self.getUuid(), ret.getHostUuid(), dbf.getDbVersion(), ret.getVersion());
logger.warn(info);
// when host is connecting, skip handling agent config changed issue
// and agent config change will be detected by next ping
self = dbf.reload(self);
if (self.getStatus() == HostStatus.Connecting) {
logger.debug("host status is %s, ignore version or host uuid changed issue");
return;
}
changeConnectionState(HostStatusEvent.disconnected);
new HostDisconnectedCanonicalEvent(self.getUuid(), argerr(info)).fire();
ReconnectHostMsg rmsg = new ReconnectHostMsg();
rmsg.setHostUuid(self.getUuid());
bus.makeTargetServiceIdByResourceUuid(rmsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(rmsg);
});
}
trigger.next();
} else {
trigger.fail(operr("%s", ret.getError()));
}
}
@Override
public Class<PingResponse> getReturnClass() {
return PingResponse.class;
}
},TimeUnit.SECONDS, HostGlobalConfig.PING_HOST_TIMEOUT.value(Long.class));
}
});
flow(new NoRollbackFlow() {
String __name__ = "call-ping-no-failure-plugins";
@Override
public void run(FlowTrigger trigger, Map data) {
List<KVMPingAgentNoFailureExtensionPoint> exts = pluginRgty.getExtensionList(KVMPingAgentNoFailureExtensionPoint.class);
if (exts.isEmpty()) {
trigger.next();
return;
}
AsyncLatch latch = new AsyncLatch(exts.size(), new NoErrorCompletion(trigger) {
@Override
public void done() {
trigger.next();
}
});
KVMHostInventory inv = (KVMHostInventory) getSelfInventory();
for (KVMPingAgentNoFailureExtensionPoint ext : exts) {
ext.kvmPingAgentNoFailure(inv, new NoErrorCompletion(latch) {
@Override
public void done() {
latch.ack();
}
});
}
}
});
flow(new NoRollbackFlow() {
String __name__ = "call-ping-plugins";
@Override
public void run(FlowTrigger trigger, Map data) {
List<KVMPingAgentExtensionPoint> exts = pluginRgty.getExtensionList(KVMPingAgentExtensionPoint.class);
Iterator<KVMPingAgentExtensionPoint> it = exts.iterator();
callPlugin(it, trigger);
}
private void callPlugin(Iterator<KVMPingAgentExtensionPoint> it, FlowTrigger trigger) {
if (!it.hasNext()) {
trigger.next();
return;
}
KVMPingAgentExtensionPoint ext = it.next();
logger.debug(String.format("calling KVMPingAgentExtensionPoint[%s]", ext.getClass()));
ext.kvmPingAgent((KVMHostInventory) getSelfInventory(), new Completion(trigger) {
@Override
public void success() {
callPlugin(it, trigger);
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
completion.success();
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
});
}
}).start();
}
@Override
protected void deleteTakeOverFlag(Completion completion) {
if (CoreGlobalProperty.UNIT_TEST_ON) {
completion.success();
return;
}
SshShell sshShell = new SshShell();
sshShell.setHostname(getSelf().getManagementIp());
sshShell.setUsername(getSelf().getUsername());
sshShell.setPassword(getSelf().getPassword());
sshShell.setPort(getSelf().getPort());
SshResult ret = sshShell.runCommand(String.format("sudo /bin/sh -c \"rm -rf %s\"", hostTakeOverFlagPath));
if (ret.isSshFailure() || ret.getReturnCode() != 0) {
completion.fail(operr(ret.getExitErrorMessage()));
return;
}
completion.success();
}
@Override
protected int getVmMigrateQuantity() {
return KVMGlobalConfig.VM_MIGRATION_QUANTITY.value(Integer.class);
}
private ErrorCode connectToAgent() {
ErrorCode errCode = null;
try {
ConnectCmd cmd = new ConnectCmd();
cmd.setHostUuid(self.getUuid());
cmd.setSendCommandUrl(restf.getSendCommandUrl());
cmd.setIptablesRules(KVMGlobalProperty.IPTABLES_RULES);
cmd.setIgnoreMsrs(KVMGlobalConfig.KVM_IGNORE_MSRS.value(Boolean.class));
cmd.setTcpServerPort(KVMGlobalProperty.TCP_SERVER_PORT);
cmd.setVersion(dbf.getDbVersion());
if (HostSystemTags.PAGE_TABLE_EXTENSION_DISABLED.hasTag(self.getUuid(), HostVO.class) || !KVMSystemTags.EPT_CPU_FLAG.hasTag(self.getUuid())) {
cmd.setPageTableExtensionDisabled(true);
}
ConnectResponse rsp = restf.syncJsonPost(connectPath, cmd, ConnectResponse.class);
if (!rsp.isSuccess() || !rsp.isIptablesSucc()) {
errCode = operr("unable to connect to kvm host[uuid:%s, ip:%s, url:%s], because %s",
self.getUuid(), self.getManagementIp(), connectPath, rsp.getError());
} else {
VersionComparator libvirtVersion = new VersionComparator(rsp.getLibvirtVersion());
VersionComparator qemuVersion = new VersionComparator(rsp.getQemuVersion());
boolean liveSnapshot = libvirtVersion.compare(KVMConstant.MIN_LIBVIRT_LIVESNAPSHOT_VERSION) >= 0
&& qemuVersion.compare(KVMConstant.MIN_QEMU_LIVESNAPSHOT_VERSION) >= 0;
String hostOS = HostSystemTags.OS_DISTRIBUTION.getTokenByResourceUuid(self.getUuid(), HostSystemTags.OS_DISTRIBUTION_TOKEN);
//liveSnapshot = liveSnapshot && (!"CentOS".equals(hostOS) || KVMGlobalConfig.ALLOW_LIVE_SNAPSHOT_ON_REDHAT.value(Boolean.class));
if (liveSnapshot) {
logger.debug(String.format("kvm host[OS:%s, uuid:%s, name:%s, ip:%s] supports live snapshot with libvirt[version:%s], qemu[version:%s]",
hostOS, self.getUuid(), self.getName(), self.getManagementIp(), rsp.getLibvirtVersion(), rsp.getQemuVersion()));
recreateNonInherentTag(HostSystemTags.LIVE_SNAPSHOT);
} else {
HostSystemTags.LIVE_SNAPSHOT.deleteInherentTag(self.getUuid());
}
}
} catch (RestClientException e) {
errCode = operr("unable to connect to kvm host[uuid:%s, ip:%s, url:%s], because %s", self.getUuid(), self.getManagementIp(),
connectPath, e.getMessage());
} catch (Throwable t) {
logger.warn(t.getMessage(), t);
errCode = inerr(t.getMessage());
}
return errCode;
}
private KVMHostVO getSelf() {
return (KVMHostVO) self;
}
private void continueConnect(final ConnectHostInfo info, final Completion completion) {
ErrorCode errCode = connectToAgent();
if (errCode != null) {
throw new OperationFailureException(errCode);
}
FlowChain chain = FlowChainBuilder.newSimpleFlowChain();
chain.setName(String.format("continue-connecting-kvm-host-%s-%s", self.getManagementIp(), self.getUuid()));
chain.getData().put(KVMConstant.CONNECT_HOST_PRIMARYSTORAGE_ERROR, new ErrorCodeList());
chain.allowWatch();
for (KVMHostConnectExtensionPoint extp : factory.getConnectExtensions()) {
KVMHostConnectedContext ctx = new KVMHostConnectedContext();
ctx.setInventory((KVMHostInventory) getSelfInventory());
ctx.setNewAddedHost(info.isNewAdded());
ctx.setBaseUrl(baseUrl);
ctx.setSkipPackages(info.getSkipPackages());
chain.then(extp.createKvmHostConnectingFlow(ctx));
}
chain.done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
if (noStorageAccessible()) {
ErrorCodeList errorCodeList = (ErrorCodeList) data.get(KVMConstant.CONNECT_HOST_PRIMARYSTORAGE_ERROR);
completion.fail(operr("host can not access any primary storage, %s", errorCodeList != null && StringUtils.isNotEmpty(errorCodeList.getReadableDetails()) ? errorCodeList.getReadableDetails() : "please check network"));
} else {
if (CoreGlobalProperty.UNIT_TEST_ON) {
completion.success();
return;
}
SshShell sshShell = new SshShell();
sshShell.setHostname(getSelf().getManagementIp());
sshShell.setUsername(getSelf().getUsername());
sshShell.setPassword(getSelf().getPassword());
sshShell.setPort(getSelf().getPort());
SshResult ret = sshShell.runCommand(String.format("sudo /bin/sh -c \"echo uuid:%s > %s\"", self.getUuid(), hostTakeOverFlagPath));
if (ret.isSshFailure() || ret.getReturnCode() != 0) {
completion.fail(operr(ret.getExitErrorMessage()));
return;
}
completion.success();
}
}
}).error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(err(HostErrors.CONNECTION_ERROR, errCode, "connection error for KVM host[uuid:%s, ip:%s]", self.getUuid(),
self.getManagementIp()));
}
}).start();
}
@Transactional(readOnly = true)
private boolean noStorageAccessible(){
// detach ps will delete PrimaryStorageClusterRefVO first.
List<String> attachedPsUuids = Q.New(PrimaryStorageClusterRefVO.class)
.select(PrimaryStorageClusterRefVO_.primaryStorageUuid)
.eq(PrimaryStorageClusterRefVO_.clusterUuid, self.getClusterUuid())
.listValues();
long attachedPsCount = attachedPsUuids.size();
long inaccessiblePsCount = attachedPsCount == 0 ? 0 : Q.New(PrimaryStorageHostRefVO.class)
.eq(PrimaryStorageHostRefVO_.hostUuid, self.getUuid())
.eq(PrimaryStorageHostRefVO_.status, PrimaryStorageHostStatus.Disconnected)
.in(PrimaryStorageHostRefVO_.primaryStorageUuid, attachedPsUuids)
.count();
return inaccessiblePsCount == attachedPsCount && attachedPsCount > 0;
}
private void createHostVersionSystemTags(String distro, String release, String version) {
createTagWithoutNonValue(HostSystemTags.OS_DISTRIBUTION, HostSystemTags.OS_DISTRIBUTION_TOKEN, distro, true);
createTagWithoutNonValue(HostSystemTags.OS_RELEASE, HostSystemTags.OS_RELEASE_TOKEN, release, true);
createTagWithoutNonValue(HostSystemTags.OS_VERSION, HostSystemTags.OS_VERSION_TOKEN, version, true);
}
private void createTagWithoutNonValue(SystemTag tag, String token, String value, boolean inherent) {
if (value == null || value.isEmpty()) {
return;
}
recreateTag(tag, token, value, inherent);
}
private void recreateNonInherentTag(SystemTag tag, String token, String value) {
recreateTag(tag, token, value, false);
}
private void recreateNonInherentTag(SystemTag tag) {
recreateTag(tag, null, null, false);
}
private void recreateInherentTag(SystemTag tag, String token, String value) {
recreateTag(tag, token, value, true);
}
private void recreateTag(SystemTag tag, String token, String value, boolean inherent) {
SystemTagCreator creator = tag.newSystemTagCreator(self.getUuid());
Optional.ofNullable(token).ifPresent(it -> creator.setTagByTokens(Collections.singletonMap(token, value)));
creator.inherent = inherent;
creator.recreate = true;
creator.create();
}
@Override
public void connectHook(final ConnectHostInfo info, final Completion complete) {
if (CoreGlobalProperty.UNIT_TEST_ON) {
if (info.isNewAdded()) {
createHostVersionSystemTags("zstack", "kvmSimulator", tester.get(ZTester.KVM_HostVersion, "0.1", String.class));
if (null == KVMSystemTags.LIBVIRT_VERSION.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.LIBVIRT_VERSION_TOKEN)) {
createTagWithoutNonValue(KVMSystemTags.LIBVIRT_VERSION, KVMSystemTags.LIBVIRT_VERSION_TOKEN, tester.get(ZTester.KVM_LibvirtVersion, "1.2.9", String.class), true);
}
if (null == KVMSystemTags.QEMU_IMG_VERSION.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.QEMU_IMG_VERSION_TOKEN)) {
createTagWithoutNonValue(KVMSystemTags.QEMU_IMG_VERSION, KVMSystemTags.QEMU_IMG_VERSION_TOKEN, tester.get(ZTester.KVM_QemuImageVersion, "2.0.0", String.class), true);
}
if (null == KVMSystemTags.CPU_MODEL_NAME.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.CPU_MODEL_NAME_TOKEN)) {
createTagWithoutNonValue(KVMSystemTags.CPU_MODEL_NAME, KVMSystemTags.CPU_MODEL_NAME_TOKEN, tester.get(ZTester.KVM_CpuModelName, "Broadwell", String.class), true);
}
if (null == KVMSystemTags.EPT_CPU_FLAG.getTokenByResourceUuid(self.getUuid(), KVMSystemTags.EPT_CPU_FLAG_TOKEN)) {
createTagWithoutNonValue(KVMSystemTags.EPT_CPU_FLAG, KVMSystemTags.EPT_CPU_FLAG_TOKEN, "ept", false);
}
if (null == self.getArchitecture()) {
ClusterVO cluster = dbf.findByUuid(self.getClusterUuid(), ClusterVO.class);
HostVO host = dbf.findByUuid(self.getUuid(), HostVO.class);
if (null == cluster.getArchitecture()){
host.setArchitecture(CpuArchitecture.x86_64.toString());
} else {
host.setArchitecture(cluster.getArchitecture());
}
dbf.update(host);
}
if (!checkQemuLibvirtVersionOfHost()) {
complete.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because qemu/libvirt version does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
if (KVMSystemTags.CHECK_CLUSTER_CPU_MODEL.hasTag(self.getClusterUuid())) {
if (KVMSystemTags.CHECK_CLUSTER_CPU_MODEL
.getTokenByResourceUuid(self.getClusterUuid(), KVMSystemTags.CHECK_CLUSTER_CPU_MODEL_TOKEN)
.equals("true")
&& !checkCpuModelOfHost()) {
complete.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because cpu model name does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
complete.success();
return;
}
if (KVMGlobalConfig.CHECK_HOST_CPU_MODEL_NAME.value(Boolean.class) && !checkCpuModelOfHost()) {
complete.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because cpu model name does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
}
continueConnect(info, complete);
} else {
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("run-ansible-for-kvm-%s", self.getUuid()));
chain.allowWatch();
chain.then(new ShareFlow() {
boolean deployed = false;
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "test-if-ssh-port-open";
@Override
public void run(FlowTrigger trigger, Map data) {
long sshTimeout = TimeUnit.SECONDS.toMillis(KVMGlobalConfig.TEST_SSH_PORT_ON_OPEN_TIMEOUT.value(Long.class));
long timeout = System.currentTimeMillis() + sshTimeout;
long ctimeout = TimeUnit.SECONDS.toMillis(KVMGlobalConfig.TEST_SSH_PORT_ON_CONNECT_TIMEOUT.value(Integer.class).longValue());
thdf.submitCancelablePeriodicTask(new CancelablePeriodicTask(trigger) {
@Override
public boolean run() {
if (testPort()) {
trigger.next();
return true;
}
return ifTimeout();
}
private boolean testPort() {
if (!NetworkUtils.isRemotePortOpen(getSelf().getManagementIp(), getSelf().getPort(), (int) ctimeout)) {
logger.debug(String.format("host[uuid:%s, name:%s, ip:%s]'s ssh port[%s] is not ready yet", getSelf().getUuid(), getSelf().getName(), getSelf().getManagementIp(), getSelf().getPort()));
return false;
} else {
return true;
}
}
private boolean ifTimeout() {
if (System.currentTimeMillis() > timeout) {
trigger.fail(operr("the host[%s] ssh port[%s] not open after %s seconds, connect timeout", getSelf().getManagementIp(), getSelf().getPort(), TimeUnit.MILLISECONDS.toSeconds(sshTimeout)));
return true;
} else {
return false;
}
}
@Override
public TimeUnit getTimeUnit() {
return TimeUnit.SECONDS;
}
@Override
public long getInterval() {
return 2;
}
@Override
public String getName() {
return "test-ssh-port-open-for-kvm-host";
}
});
}
});
if (info.isNewAdded()) {
if ((!AnsibleGlobalProperty.ZSTACK_REPO.contains("zstack-mn")) && (!AnsibleGlobalProperty.ZSTACK_REPO.equals("false"))) {
flow(new NoRollbackFlow() {
String __name__ = "ping-DNS-check-list";
@Override
public void run(FlowTrigger trigger, Map data) {
String checkList;
if (AnsibleGlobalProperty.ZSTACK_REPO.contains(KVMConstant.ALI_REPO)) {
checkList = KVMGlobalConfig.HOST_DNS_CHECK_ALIYUN.value();
} else if (AnsibleGlobalProperty.ZSTACK_REPO.contains(KVMConstant.NETEASE_REPO)) {
checkList = KVMGlobalConfig.HOST_DNS_CHECK_163.value();
} else {
checkList = KVMGlobalConfig.HOST_DNS_CHECK_LIST.value();
}
checkList = checkList.replaceAll(",", " ");
SshShell sshShell = new SshShell();
sshShell.setHostname(getSelf().getManagementIp());
sshShell.setUsername(getSelf().getUsername());
sshShell.setPassword(getSelf().getPassword());
sshShell.setPort(getSelf().getPort());
SshResult ret = sshShell.runScriptWithToken("scripts/check-public-dns-name.sh",
map(e("dnsCheckList", checkList)));
if (ret.isSshFailure()) {
trigger.fail(operr("unable to connect to KVM[ip:%s, username:%s, sshPort: %d, ] to do DNS check, please check if username/password is wrong; %s", self.getManagementIp(), getSelf().getUsername(), getSelf().getPort(), ret.getExitErrorMessage()));
} else if (ret.getReturnCode() != 0) {
trigger.fail(operr("failed to ping all DNS/IP in %s; please check /etc/resolv.conf to make sure your host is able to reach public internet", checkList));
} else {
trigger.next();
}
}
});
}
}
flow(new NoRollbackFlow() {
String __name__ = "check-if-host-can-reach-management-node";
@Override
public void run(FlowTrigger trigger, Map data) {
ShellUtils.run(String.format("arp -d %s || true", getSelf().getManagementIp()));
SshShell sshShell = new SshShell();
sshShell.setHostname(getSelf().getManagementIp());
sshShell.setUsername(getSelf().getUsername());
sshShell.setPassword(getSelf().getPassword());
sshShell.setPort(getSelf().getPort());
sshShell.setWithSudo(false);
final String cmd = String.format("curl --connect-timeout 10 %s|| wget --spider -q --connect-timeout=10 %s|| test $? -eq 8", restf.getCallbackUrl(), restf.getCallbackUrl());
SshResult ret = sshShell.runCommand(cmd);
if (ret.getStderr() != null && ret.getStderr().contains("No route to host")) {
ret = sshShell.runCommand(cmd);
}
if (ret.isSshFailure()) {
throw new OperationFailureException(operr("unable to connect to KVM[ip:%s, username:%s, sshPort:%d] to check the management node connectivity," +
"please check if username/password is wrong; %s", self.getManagementIp(), getSelf().getUsername(), getSelf().getPort(), ret.getExitErrorMessage()));
} else if (ret.getReturnCode() != 0) {
throw new OperationFailureException(operr("the KVM host[ip:%s] cannot access the management node's callback url. It seems" +
" that the KVM host cannot reach the management IP[%s]. %s %s", self.getManagementIp(), restf.getHostName(),
ret.getStderr(), ret.getExitErrorMessage()));
}
trigger.next();
}
});
flow(new NoRollbackFlow() {
String __name__ = "check-Host-is-taken-over";
@Override
public void run(FlowTrigger trigger, Map data) {
if (!info.isNewAdded() || CoreGlobalProperty.UNIT_TEST_ON) {
trigger.next();
return;
}
try {
Ssh ssh = new Ssh().setUsername(getSelf().getUsername())
.setPassword(getSelf().getPassword()).setPort(getSelf().getPort())
.setHostname(getSelf().getManagementIp());
ssh.command(String.format("grep -i ^uuid %s | sed 's/uuid://g'", hostTakeOverFlagPath));
SshResult hostRet = ssh.run();
if (hostRet.isSshFailure() || hostRet.getReturnCode() != 0) {
trigger.fail(operr("unable to Check whether the host is taken over, because %s", hostRet.getExitErrorMessage()));
return;
}
String hostOutput = hostRet.getStdout().replaceAll("\r|\n","");
if (hostOutput.contains("No such file or directory")) {
trigger.next();
return;
}
ssh.command(String.format("date +%%s -r %s", hostTakeOverFlagPath));
SshResult timeRet = ssh.run();
if (timeRet.isSshFailure() || timeRet.getReturnCode() != 0) {
trigger.fail(operr("Unable to get the timestamp of the flag, because %s", timeRet.getExitErrorMessage()));
return;
}
String timestampOutput = timeRet.getStdout().replaceAll("\r|\n","");
long diff = (new Date().getTime() / 1000) - Long.parseLong(timestampOutput);
logger.debug(String.format("hostOutput is %s ,The time difference is %d(s) ", hostOutput, diff));
if (diff < HostGlobalConfig.PING_HOST_INTERVAL.value(int.class)) {
trigger.fail(operr("the host[ip:%s] has been taken over, because the takeover flag[HostUuid:%s] already exists and utime[%d] has not exceeded host ping interval[%d]",
self.getManagementIp(), hostOutput, diff, HostGlobalConfig.PING_HOST_INTERVAL.value(int.class)));
return;
}
HostVO lastHostInv = Q.New(HostVO.class).eq(HostVO_.uuid, hostOutput).find();
if (lastHostInv == null) {
trigger.next();
} else {
trigger.fail(operr("the host[ip:%s] has been taken over, because flag[HostUuid:%s] exists in the database",
self.getManagementIp(), lastHostInv.getUuid()));
}
} catch (Exception e) {
logger.warn(e.getMessage(), e);
trigger.next();
return;
}
}
});
flow(new NoRollbackFlow() {
String __name__ = "check-host-cpu-arch";
@Override
public void run(FlowTrigger trigger, Map data) {
SshShell sshShell = new SshShell();
sshShell.setHostname(getSelf().getManagementIp());
sshShell.setUsername(getSelf().getUsername());
sshShell.setPassword(getSelf().getPassword());
sshShell.setPort(getSelf().getPort());
SshResult ret = sshShell.runCommand("uname -m");
if (ret.isSshFailure() || ret.getReturnCode() != 0) {
trigger.fail(operr("unable to get host cpu architecture, please check if username/password is wrong; %s", ret.getExitErrorMessage()));
return;
}
String hostArchitecture = ret.getStdout().trim();
HostVO host = dbf.findByUuid(getSelf().getUuid(), HostVO.class);
host.setArchitecture(hostArchitecture);
dbf.update(host);
self.setArchitecture(hostArchitecture);
ClusterVO cluster = dbf.findByUuid(self.getClusterUuid(), ClusterVO.class);
if (cluster.getArchitecture() != null && !hostArchitecture.equals(cluster.getArchitecture()) && !cluster.getHypervisorType().equals("baremetal2")) {
trigger.fail(operr("host cpu architecture[%s] is not matched the cluster[%s]", hostArchitecture, cluster.getArchitecture()));
return;
}
// for upgrade case, prevent from add host failure.
if (cluster.getArchitecture() == null && !info.isNewAdded()) {
cluster.setArchitecture(hostArchitecture);
dbf.update(cluster);
}
trigger.next();
}
});
flow(new NoRollbackFlow() {
String __name__ = "apply-ansible-playbook";
@Override
public void run(final FlowTrigger trigger, Map data) {
String srcPath = PathUtil.findFileOnClassPath(String.format("ansible/kvm/%s", agentPackageName), true).getAbsolutePath();
String destPath = String.format("/var/lib/zstack/kvm/package/%s", agentPackageName);
SshFileMd5Checker checker = new SshFileMd5Checker();
checker.setUsername(getSelf().getUsername());
checker.setPassword(getSelf().getPassword());
checker.setSshPort(getSelf().getPort());
checker.setTargetIp(getSelf().getManagementIp());
checker.addSrcDestPair(SshFileMd5Checker.ZSTACKLIB_SRC_PATH, String.format("/var/lib/zstack/kvm/package/%s", AnsibleGlobalProperty.ZSTACKLIB_PACKAGE_NAME));
checker.addSrcDestPair(srcPath, destPath);
SshChronyConfigChecker chronyChecker = new SshChronyConfigChecker();
chronyChecker.setTargetIp(getSelf().getManagementIp());
chronyChecker.setUsername(getSelf().getUsername());
chronyChecker.setPassword(getSelf().getPassword());
chronyChecker.setSshPort(getSelf().getPort());
SshYumRepoChecker repoChecker = new SshYumRepoChecker();
repoChecker.setTargetIp(getSelf().getManagementIp());
repoChecker.setUsername(getSelf().getUsername());
repoChecker.setPassword(getSelf().getPassword());
repoChecker.setSshPort(getSelf().getPort());
CallBackNetworkChecker callbackChecker = new CallBackNetworkChecker();
callbackChecker.setTargetIp(getSelf().getManagementIp());
callbackChecker.setUsername(getSelf().getUsername());
callbackChecker.setPassword(getSelf().getPassword());
callbackChecker.setPort(getSelf().getPort());
callbackChecker.setCallbackIp(Platform.getManagementServerIp());
callbackChecker.setCallBackPort(CloudBusGlobalProperty.HTTP_PORT);
AnsibleRunner runner = new AnsibleRunner();
runner.installChecker(checker);
runner.installChecker(chronyChecker);
runner.installChecker(repoChecker);
runner.installChecker(callbackChecker);
if (KVMGlobalConfig.ENABLE_HOST_TCP_CONNECTION_CHECK.value(Boolean.class)) {
CallBackNetworkChecker hostTcpConnectionCallbackChecker = new CallBackNetworkChecker();
hostTcpConnectionCallbackChecker.setTargetIp(getSelf().getManagementIp());
hostTcpConnectionCallbackChecker.setUsername(getSelf().getUsername());
hostTcpConnectionCallbackChecker.setPassword(getSelf().getPassword());
hostTcpConnectionCallbackChecker.setPort(getSelf().getPort());
hostTcpConnectionCallbackChecker.setCallbackIp(Platform.getManagementServerIp());
hostTcpConnectionCallbackChecker.setCallBackPort(KVMGlobalProperty.TCP_SERVER_PORT);
runner.installChecker(hostTcpConnectionCallbackChecker);
}
for (KVMHostAddSshFileMd5CheckerExtensionPoint exp : pluginRgty.getExtensionList(KVMHostAddSshFileMd5CheckerExtensionPoint.class)) {
SshFileMd5Checker sshFileMd5Checker = exp.getSshFileMd5Checker(getSelf());
if (sshFileMd5Checker != null) {
runner.installChecker(sshFileMd5Checker);
}
}
runner.setAgentPort(KVMGlobalProperty.AGENT_PORT);
runner.setTargetIp(getSelf().getManagementIp());
runner.setTargetUuid(getSelf().getUuid());
runner.setPlayBookName(KVMConstant.ANSIBLE_PLAYBOOK_NAME);
runner.setUsername(getSelf().getUsername());
runner.setPassword(getSelf().getPassword());
runner.setSshPort(getSelf().getPort());
if (info.isNewAdded()) {
runner.putArgument("init", "true");
runner.setFullDeploy(true);
}
if (NetworkGlobalProperty.SKIP_IPV6) {
runner.putArgument("skipIpv6", "true");
}
for (CheckMiniExtensionPoint ext : pluginRegistry.getExtensionList(CheckMiniExtensionPoint.class)) {
if (ext.isMini()) {
runner.putArgument("isMini", "true");
}
}
if ("baremetal2".equals(self.getHypervisorType())) {
runner.putArgument("isBareMetal2Gateway", "true");
}
if (NetworkGlobalProperty.BRIDGE_DISABLE_IPTABLES) {
runner.putArgument("bridgeDisableIptables", "true");
}
runner.putArgument("pkg_kvmagent", agentPackageName);
runner.putArgument("hostname", String.format("%s.zstack.org", self.getManagementIp().replaceAll("\\.", "-")));
if (CoreGlobalProperty.SYNC_NODE_TIME) {
if (CoreGlobalProperty.CHRONY_SERVERS == null || CoreGlobalProperty.CHRONY_SERVERS.isEmpty()) {
trigger.fail(operr("chrony server not configured!"));
return;
}
runner.putArgument("chrony_servers", String.join(",", CoreGlobalProperty.CHRONY_SERVERS));
}
runner.putArgument("skip_packages", info.getSkipPackages());
runner.putArgument("update_packages", String.valueOf(CoreGlobalProperty.UPDATE_PKG_WHEN_CONNECT));
UriComponentsBuilder ub = UriComponentsBuilder.fromHttpUrl(restf.getBaseUrl());
ub.path(new StringBind(KVMConstant.KVM_ANSIBLE_LOG_PATH_FROMAT).bind("uuid", self.getUuid()).toString());
String postUrl = ub.build().toString();
runner.putArgument("post_url", postUrl);
runner.run(new ReturnValueCompletion<Boolean>(trigger) {
@Override
public void success(Boolean run) {
if (run != null) {
deployed = run;
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "configure-iptables";
@Override
public void run(FlowTrigger trigger, Map data) {
StringBuilder builder = new StringBuilder();
if (!KVMGlobalProperty.MN_NETWORKS.isEmpty()) {
builder.append(String.format("sudo bash %s -m %s -p %s -c %s",
"/var/lib/zstack/kvm/kvmagent-iptables",
KVMConstant.IPTABLES_COMMENTS,
KVMGlobalConfig.KVMAGENT_ALLOW_PORTS_LIST.value(String.class),
String.join(",", KVMGlobalProperty.MN_NETWORKS)));
} else {
builder.append(String.format("sudo bash %s -m %s -p %s",
"/var/lib/zstack/kvm/kvmagent-iptables",
KVMConstant.IPTABLES_COMMENTS,
KVMGlobalConfig.KVMAGENT_ALLOW_PORTS_LIST.value(String.class)));
}
try {
new Ssh().shell(builder.toString())
.setUsername(getSelf().getUsername())
.setPassword(getSelf().getPassword())
.setHostname(getSelf().getManagementIp())
.setPort(getSelf().getPort()).runErrorByExceptionAndClose();
} catch (SshException ex) {
throw new OperationFailureException(operr(ex.toString()));
}
trigger.next();
}
});
flow(new NoRollbackFlow() {
String __name__ = "echo-host";
@Override
public void run(final FlowTrigger trigger, Map data) {
restf.echo(echoPath, new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
boolean needRestart = KVMGlobalConfig.RESTART_AGENT_IF_FAKE_DEAD.value(Boolean.class);
if (!deployed && needRestart) {
// if not deployed and echo failed, we thought it is fake dead, see: ZSTACK-18628
AnsibleRunner runner = new AnsibleRunner();
runner.setAgentPort(KVMGlobalProperty.AGENT_PORT);
runner.setTargetIp(getSelf().getManagementIp());
runner.setTargetUuid(getSelf().getUuid());
runner.setUsername(getSelf().getUsername());
runner.setPassword(getSelf().getPassword());
runner.setSshPort(getSelf().getPort());
runner.restartAgent(AnsibleConstant.KVM_AGENT_NAME, new Completion(trigger) {
@Override
public void success() {
restf.echo(echoPath, new Completion(trigger) {
@Override
public void success() {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
} else {
trigger.fail(errorCode);
}
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "update-kvmagent-dependencies";
@Override
public void run(FlowTrigger trigger, Map data) {
if (!CoreGlobalProperty.UPDATE_PKG_WHEN_CONNECT) {
trigger.next();
return;
}
// new added need to update dependency if experimental repo enabled
if (info.isNewAdded() && !rcf.getResourceConfigValue(
ClusterGlobalConfig.ZSTACK_EXPERIMENTAL_REPO, self.getClusterUuid(), Boolean.class)) {
trigger.next();
return;
}
UpdateDependencyCmd cmd = new UpdateDependencyCmd();
cmd.hostUuid = self.getUuid();
if (info.isNewAdded()) {
cmd.enableExpRepo = true;
cmd.updatePackages = rcf.getResourceConfigValue(
ClusterGlobalConfig.ZSTACK_EXPERIMENTAL_UPDATE_DEPENDENCY, self.getClusterUuid(), String.class);
cmd.excludePackages = rcf.getResourceConfigValue(
ClusterGlobalConfig.ZSTACK_EXPERIMENTAL_EXCLUDE_DEPENDENCY, self.getClusterUuid(), String.class);
}
new Http<>(updateDependencyPath, cmd, UpdateDependencyRsp.class)
.call(new ReturnValueCompletion<UpdateDependencyRsp>(trigger) {
@Override
public void success(UpdateDependencyRsp ret) {
if (ret.isSuccess()) {
trigger.next();
} else {
trigger.fail(Platform.operr("%s", ret.getError()));
}
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "collect-kvm-host-facts";
@Override
public void run(final FlowTrigger trigger, Map data) {
HostFactCmd cmd = new HostFactCmd();
new Http<>(hostFactPath, cmd, HostFactResponse.class)
.call(new ReturnValueCompletion<HostFactResponse>(trigger) {
@Override
public void success(HostFactResponse ret) {
if (!ret.isSuccess()) {
trigger.fail(operr("operation error, because:%s", ret.getError()));
return;
}
if (ret.getHvmCpuFlag() == null) {
trigger.fail(operr("cannot find either 'vmx' or 'svm' in /proc/cpuinfo, please make sure you have enabled virtualization in your BIOS setting"));
return;
}
// create system tags of os::version etc
createHostVersionSystemTags(ret.getOsDistribution(), ret.getOsRelease(), ret.getOsVersion());
createTagWithoutNonValue(KVMSystemTags.QEMU_IMG_VERSION, KVMSystemTags.QEMU_IMG_VERSION_TOKEN, ret.getQemuImgVersion(), false);
createTagWithoutNonValue(KVMSystemTags.LIBVIRT_VERSION, KVMSystemTags.LIBVIRT_VERSION_TOKEN, ret.getLibvirtVersion(), false);
createTagWithoutNonValue(KVMSystemTags.HVM_CPU_FLAG, KVMSystemTags.HVM_CPU_FLAG_TOKEN, ret.getHvmCpuFlag(), false);
createTagWithoutNonValue(KVMSystemTags.EPT_CPU_FLAG, KVMSystemTags.EPT_CPU_FLAG_TOKEN, ret.getEptFlag(), false);
createTagWithoutNonValue(KVMSystemTags.CPU_MODEL_NAME, KVMSystemTags.CPU_MODEL_NAME_TOKEN, ret.getCpuModelName(), false);
createTagWithoutNonValue(HostSystemTags.HOST_CPU_MODEL_NAME, HostSystemTags.HOST_CPU_MODEL_NAME_TOKEN, ret.getHostCpuModelName(), true);
createTagWithoutNonValue(HostSystemTags.CPU_GHZ, HostSystemTags.CPU_GHZ_TOKEN, ret.getCpuGHz(), true);
createTagWithoutNonValue(HostSystemTags.SYSTEM_PRODUCT_NAME, HostSystemTags.SYSTEM_PRODUCT_NAME_TOKEN, ret.getSystemProductName(), true);
createTagWithoutNonValue(HostSystemTags.SYSTEM_SERIAL_NUMBER, HostSystemTags.SYSTEM_SERIAL_NUMBER_TOKEN, ret.getSystemSerialNumber(), true);
if (ret.getLibvirtVersion().compareTo(KVMConstant.MIN_LIBVIRT_VIRTIO_SCSI_VERSION) >= 0) {
recreateNonInherentTag(KVMSystemTags.VIRTIO_SCSI);
}
List<String> ips = ret.getIpAddresses();
if (ips != null) {
ips.remove(self.getManagementIp());
if (CoreGlobalProperty.MN_VIP != null) {
ips.remove(CoreGlobalProperty.MN_VIP);
}
if (!ips.isEmpty()) {
recreateNonInherentTag(HostSystemTags.EXTRA_IPS, HostSystemTags.EXTRA_IPS_TOKEN, StringUtils.join(ips, ","));
} else {
HostSystemTags.EXTRA_IPS.delete(self.getUuid());
}
}
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
if (info.isNewAdded()) {
flow(new NoRollbackFlow() {
String __name__ = "check-qemu-libvirt-version";
@Override
public void run(FlowTrigger trigger, Map data) {
if (!checkQemuLibvirtVersionOfHost()) {
trigger.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because qemu/libvirt version does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
if (KVMSystemTags.CHECK_CLUSTER_CPU_MODEL.hasTag(self.getClusterUuid())) {
if (KVMSystemTags.CHECK_CLUSTER_CPU_MODEL
.getTokenByResourceUuid(self.getClusterUuid(), KVMSystemTags.CHECK_CLUSTER_CPU_MODEL_TOKEN)
.equals("true")
&& !checkCpuModelOfHost()) {
trigger.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because cpu model name does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
trigger.next();
return;
}
if (KVMGlobalConfig.CHECK_HOST_CPU_MODEL_NAME.value(Boolean.class) && !checkCpuModelOfHost()) {
trigger.fail(operr("host [uuid:%s] cannot be added to cluster [uuid:%s] because cpu model name does not match",
self.getUuid(), self.getClusterUuid()));
return;
}
trigger.next();
}
});
}
flow(new NoRollbackFlow() {
String __name__ = "prepare-host-env";
@Override
public void run(FlowTrigger trigger, Map data) {
String script = "which iptables > /dev/null && iptables -C FORWARD -j REJECT --reject-with icmp-host-prohibited > /dev/null 2>&1 && iptables -D FORWARD -j REJECT --reject-with icmp-host-prohibited > /dev/null 2>&1 || true";
runShell(script);
trigger.next();
}
});
error(new FlowErrorHandler(complete) {
@Override
public void handle(ErrorCode errCode, Map data) {
complete.fail(errCode);
}
});
done(new FlowDoneHandler(complete) {
@Override
public void handle(Map data) {
continueConnect(info, complete);
}
});
}
}).start();
}
}
private void handle(final ShutdownHostMsg msg) {
inQueue().name(String.format("shut-down-kvm-host-%s", self.getUuid()))
.asyncBackup(msg)
.run(chain -> handleShutdownHost(msg, new NoErrorCompletion(chain) {
@Override
public void done() {
chain.next();
}
}));
}
private void handleShutdownHost(final ShutdownHostMsg msg, final NoErrorCompletion completion) {
ShutdownHostReply reply = new ShutdownHostReply();
KVMAgentCommands.ShutdownHostCmd cmd = new KVMAgentCommands.ShutdownHostCmd();
new Http<>(shutdownHost, cmd, ShutdownHostResponse.class).call(new ReturnValueCompletion<ShutdownHostResponse>(msg, completion) {
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
completion.done();
}
@Override
public void success(KVMAgentCommands.ShutdownHostResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
bus.reply(msg, reply);
completion.done();
return;
}
changeConnectionState(HostStatusEvent.disconnected);
if (msg.isReturnEarly()) {
bus.reply(msg, reply);
completion.done();
} else {
waitForHostShutdown(reply, completion);
}
}
private boolean testPort() {
if (CoreGlobalProperty.UNIT_TEST_ON) {
return false;
}
long ctimeout = TimeUnit.SECONDS.toMillis(KVMGlobalConfig.TEST_SSH_PORT_ON_CONNECT_TIMEOUT.value(Integer.class).longValue());
if (!NetworkUtils.isRemotePortOpen(getSelf().getManagementIp(), getSelf().getPort(), (int) ctimeout)) {
logger.debug(String.format("host[uuid:%s, name:%s, ip:%s]'s ssh port[%s] is no longer open, " +
"seem to be shutdowned", getSelf().getUuid(), getSelf().getName(), getSelf().getManagementIp(), getSelf().getPort()));
return false;
} else {
return true;
}
}
private void waitForHostShutdown(ShutdownHostReply reply, NoErrorCompletion noErrorCompletion) {
thdf.submitCancelablePeriodicTask(new CancelablePeriodicTask(msg, noErrorCompletion) {
@Override
public boolean run() {
if (testPort()) {
return false;
}
bus.reply(msg, reply);
noErrorCompletion.done();
return true;
}
@Override
public TimeUnit getTimeUnit() {
return TimeUnit.SECONDS;
}
@Override
public long getInterval() {
return 2;
}
@Override
public String getName() {
return "test-ssh-port-open-for-kvm-host";
}
});
}
});
}
private void handle(final CancelHostTaskMsg msg) {
CancelHostTaskReply reply = new CancelHostTaskReply();
cancelJob(msg.getCancellationApiId(), new Completion(msg) {
@Override
public void success() {
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void cancelJob(String apiId, Completion completion) {
CancelCmd cmd = new CancelCmd();
cmd.setCancellationApiId(apiId);
new Http<>(cancelJob, cmd, CancelRsp.class).call(new ReturnValueCompletion<CancelRsp>(completion) {
@Override
public void success(CancelRsp ret) {
if (ret.isSuccess()) {
completion.success();
} else {
completion.fail(Platform.operr("%s", ret.getError()));
}
}
@Override
public void fail(ErrorCode errorCode) {
completion.fail(errorCode);
}
});
}
private boolean checkCpuModelOfHost() {
List<String> hostUuidsInCluster = Q.New(HostVO.class)
.select(HostVO_.uuid)
.eq(HostVO_.clusterUuid, self.getClusterUuid())
.notEq(HostVO_.uuid, self.getUuid())
.listValues();
if (hostUuidsInCluster.isEmpty()) {
return true;
}
Map<String, List<String>> cpuModelNames = KVMSystemTags.CPU_MODEL_NAME.getTags(hostUuidsInCluster);
if (cpuModelNames != null && cpuModelNames.size() != 0) {
String clusterCpuModelName = KVMSystemTags.CPU_MODEL_NAME.getTokenByTag(
cpuModelNames.values().iterator().next().get(0),
KVMSystemTags.CPU_MODEL_NAME_TOKEN
);
String hostCpuModelName = KVMSystemTags.CPU_MODEL_NAME.getTokenByResourceUuid(
self.getUuid(), KVMSystemTags.CPU_MODEL_NAME_TOKEN
);
if (clusterCpuModelName != null && !clusterCpuModelName.equals(hostCpuModelName)) {
return false;
}
}
return true;
}
@Override
protected void updateOsHook(UpdateHostOSMsg msg, Completion completion) {
FlowChain chain = FlowChainBuilder.newShareFlowChain();
self = dbf.reload(self);
chain.setName(String.format("update-operating-system-for-host-%s", self.getUuid()));
chain.then(new ShareFlow() {
// is the host in maintenance already?
final HostState oldState = self.getState();
final boolean maintenance = oldState == HostState.Maintenance;
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "double-check-host-state-status";
@Override
public void run(FlowTrigger trigger, Map data) {
if (self.getState() == HostState.PreMaintenance) {
trigger.fail(Platform.operr("host is in the premaintenance state, cannot update os"));
} else if (self.getStatus() != HostStatus.Connected) {
trigger.fail(Platform.operr("host is not in the connected status, cannot update os"));
} else {
trigger.next();
}
}
});
flow(new Flow() {
String __name__ = "make-host-in-maintenance";
@Override
public void run(FlowTrigger trigger, Map data) {
if (maintenance) {
trigger.next();
return;
}
// enter maintenance, but donot stop/migrate vm on the host
ChangeHostStateMsg cmsg = new ChangeHostStateMsg();
cmsg.setUuid(self.getUuid());
cmsg.setStateEvent(HostStateEvent.preMaintain.toString());
bus.makeTargetServiceIdByResourceUuid(cmsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(cmsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
trigger.next();
} else {
trigger.fail(reply.getError());
}
}
});
}
@Override
public void rollback(FlowRollback trigger, Map data) {
if (maintenance) {
trigger.rollback();
return;
}
// back to old host state
if (oldState == HostState.Disabled) {
changeState(HostStateEvent.disable);
} else {
changeState(HostStateEvent.enable);
}
trigger.rollback();
}
});
flow(new NoRollbackFlow() {
String __name__ = "update-host-os";
@Override
public void run(FlowTrigger trigger, Map data) {
UpdateHostOSCmd cmd = new UpdateHostOSCmd();
cmd.hostUuid = self.getUuid();
cmd.excludePackages = msg.getExcludePackages();
cmd.updatePackages = msg.getUpdatePackages();
cmd.releaseVersion = msg.getReleaseVersion();
cmd.enableExpRepo = msg.isEnableExperimentalRepo();
new Http<>(updateHostOSPath, cmd, UpdateHostOSRsp.class)
.call(new ReturnValueCompletion<UpdateHostOSRsp>(trigger) {
@Override
public void success(UpdateHostOSRsp ret) {
if (ret.isSuccess()) {
trigger.next();
} else {
trigger.fail(Platform.operr("%s", ret.getError()));
}
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "recover-host-state";
@Override
public void run(FlowTrigger trigger, Map data) {
if (maintenance) {
trigger.next();
return;
}
// back to old host state
if (oldState == HostState.Disabled) {
changeState(HostStateEvent.disable);
} else {
changeState(HostStateEvent.enable);
}
trigger.next();
}
});
flow(new NoRollbackFlow() {
String __name__ = "auto-reconnect-host";
@Override
public void run(FlowTrigger trigger, Map data) {
ReconnectHostMsg rmsg = new ReconnectHostMsg();
rmsg.setHostUuid(self.getUuid());
bus.makeTargetServiceIdByResourceUuid(rmsg, HostConstant.SERVICE_ID, self.getUuid());
bus.send(rmsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
logger.info("successfully reconnected host " + self.getUuid());
} else {
logger.error("failed to reconnect host " + self.getUuid());
}
trigger.next();
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
logger.debug(String.format("successfully updated operating system for host[uuid:%s]", self.getUuid()));
completion.success();
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
logger.warn(String.format("failed to updated operating system for host[uuid:%s] because %s",
self.getUuid(), errCode.getDetails()));
completion.fail(errCode);
}
});
}
}).start();
}
private boolean checkMigrateNetworkCidrOfHost(String cidr) {
if (NetworkUtils.isIpv4InCidr(self.getManagementIp(), cidr)) {
return true;
}
final String extraIps = HostSystemTags.EXTRA_IPS.getTokenByResourceUuid(
self.getUuid(), HostSystemTags.EXTRA_IPS_TOKEN);
if (extraIps == null) {
logger.error(String.format("Host[uuid:%s] has no IPs in migrate network", self.getUuid()));
return false;
}
final String[] ips = extraIps.split(",");
for (String ip: ips) {
if (NetworkUtils.isIpv4InCidr(ip, cidr)) {
return true;
}
}
return false;
}
private boolean checkQemuLibvirtVersionOfHost() {
List<String> hostUuidsInCluster = Q.New(HostVO.class)
.select(HostVO_.uuid)
.eq(HostVO_.clusterUuid, self.getClusterUuid())
.notEq(HostVO_.uuid, self.getUuid())
.listValues();
if (hostUuidsInCluster.isEmpty()) {
return true;
}
Map<String, List<String>> qemuVersions = KVMSystemTags.QEMU_IMG_VERSION.getTags(hostUuidsInCluster);
if (qemuVersions != null && qemuVersions.size() != 0) {
String clusterQemuVer = KVMSystemTags.QEMU_IMG_VERSION.getTokenByTag(
qemuVersions.values().iterator().next().get(0),
KVMSystemTags.QEMU_IMG_VERSION_TOKEN
);
String hostQemuVer = KVMSystemTags.QEMU_IMG_VERSION.getTokenByResourceUuid(
self.getUuid(), KVMSystemTags.QEMU_IMG_VERSION_TOKEN
);
if (clusterQemuVer != null && !clusterQemuVer.equals(hostQemuVer)) {
return false;
}
}
Map<String, List<String>> libvirtVersions = KVMSystemTags.LIBVIRT_VERSION.getTags(hostUuidsInCluster);
if (libvirtVersions != null && libvirtVersions.size() != 0) {
String clusterLibvirtVer = KVMSystemTags.LIBVIRT_VERSION.getTokenByTag(
libvirtVersions.values().iterator().next().get(0),
KVMSystemTags.LIBVIRT_VERSION_TOKEN
);
String hostLibvirtVer = KVMSystemTags.LIBVIRT_VERSION.getTokenByResourceUuid(
self.getUuid(), KVMSystemTags.LIBVIRT_VERSION_TOKEN
);
if (clusterLibvirtVer != null && !clusterLibvirtVer.equals(hostLibvirtVer)) {
return false;
}
}
return true;
}
@Override
protected int getHostSyncLevel() {
return KVMGlobalConfig.HOST_SYNC_LEVEL.value(Integer.class);
}
@Override
protected HostVO updateHost(APIUpdateHostMsg msg) {
if (!(msg instanceof APIUpdateKVMHostMsg)) {
return super.updateHost(msg);
}
KVMHostVO vo = (KVMHostVO) super.updateHost(msg);
vo = vo == null ? getSelf() : vo;
APIUpdateKVMHostMsg umsg = (APIUpdateKVMHostMsg) msg;
if (umsg.getUsername() != null) {
vo.setUsername(umsg.getUsername());
}
if (umsg.getPassword() != null) {
vo.setPassword(umsg.getPassword());
}
if (umsg.getSshPort() != null && umsg.getSshPort() > 0 && umsg.getSshPort() <= 65535) {
vo.setPort(umsg.getSshPort());
}
return vo;
}
@Override
protected void scanVmPorts(ScanVmPortMsg msg) {
ScanVmPortReply reply = new ScanVmPortReply();
reply.setSupportScan(true);
checkStatus();
ScanVmPortCmd cmd = new ScanVmPortCmd();
cmd.setIp(msg.getIp());
cmd.setBrname(msg.getBrName());
cmd.setPort(msg.getPort());
new Http<>(scanVmPortPath, cmd, ScanVmPortResponse.class).call(new ReturnValueCompletion<ScanVmPortResponse>(msg) {
@Override
public void success(ScanVmPortResponse ret) {
if (!ret.isSuccess()) {
reply.setError(operr("operation error, because:%s", ret.getError()));
} else {
reply.setStatus(ret.getPortStatus());
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
} |
package org.estatio.capex.dom.task.policy;
import java.util.Optional;
import javax.inject.Inject;
import com.google.common.eventbus.Subscribe;
import org.axonframework.eventhandling.annotation.EventHandler;
import org.apache.isis.applib.annotation.DomainService;
import org.apache.isis.applib.annotation.DomainServiceLayout;
import org.apache.isis.applib.annotation.NatureOfService;
import org.apache.isis.applib.services.metamodel.MetaModelService3;
import org.estatio.capex.dom.EstatioCapexDomModule;
import org.estatio.capex.dom.state.State;
import org.estatio.capex.dom.state.StateTransition;
import org.estatio.capex.dom.state.StateTransitionService;
import org.estatio.capex.dom.state.StateTransitionType;
import org.estatio.capex.dom.task.Task;
import org.estatio.capex.dom.task.Task_mixinActAbstract;
import org.estatio.capex.dom.triggers.DomainObject_triggerAbstract;
import org.estatio.dom.party.Person;
import org.estatio.dom.party.PersonRepository;
import org.estatio.dom.togglz.EstatioTogglzFeature;
@DomainService(nature = NatureOfService.DOMAIN)
@DomainServiceLayout(menuOrder = "1")
public class EnforceTaskAssignmentPolicySubscriber extends org.apache.isis.applib.AbstractSubscriber {
public static interface WithStateTransitionClass {
Class<?> getStateTransitionClass();
}
@EventHandler
@Subscribe
public void on(Task_mixinActAbstract.ActionDomainEvent ev) {
if(ev.getSemantics().isSafeInNature()) {
return;
}
final Class stateTransitionClass = ev.getStateTransitionClass();
final Task task = (Task) ev.getMixedIn();
final StateTransition transition = stateTransitionService.findFor(task);
if(transition == null) {
// shouldn't occur
return;
}
final Class taskTransitionClass = stateTransitionService.transitionClassFor(transition.getTransitionType());
if(stateTransitionClass != taskTransitionClass) {
// just ignore; this mixin action on task doesn't apply to the domain object that the task applies to.
// or, maybe should hide (and then we can delete code in the subtypes of the mixinAbstract
return;
}
final Object domainObject = transition.getDomainObject();
applyPolicy(stateTransitionClass, domainObject, ev);
}
@EventHandler
@Subscribe
public void on(DomainObject_triggerAbstract.ActionDomainEvent ev) {
if(ev.getSemantics().isSafeInNature()) {
return;
}
final Class stateTransitionClass = ev.getStateTransitionClass();
final Object domainObject = ev.getMixedIn();
applyPolicy(stateTransitionClass, domainObject, ev);
}
private void applyPolicy(
final Class stateTransitionClass,
final Object domainObject,
final EstatioCapexDomModule.ActionDomainEvent<?> evv) {
Optional<String> reasonIfAny = applyPolicy(stateTransitionClass, domainObject);
reasonIfAny.ifPresent(evv::disable);
}
private <
DO,
ST extends StateTransition<DO, ST, STT, S>,
STT extends StateTransitionType<DO, ST, STT, S>,
S extends State<S>
> Optional<String> applyPolicy(
final Class<ST> stateTransitionClass,
final DO domainObject) {
if(EstatioTogglzFeature.ApproveByProxy.isActive()) {
return Optional.empty();
}
final ST pendingTransition = stateTransitionService.pendingTransitionOf(domainObject, stateTransitionClass);
if (pendingTransition == null){
return Optional.empty();
}
final Task task = pendingTransition.getTask();
if(task == null) {
return Optional.empty();
}
final Person meAsPerson = personRepository.me();
final Person taskAssignedTo = task.getPersonAssignedTo();
if(taskAssignedTo == null || taskAssignedTo == meAsPerson) {
return Optional.empty();
}
return Optional.of(String.format("Task assigned to %s", taskAssignedTo.getReference()));
}
@Inject
MetaModelService3 metaModelService3;
@Inject
StateTransitionService stateTransitionService;
@Inject
PersonRepository personRepository;
} |
package org.ovirt.engine.ui.uicommonweb.models.hosts;
import java.util.ArrayList;
import java.util.Arrays;
import org.ovirt.engine.core.common.VdcActionUtils;
import org.ovirt.engine.core.common.action.UpdateVdsActionParameters;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.action.VdsActionParameters;
import org.ovirt.engine.core.common.businessentities.NonOperationalReason;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VDSType;
import org.ovirt.engine.core.common.businessentities.VdsSpmStatus;
import org.ovirt.engine.core.common.businessentities.VdsVersion;
import org.ovirt.engine.core.compat.Event;
import org.ovirt.engine.core.compat.EventArgs;
import org.ovirt.engine.core.compat.EventDefinition;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.PropertyChangedEventArgs;
import org.ovirt.engine.core.compat.RpmVersion;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.DataProvider;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.UICommand;
import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
import org.ovirt.engine.ui.uicompat.FrontendActionAsyncResult;
import org.ovirt.engine.ui.uicompat.FrontendMultipleActionAsyncResult;
import org.ovirt.engine.ui.uicompat.IFrontendActionAsyncCallback;
import org.ovirt.engine.ui.uicompat.IFrontendMultipleActionAsyncCallback;
@SuppressWarnings("unused")
public class HostGeneralModel extends EntityModel
{
public static EventDefinition RequestEditEventDefinition;
private Event privateRequestEditEvent;
public Event getRequestEditEvent()
{
return privateRequestEditEvent;
}
private void setRequestEditEvent(Event value)
{
privateRequestEditEvent = value;
}
public static EventDefinition RequestGOToEventsTabEventDefinition;
private Event privateRequestGOToEventsTabEvent;
public Event getRequestGOToEventsTabEvent()
{
return privateRequestGOToEventsTabEvent;
}
private void setRequestGOToEventsTabEvent(Event value)
{
privateRequestGOToEventsTabEvent = value;
}
private UICommand privateSaveNICsConfigCommand;
public UICommand getSaveNICsConfigCommand()
{
return privateSaveNICsConfigCommand;
}
private void setSaveNICsConfigCommand(UICommand value)
{
privateSaveNICsConfigCommand = value;
}
private UICommand privateInstallCommand;
public UICommand getInstallCommand()
{
return privateInstallCommand;
}
private void setInstallCommand(UICommand value)
{
privateInstallCommand = value;
}
private UICommand privateEditHostCommand;
public UICommand getEditHostCommand()
{
return privateEditHostCommand;
}
private void setEditHostCommand(UICommand value)
{
privateEditHostCommand = value;
}
private UICommand privateGoToEventsCommand;
public UICommand getGoToEventsCommand()
{
return privateGoToEventsCommand;
}
private void setGoToEventsCommand(UICommand value)
{
privateGoToEventsCommand = value;
}
private boolean isEntityChanged;
@Override
public VDS getEntity()
{
return (VDS) super.getEntity();
}
@Override
public void setEntity(Object value)
{
VDS vds = (VDS) value;
isEntityChanged = vds == null || getEntity() == null || !vds.getId().equals(getEntity().getId());
super.setEntity(value);
}
private String os;
public String getOS()
{
return os;
}
public void setOS(String value)
{
if (!StringHelper.stringsEqual(os, value))
{
os = value;
OnPropertyChanged(new PropertyChangedEventArgs("OS")); //$NON-NLS-1$
}
}
private String kernelVersion;
public String getKernelVersion()
{
return kernelVersion;
}
public void setKernelVersion(String value)
{
if (!StringHelper.stringsEqual(kernelVersion, value))
{
kernelVersion = value;
OnPropertyChanged(new PropertyChangedEventArgs("KernelVersion")); //$NON-NLS-1$
}
}
private String kvmVersion;
public String getKvmVersion()
{
return kvmVersion;
}
public void setKvmVersion(String value)
{
if (!StringHelper.stringsEqual(kvmVersion, value))
{
kvmVersion = value;
OnPropertyChanged(new PropertyChangedEventArgs("KvmVersion")); //$NON-NLS-1$
}
}
private Version vdsmVersion;
public Version getVdsmVersion()
{
return vdsmVersion;
}
public void setVdsmVersion(Version value)
{
if (Version.OpInequality(vdsmVersion, value))
{
vdsmVersion = value;
OnPropertyChanged(new PropertyChangedEventArgs("VdsmVersion")); //$NON-NLS-1$
}
}
private String spiceVersion;
public String getSpiceVersion()
{
return spiceVersion;
}
public void setSpiceVersion(String value)
{
if (!StringHelper.stringsEqual(spiceVersion, value))
{
spiceVersion = value;
OnPropertyChanged(new PropertyChangedEventArgs("SpiceVersion")); //$NON-NLS-1$
}
}
private String iScsiInitiatorName;
public String getIScsiInitiatorName()
{
return iScsiInitiatorName;
}
public void setIScsiInitiatorName(String value)
{
if (!StringHelper.stringsEqual(iScsiInitiatorName, value))
{
iScsiInitiatorName = value;
OnPropertyChanged(new PropertyChangedEventArgs("IScsiInitiatorName")); //$NON-NLS-1$
}
}
private Integer activeVms;
public Integer getActiveVms()
{
return activeVms;
}
public void setActiveVms(Integer value)
{
if (activeVms == null && value == null)
{
return;
}
if (activeVms == null || !activeVms.equals(value))
{
activeVms = value;
OnPropertyChanged(new PropertyChangedEventArgs("ActiveVms")); //$NON-NLS-1$
}
}
private Boolean memoryPageSharing;
public Boolean getMemoryPageSharing()
{
return memoryPageSharing;
}
public void setMemoryPageSharing(Boolean value)
{
if (memoryPageSharing == null && value == null)
{
return;
}
if (memoryPageSharing == null || !memoryPageSharing.equals(value))
{
memoryPageSharing = value;
OnPropertyChanged(new PropertyChangedEventArgs("MemoryPageSharing")); //$NON-NLS-1$
}
}
private Object automaticLargePage;
public Object getAutomaticLargePage()
{
return automaticLargePage;
}
public void setAutomaticLargePage(Object value)
{
if (automaticLargePage != value)
{
automaticLargePage = value;
OnPropertyChanged(new PropertyChangedEventArgs("AutomaticLargePage")); //$NON-NLS-1$
}
}
private Integer numberOfCPUs;
public Integer getNumberOfCPUs()
{
return numberOfCPUs;
}
public void setNumberOfCPUs(Integer value)
{
if (numberOfCPUs == null && value == null)
{
return;
}
if (numberOfCPUs == null || !numberOfCPUs.equals(value))
{
numberOfCPUs = value;
OnPropertyChanged(new PropertyChangedEventArgs("NumberOfCPUs")); //$NON-NLS-1$
}
}
private String cpuName;
public String getCpuName()
{
return cpuName;
}
public void setCpuName(String value)
{
if (!StringHelper.stringsEqual(cpuName, value))
{
cpuName = value;
OnPropertyChanged(new PropertyChangedEventArgs("CpuName")); //$NON-NLS-1$
}
}
private String cpuType;
public String getCpuType()
{
return cpuType;
}
public void setCpuType(String value)
{
if (!StringHelper.stringsEqual(cpuType, value))
{
cpuType = value;
OnPropertyChanged(new PropertyChangedEventArgs("CpuType")); //$NON-NLS-1$
}
}
private Integer sharedMemory;
public Integer getSharedMemory()
{
return sharedMemory;
}
public void setSharedMemory(Integer value)
{
if (sharedMemory == null && value == null)
{
return;
}
if (sharedMemory == null || !sharedMemory.equals(value))
{
sharedMemory = value;
OnPropertyChanged(new PropertyChangedEventArgs("SharedMemory")); //$NON-NLS-1$
}
}
private Integer physicalMemory;
public Integer getPhysicalMemory()
{
return physicalMemory;
}
public void setPhysicalMemory(Integer value)
{
if (physicalMemory == null && value == null)
{
return;
}
if (physicalMemory == null || !physicalMemory.equals(value))
{
physicalMemory = value;
OnPropertyChanged(new PropertyChangedEventArgs("PhysicalMemory")); //$NON-NLS-1$
}
}
private Long swapTotal;
public Long getSwapTotal()
{
return swapTotal;
}
public void setSwapTotal(Long value)
{
if (swapTotal == null && value == null)
{
return;
}
if (swapTotal == null || !swapTotal.equals(value))
{
swapTotal = value;
OnPropertyChanged(new PropertyChangedEventArgs("SwapTotal")); //$NON-NLS-1$
}
}
private Long swapFree;
public Long getSwapFree()
{
return swapFree;
}
public void setSwapFree(Long value)
{
if (swapFree == null && value == null)
{
return;
}
if (swapFree == null || !swapFree.equals(value))
{
swapFree = value;
OnPropertyChanged(new PropertyChangedEventArgs("SwapFree")); //$NON-NLS-1$
}
}
private Integer freeMemory;
public Integer getFreeMemory()
{
return freeMemory;
}
public void setFreeMemory(Integer value)
{
if (freeMemory == null && value == null)
{
return;
}
if (freeMemory == null || !freeMemory.equals(value))
{
freeMemory = value;
OnPropertyChanged(new PropertyChangedEventArgs("FreeMemory")); //$NON-NLS-1$
}
}
private Integer usedMemory;
public Integer getUsedMemory()
{
return usedMemory;
}
public void setUsedMemory(Integer value)
{
if (usedMemory == null && value == null)
{
return;
}
if (usedMemory == null || !usedMemory.equals(value))
{
usedMemory = value;
OnPropertyChanged(new PropertyChangedEventArgs("UsedMemory")); //$NON-NLS-1$
}
}
private Long usedSwap;
public Long getUsedSwap()
{
return usedSwap;
}
public void setUsedSwap(Long value)
{
if (usedSwap == null && value == null)
{
return;
}
if (usedSwap == null || !usedSwap.equals(value))
{
usedSwap = value;
OnPropertyChanged(new PropertyChangedEventArgs("UsedSwap")); //$NON-NLS-1$
}
}
private boolean hasAnyAlert;
public boolean getHasAnyAlert()
{
return hasAnyAlert;
}
public void setHasAnyAlert(boolean value)
{
if (hasAnyAlert != value)
{
hasAnyAlert = value;
OnPropertyChanged(new PropertyChangedEventArgs("HasAnyAlert")); //$NON-NLS-1$
}
}
private boolean hasUpgradeAlert;
public boolean getHasUpgradeAlert()
{
return hasUpgradeAlert;
}
public void setHasUpgradeAlert(boolean value)
{
if (hasUpgradeAlert != value)
{
hasUpgradeAlert = value;
OnPropertyChanged(new PropertyChangedEventArgs("HasUpgradeAlert")); //$NON-NLS-1$
}
}
private boolean hasManualFenceAlert;
public boolean getHasManualFenceAlert()
{
return hasManualFenceAlert;
}
public void setHasManualFenceAlert(boolean value)
{
if (hasManualFenceAlert != value)
{
hasManualFenceAlert = value;
OnPropertyChanged(new PropertyChangedEventArgs("HasManualFenceAlert")); //$NON-NLS-1$
}
}
private boolean hasNoPowerManagementAlert;
public boolean getHasNoPowerManagementAlert()
{
return hasNoPowerManagementAlert;
}
public void setHasNoPowerManagementAlert(boolean value)
{
if (hasNoPowerManagementAlert != value)
{
hasNoPowerManagementAlert = value;
OnPropertyChanged(new PropertyChangedEventArgs("HasNoPowerManagementAlert")); //$NON-NLS-1$
}
}
private boolean hasReinstallAlertNonResponsive;
public boolean getHasReinstallAlertNonResponsive()
{
return hasReinstallAlertNonResponsive;
}
public void setHasReinstallAlertNonResponsive(boolean value)
{
if (hasReinstallAlertNonResponsive != value)
{
hasReinstallAlertNonResponsive = value;
OnPropertyChanged(new PropertyChangedEventArgs("HasReinstallAlertNonResponsive")); //$NON-NLS-1$
}
}
private boolean hasReinstallAlertInstallFailed;
public boolean getHasReinstallAlertInstallFailed()
{
return hasReinstallAlertInstallFailed;
}
public void setHasReinstallAlertInstallFailed(boolean value)
{
if (hasReinstallAlertInstallFailed != value)
{
hasReinstallAlertInstallFailed = value;
OnPropertyChanged(new PropertyChangedEventArgs("HasReinstallAlertInstallFailed")); //$NON-NLS-1$
}
}
private boolean hasReinstallAlertMaintenance;
public boolean getHasReinstallAlertMaintenance()
{
return hasReinstallAlertMaintenance;
}
public void setHasReinstallAlertMaintenance(boolean value)
{
if (hasReinstallAlertMaintenance != value)
{
hasReinstallAlertMaintenance = value;
OnPropertyChanged(new PropertyChangedEventArgs("HasReinstallAlertMaintenance")); //$NON-NLS-1$
}
}
private boolean hasNICsAlert;
public boolean getHasNICsAlert()
{
return hasNICsAlert;
}
public void setHasNICsAlert(boolean value)
{
if (hasNICsAlert != value)
{
hasNICsAlert = value;
OnPropertyChanged(new PropertyChangedEventArgs("HasNICsAlert")); //$NON-NLS-1$
}
}
private NonOperationalReason nonOperationalReasonEntity;
public NonOperationalReason getNonOperationalReasonEntity()
{
return nonOperationalReasonEntity;
}
public void setNonOperationalReasonEntity(NonOperationalReason value)
{
if (nonOperationalReasonEntity != value)
{
nonOperationalReasonEntity = value;
OnPropertyChanged(new PropertyChangedEventArgs("NonOperationalReasonEntity")); //$NON-NLS-1$
}
}
static
{
RequestEditEventDefinition = new EventDefinition("RequestEditEvent", HostGeneralModel.class); //$NON-NLS-1$
RequestGOToEventsTabEventDefinition = new EventDefinition("RequestGOToEventsTabEvent", HostGeneralModel.class); //$NON-NLS-1$
}
public HostGeneralModel()
{
setRequestEditEvent(new Event(RequestEditEventDefinition));
setRequestGOToEventsTabEvent(new Event(RequestGOToEventsTabEventDefinition));
setTitle(ConstantsManager.getInstance().getConstants().generalTitle());
setHashName("general"); //$NON-NLS-1$
setSaveNICsConfigCommand(new UICommand("SaveNICsConfig", this)); //$NON-NLS-1$
setInstallCommand(new UICommand("Install", this)); //$NON-NLS-1$
setEditHostCommand(new UICommand("EditHost", this)); //$NON-NLS-1$
setGoToEventsCommand(new UICommand("GoToEvents", this)); //$NON-NLS-1$
}
public void SaveNICsConfig()
{
Frontend.RunMultipleAction(VdcActionType.CommitNetworkChanges,
new ArrayList<VdcActionParametersBase>(Arrays.asList(new VdcActionParametersBase[] {new VdsActionParameters(getEntity().getId())})),
new IFrontendMultipleActionAsyncCallback() {
@Override
public void Executed(FrontendMultipleActionAsyncResult result) {
}
},
null);
}
private Version GetVersionFromOS(String os) {
try {
if (!StringHelper.isNullOrEmpty(os)) {
String[] parts = os.split("-"); //$NON-NLS-1$
if (parts.length == 3) {
parts = parts[2].trim().split("\\."); //$NON-NLS-1$
return new Version(parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3]); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
}
} catch (Exception ex) {
// Do nothing.
} finally {
return new Version(0, 0, 0, 0);
}
}
public void Install() {
if (getWindow() != null) {
return;
}
InstallModel model = new InstallModel();
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().installHostTitle());
model.setHashName("install_host"); //$NON-NLS-1$
model.getOVirtISO().setIsAvailable(false);
model.getRootPassword().setIsAvailable(false);
model.getOverrideIpTables().setIsAvailable(false);
final Version hostOsVersion = GetVersionFromOS(getEntity().gethost_os());
model.getHostVersion().setEntity(hostOsVersion.getMajor() + "." + hostOsVersion.getMinor()); //$NON-NLS-1$
model.getHostVersion().setIsAvailable(false);
getWindow().StartProgress(null);
if (getEntity().getvds_type() == VDSType.oVirtNode) {
AsyncDataProvider.GetoVirtISOsList(new AsyncQuery(model,
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
InstallModel model = (InstallModel) target;
ArrayList<RpmVersion> isos = (ArrayList<RpmVersion>) returnValue;
isos = Linq.OrderByDescending(isos, new Linq.RpmVersionComparer());
model.getOVirtISO().setItems(isos);
model.getOVirtISO().setSelectedItem(Linq.FirstOrDefault(isos));
model.getOVirtISO().setIsAvailable(true);
model.getOVirtISO().setIsChangable(!isos.isEmpty());
model.getHostVersion().setIsAvailable(true);
if (isos.isEmpty()) {
model.setMessage(ConstantsManager.getInstance()
.getConstants()
.thereAreNoISOversionsVompatibleWithHostCurrentVerMsg());
}
AddInstallCommands(model, isos.isEmpty());
getWindow().StopProgress();
}
}),
null);
} else {
model.getRootPassword().setIsAvailable(true);
model.getRootPassword().setIsChangable(true);
Version v3 = new Version(3, 0);
boolean isLessThan3 = getEntity().getvds_group_compatibility_version().compareTo(v3) < 0;
if (!isLessThan3) {
model.getOverrideIpTables().setIsAvailable(true);
model.getOverrideIpTables().setEntity(true);
}
AddInstallCommands(model, false);
getWindow().StopProgress();
}
}
private void AddInstallCommands(InstallModel model, boolean isOnlyClose) {
if (!isOnlyClose) {
UICommand command = new UICommand("OnInstall", this); //$NON-NLS-1$
command.setTitle(ConstantsManager.getInstance().getConstants().ok());
command.setIsDefault(true);
model.getCommands().add(command);
}
UICommand command = new UICommand("Cancel", this); //$NON-NLS-1$
command.setTitle(isOnlyClose ? ConstantsManager.getInstance().getConstants().close()
: ConstantsManager.getInstance().getConstants().cancel());
command.setIsCancel(true);
model.getCommands().add(command);
}
public void EditHost()
{
// Let's the parent model know about request.
getRequestEditEvent().raise(this, EventArgs.Empty);
}
public void OnInstall()
{
InstallModel model = (InstallModel) getWindow();
boolean isOVirt = getEntity().getvds_type() == VDSType.oVirtNode;
if (!model.Validate(isOVirt))
{
return;
}
UpdateVdsActionParameters param = new UpdateVdsActionParameters();
param.setvds(getEntity());
param.setVdsId(getEntity().getId());
param.setRootPassword((String) model.getRootPassword().getEntity());
param.setIsReinstallOrUpgrade(true);
param.setInstallVds(true);
param.setoVirtIsoFile(isOVirt ? ((RpmVersion) model.getOVirtISO().getSelectedItem()).getRpmName() : null);
param.setOverrideFirewall((Boolean) model.getOverrideIpTables().getEntity());
Frontend.RunAction(
VdcActionType.UpdateVds,
param,
new IFrontendActionAsyncCallback() {
@Override
public void Executed(FrontendActionAsyncResult result) {
VdcReturnValueBase returnValue = result.getReturnValue();
if (returnValue != null && returnValue.getSucceeded()) {
Cancel();
}
}
}
);
}
private VdsVersion GetHostVersion(Guid hostId)
{
VDS host = DataProvider.GetHostById(hostId);
return host != null ? host.getVersion() : new VdsVersion();
}
public void Cancel()
{
setWindow(null);
}
@Override
protected void OnEntityChanged()
{
super.OnEntityChanged();
if (getEntity() != null)
{
UpdateAlerts();
UpdateMemory();
UpdateSwapUsed();
UpdateProperties();
}
}
@Override
protected void EntityPropertyChanged(Object sender, PropertyChangedEventArgs e)
{
super.EntityPropertyChanged(sender, e);
if (e.PropertyName.equals("net_config_dirty") || e.PropertyName.equals("status") //$NON-NLS-1$ //$NON-NLS-2$
|| e.PropertyName.equals("spm_status") || e.PropertyName.equals("vm_active")) //$NON-NLS-1$ //$NON-NLS-2$
{
UpdateAlerts();
}
if (e.PropertyName.equals("usage_mem_percent") || e.PropertyName.equals("physical_mem_mb")) //$NON-NLS-1$ //$NON-NLS-2$
{
UpdateMemory();
}
if (e.PropertyName.equals("swap_total") || e.PropertyName.equals("swap_free")) //$NON-NLS-1$ //$NON-NLS-2$
{
UpdateSwapUsed();
}
}
private void UpdateProperties()
{
VDS vds = getEntity();
setOS(vds.gethost_os());
setKernelVersion(vds.getkernel_version());
setKvmVersion(vds.getkvm_version());
setVdsmVersion(vds.getVersion().getFullVersion());
setSpiceVersion(vds.getspice_version());
setIScsiInitiatorName(vds.getIScsiInitiatorName());
setActiveVms(vds.getvm_active());
setMemoryPageSharing(vds.getksm_state());
setAutomaticLargePage(vds.getTransparentHugePagesState());
setNumberOfCPUs(vds.getcpu_cores());
setCpuName(vds.getCpuName() != null ? vds.getCpuName().getCpuName() : null);
setCpuType(vds.getcpu_model());
setSharedMemory(vds.getmem_shared_percent());
setPhysicalMemory(vds.getphysical_mem_mb());
setSwapTotal(vds.getswap_total());
setSwapFree(vds.getswap_free());
}
private void UpdateAlerts()
{
setHasAnyAlert(false);
setHasUpgradeAlert(false);
setHasManualFenceAlert(false);
setHasNoPowerManagementAlert(false);
setHasReinstallAlertNonResponsive(false);
setHasReinstallAlertInstallFailed(false);
setHasReinstallAlertMaintenance(false);
setHasNICsAlert(false);
getInstallCommand().setIsExecutionAllowed(true);
getEditHostCommand().setIsExecutionAllowed(VdcActionUtils.CanExecute(new ArrayList<VDS>(Arrays.asList(new VDS[] { getEntity() })),
VDS.class,
VdcActionType.UpdateVds));
// Check the network alert presense.
setHasNICsAlert((getEntity().getnet_config_dirty() == null ? false : getEntity().getnet_config_dirty()));
// Check manual fence alert presense.
if (getEntity().getstatus() == VDSStatus.NonResponsive
&& !getEntity().getpm_enabled()
&& ((getEntity().getvm_active() == null ? 0 : getEntity().getvm_active()) > 0 || getEntity().getspm_status() == VdsSpmStatus.SPM))
{
setHasManualFenceAlert(true);
}
else if (!getEntity().getpm_enabled())
{
setHasNoPowerManagementAlert(true);
}
// Check the reinstall alert presense.
if (getEntity().getstatus() == VDSStatus.NonResponsive)
{
setHasReinstallAlertNonResponsive(true);
}
else if (getEntity().getstatus() == VDSStatus.InstallFailed)
{
setHasReinstallAlertInstallFailed(true);
}
else if (getEntity().getstatus() == VDSStatus.Maintenance)
{
setHasReinstallAlertMaintenance(true);
}
// TODO: Need to come up with a logic to show the Upgrade action-item.
// Currently, this action-item will be shown for all oVirts assuming there are
// available oVirt ISOs that are returned by the backend's GetoVirtISOs query.
else if (getEntity().getvds_type() == VDSType.oVirtNode && isEntityChanged)
{
AsyncDataProvider.GetoVirtISOsList(new AsyncQuery(this,
new INewAsyncCallback() {
@Override
public void OnSuccess(Object target, Object returnValue) {
HostGeneralModel hostGeneralModel = (HostGeneralModel) target;
ArrayList<RpmVersion> isos = (ArrayList<RpmVersion>) returnValue;
if (isos.size() > 0)
{
VDS vds = hostGeneralModel.getEntity();
hostGeneralModel.setHasUpgradeAlert(true);
hostGeneralModel.getInstallCommand()
.setIsExecutionAllowed(vds.getstatus() != VDSStatus.Up
&& vds.getstatus() != VDSStatus.Installing
&& vds.getstatus() != VDSStatus.PreparingForMaintenance
&& vds.getstatus() != VDSStatus.Reboot
&& vds.getstatus() != VDSStatus.PendingApproval);
if (!hostGeneralModel.getInstallCommand().getIsExecutionAllowed())
{
hostGeneralModel.getInstallCommand()
.getExecuteProhibitionReasons()
.add(ConstantsManager.getInstance()
.getConstants()
.switchToMaintenanceModeToEnableUpgradeReason());
}
}
}
}),
getEntity().getId());
}
setNonOperationalReasonEntity((getEntity().getNonOperationalReason() == NonOperationalReason.NONE ? null
: (NonOperationalReason) getEntity().getNonOperationalReason()));
setHasAnyAlert(getHasNICsAlert() || getHasUpgradeAlert() || getHasManualFenceAlert()
|| getHasNoPowerManagementAlert() || getHasReinstallAlertNonResponsive()
|| getHasReinstallAlertInstallFailed() || getHasReinstallAlertMaintenance());
}
private void GoToEvents()
{
this.getRequestGOToEventsTabEvent().raise(this, null);
}
private void UpdateMemory()
{
setFreeMemory(null);
setUsedMemory(null);
if (getEntity().getphysical_mem_mb() != null && getEntity().getusage_mem_percent() != null)
{
setFreeMemory(getEntity().getphysical_mem_mb()
- (getEntity().getphysical_mem_mb() / 100 * getEntity().getusage_mem_percent()));
setUsedMemory(getEntity().getphysical_mem_mb() - getFreeMemory());
}
}
private void UpdateSwapUsed()
{
setUsedSwap(null);
if (getEntity().getswap_total() != null && getEntity().getswap_free() != null)
{
setUsedSwap(getEntity().getswap_total() - getEntity().getswap_free());
}
}
@Override
public void ExecuteCommand(UICommand command)
{
super.ExecuteCommand(command);
if (command == getSaveNICsConfigCommand())
{
SaveNICsConfig();
}
else if (command == getInstallCommand())
{
Install();
}
else if (command == getEditHostCommand())
{
EditHost();
}
else if (command == getGoToEventsCommand())
{
GoToEvents();
}
else if (StringHelper.stringsEqual(command.getName(), "OnInstall")) //$NON-NLS-1$
{
OnInstall();
}
else if (StringHelper.stringsEqual(command.getName(), "Cancel")) //$NON-NLS-1$
{
Cancel();
}
}
} |
package org.wikipedia;
import java.io.File;
import java.net.URLEncoder;
import java.util.*;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Unit tests for Wiki.java
* @author MER-C
*/
public class WikiUnitTest
{
private static Wiki enWiki, deWiki, arWiki, testWiki;
public WikiUnitTest()
{
}
/**
* Initialize wiki objects.
*/
@BeforeClass
public static void setUpClass()
{
enWiki = new Wiki("en.wikipedia.org");
enWiki.setMaxLag(-1);
deWiki = new Wiki("de.wikipedia.org");
deWiki.setMaxLag(-1);
arWiki = new Wiki("ar.wikipedia.org");
arWiki.setMaxLag(-1);
testWiki = new Wiki("test.wikipedia.org");
testWiki.setMaxLag(-1);
}
@Test
public void namespace() throws Exception
{
assertEquals("NS: en, category", Wiki.CATEGORY_NAMESPACE, enWiki.namespace("Category:CSD"));
assertEquals("NS: en, alias", Wiki.PROJECT_NAMESPACE, enWiki.namespace("WP:CSD"));
assertEquals("NS: main ns fail", Wiki.MAIN_NAMESPACE, enWiki.namespace("Star Wars: The Old Republic"));
assertEquals("NS: main ns fail2", Wiki.MAIN_NAMESPACE, enWiki.namespace("Some Category: Blah"));
assertEquals("NS: i18n fail", Wiki.CATEGORY_NAMESPACE, deWiki.namespace("Kategorie:Begriffsklärung"));
assertEquals("NS: mixed i18n", Wiki.CATEGORY_NAMESPACE, deWiki.namespace("Category:Begriffsklärung"));
assertEquals("NS: rtl fail", Wiki.CATEGORY_NAMESPACE, arWiki.namespace("تصنيف:صفحات_للحذف_السريع"));
}
@Test
public void namespaceIdentifier() throws Exception
{
assertEquals("NSIdentifier: wrong identifier", "Category", enWiki.namespaceIdentifier(Wiki.CATEGORY_NAMESPACE));
assertEquals("NSIdentifier: i18n fail", "Kategorie", deWiki.namespaceIdentifier(Wiki.CATEGORY_NAMESPACE));
assertEquals("NSIdentifier: custom namespace", "Portal", enWiki.namespaceIdentifier(100));
}
@Test
public void userExists() throws Exception
{
assertTrue("I should exist!", enWiki.userExists("MER-C"));
assertFalse("Anon should not exist", enWiki.userExists("127.0.0.1"));
}
@Test
public void getFirstRevision() throws Exception
{
assertNull("Non-existent page", enWiki.getFirstRevision("dgfhdf&jklg"));
}
@Test
public void getLastRevision() throws Exception
{
assertNull("Non-existent page", enWiki.getTopRevision("dgfhd&fjklg"));
}
@Test
public void getTemplates() throws Exception
{
assertArrayEquals("getTemplates: non-existent page", new String[0], enWiki.getTemplates("sdkf&hsdklj"));
assertArrayEquals("getTemplates: page with no templates", new String[0], enWiki.getTemplates("User:MER-C/monobook.js"));
}
@Test
public void exists() throws Exception
{
String[] titles = new String[] { "Main Page", "Tdkfgjsldf", "User:MER-C", "Wikipedia:Skfjdl", "Main Page", "Fish & chips" };
boolean[] expected = new boolean[] { true, false, true, false, true, true };
assertTrue("exists", Arrays.equals(expected, enWiki.exists(titles)));
}
@Test
public void resolveRedirects() throws Exception
{
String[] titles = new String[] { "Main page", "Main Page", "sdkghsdklg", "Hello.jpg", "Main page", "Fish & chips" };
String[] expected = new String[] { "Main Page", null, null, "Goatse.cx", "Main Page", "Fish and chips" };
assertArrayEquals("resolveRedirects", expected, enWiki.resolveRedirects(titles));
assertEquals("resolveRedirects: RTL", "الصفحة الرئيسية", arWiki.resolveRedirect("الصفحه الرئيسيه"));
}
@Test
public void getLinksOnPage() throws Exception
{
assertArrayEquals("getLinksOnPage: non-existent page", new String[0], enWiki.getLinksOnPage("Skfls&jdkfs"));
// User:MER-C/monobook.js has one link... despite it being preformatted (?!)
assertArrayEquals("getLinksOnPage: page with no links", new String[0], enWiki.getLinksOnPage("User:MER-C/monobook.css"));
}
@Test
public void getImagesOnPage() throws Exception
{
assertArrayEquals("getImagesOnPage: non-existent page", new String[0], enWiki.getImagesOnPage("Skflsj&dkfs"));
assertArrayEquals("getImagesOnPage: page with no images", new String[0], enWiki.getImagesOnPage("User:MER-C/monobook.js"));
}
@Test
public void getCategories() throws Exception
{
assertArrayEquals("getCategories: non-existent page", new String[0], enWiki.getImagesOnPage("Skfls&jdkfs"));
assertArrayEquals("getCategories: page with no images", new String[0], enWiki.getImagesOnPage("User:MER-C/monobook.js"));
}
@Test
public void getImageHistory() throws Exception
{
assertArrayEquals("getImageHistory: non-existent file", new Wiki.LogEntry[0], enWiki.getImageHistory("File:Sdfjgh&sld.jpg"));
assertArrayEquals("getImageHistory: commons image", new Wiki.LogEntry[0], enWiki.getImageHistory("File:WikipediaSignpostIcon.svg"));
}
@Test
public void getImage() throws Exception
{
File tempfile = File.createTempFile("wiki-java_getImage", null);
tempfile.deleteOnExit();
assertFalse("getImage: non-existent file", enWiki.getImage("File:Sdkjf&sdlf.blah", tempfile));
}
@Test
public void getPageHistory() throws Exception
{
assertArrayEquals("getPageHistory: non-existent page", new Wiki.Revision[0], enWiki.getPageHistory("EOTkd&ssdf"));
assertArrayEquals("getPageHistory: special page", new Wiki.Revision[0], enWiki.getPageHistory("Special:Specialpages"));
}
@Test
public void getPageInfo() throws Exception
{
Map<String, Object>[] pageinfo = enWiki.getPageInfo(new String[] { "Main Page", "IPod" });
// Main Page
Map<String, Object> protection = (Map<String, Object>)pageinfo[0].get("protectionstate");
assertEquals("getPageInfo: Main Page edit protection level", Wiki.FULL_PROTECTION, protection.get("edit"));
assertNull("getPageInfo: Main Page edit protection expiry", protection.get("editexpiry"));
assertEquals("getPageInfo: Main Page move protection level", Wiki.FULL_PROTECTION, protection.get("move"));
assertNull("getPageInfo: Main Page move protection expiry", protection.get("moveexpiry"));
assertTrue("getPageInfo: Main Page cascade protection", (Boolean)protection.get("cascade"));
assertEquals("getPageInfo: Main Page display title", "Main Page", pageinfo[0].get("displaytitle"));
// different display title
assertEquals("getPageInfo: iPod display title", "iPod", pageinfo[1].get("displaytitle"));
}
@Test
public void getFileMetadata() throws Exception
{
assertNull("getFileMetadata: non-existent file", enWiki.getFileMetadata("File:Lweo&pafd.blah"));
assertNull("getFileMetadata: commons image", enWiki.getFileMetadata("File:WikipediaSignpostIcon.svg"));
}
@Test
public void getDuplicates() throws Exception
{
assertArrayEquals("getDuplicates: non-existent file", new String[0], enWiki.getImageHistory("File:Sdfj&ghsld.jpg"));
}
@Test
public void getInterWikiLinks() throws Exception
{
Map<String, String> temp = enWiki.getInterWikiLinks("Gkdfkkl&djfdf");
assertTrue("getInterWikiLinks: non-existent page", temp.isEmpty());
}
@Test
public void getExternalLinksOnPage() throws Exception
{
assertArrayEquals("getExternalLinksOnPage: non-existent page", new String[0], enWiki.getExternalLinksOnPage("Gdkgfskl&dkf"));
assertArrayEquals("getExternalLinksOnPage: page with no links", new String[0], enWiki.getExternalLinksOnPage("User:MER-C/monobook.js"));
}
@Test
public void getSectionText() throws Exception
{
assertEquals("getSectionText(): section 0", "This is section 0.", testWiki.getSectionText("User:MER-C/UnitTests/SectionTest", 0));
assertEquals("getSectionText(): section 2", "===Section 3===\nThis is section 2.",
testWiki.getSectionText("User:MER-C/UnitTests/SectionTest", 2));
}
@Test
public void random() throws Exception
{
for (int i = 0; i < 3; i++)
{
String random = enWiki.random();
assertEquals("random: main namespace", Wiki.MAIN_NAMESPACE, enWiki.namespace(random));
random = enWiki.random(Wiki.PROJECT_NAMESPACE, Wiki.USER_NAMESPACE);
int temp = enWiki.namespace(random);
if (temp != Wiki.PROJECT_NAMESPACE && temp != Wiki.USER_NAMESPACE)
fail("random: multiple namespaces");
}
}
@Test
public void getSiteInfo() throws Exception
{
Map<String, Object> info = enWiki.getSiteInfo();
assertTrue("siteinfo: caplinks true", (Boolean)info.get("usingcapitallinks"));
assertEquals("siteinfo: scriptpath", "/w", (String)info.get("scriptpath"));
info = new Wiki("en.wiktionary.org").getSiteInfo();
assertFalse("siteinfo: caplinks false", (Boolean)info.get("usingcapitallinks"));
}
@Test
public void normalize() throws Exception
{
assertEquals("normalize", "Blah", enWiki.normalize("Blah"));
assertEquals("normalize", "Blah", enWiki.normalize("blah"));
assertEquals("normalize", "File:Blah.jpg", enWiki.normalize("File:Blah.jpg"));
assertEquals("normalize", "File:Blah.jpg", enWiki.normalize("File:blah.jpg"));
assertEquals("normalize", "Category:Wikipedia:blah", enWiki.normalize("Category:Wikipedia:blah"));
assertEquals("normalize", "Hilfe Diskussion:Glossar", deWiki.normalize("Help talk:Glossar"));
}
@Test
public void getRevision() throws Exception
{
Wiki.Revision rev = enWiki.getRevision(597454682L);
assertEquals("getRevision: page", "Wikipedia talk:WikiProject Spam", rev.getPage());
assertEquals("getRevision: timestamp", "20140228004031", enWiki.calendarToTimestamp(rev.getTimestamp()));
assertEquals("getRevision: user", "Lowercase sigmabot III", rev.getUser());
assertEquals("getRevision: summary", "Archiving 3 discussion(s) to [[Wikipedia talk:WikiProject Spam/2014 Archive Feb 1]]) (bot",
rev.getSummary());
assertEquals("getRevision: size", 4286, rev.getSize());
assertEquals("getRevision: revid", 597454682L, rev.getRevid());
assertEquals("getRevision: previous", 597399794L, rev.getPrevious().getRevid());
// assertEquals("getRevision: next", 597553957L, rev.getNext().getRevid());
assertTrue("getRevision: minor", rev.isMinor());
assertFalse("getRevision: new", rev.isNew());
assertFalse("getRevison: bot", rev.isBot());
assertFalse("getRevision: user not revdeled", rev.isUserDeleted());
assertFalse("getRevision: summary not revdeled", rev.isSummaryDeleted());
assertFalse("getRevision: content not deleted", rev.isContentDeleted());
assertFalse("getRevision: page not deleted", rev.isPageDeleted());
// revdel, logged out
rev = enWiki.getRevision(596714684L);
assertNull("getRevision: summary revdeled", rev.getSummary());
assertNull("getRevision: user revdeled", rev.getUser());
assertTrue("getRevision: user revdeled", rev.isUserDeleted());
assertTrue("getRevision: summary revdeled", rev.isSummaryDeleted());
// NOT IMPLEMENTED:
// assertTrue("getRevision: content revdeled", rev.isContentDeleted());
}
@Test
public void diff() throws Exception
{
assertNull("diff: no previous revision", enWiki.getRevision(586849481L).diff(Wiki.PREVIOUS_REVISION));
}
@Test
public void contribs() throws Exception
{
// should really be null, but the API returns zero
assertEquals("contribs: non-existent user", testWiki.contribs("Dsdlgfkjsdlkfdjilgsujilvjcl").length, 0);
}
@Test
public void getPageText() throws Exception
{
String text = testWiki.getPageText("User:MER-C/UnitTests/Delete");
assertEquals("getPageText", text, "This revision is not deleted!\n");
text = testWiki.getPageText("User:MER-C/UnitTests/pagetext");
assertEquals("page text: decoding", text, "''italic''" +
"\n'''&'''\n&&\n<>\n<>\n"\n");
}
@Test
public void constructNamespaceString() throws Exception
{
StringBuilder temp = new StringBuilder();
enWiki.constructNamespaceString(temp, "blah", 1, 2, 3);
assertEquals("constructNamespaceString", "&blahnamespace=1%7C2%7C3", temp.toString());
}
@Test
public void constructTitleString() throws Exception
{
String[] titles = new String[101];
for (int i = 0; i < titles.length; i++)
titles[i] = "a" + i;
String[] expected = new String[]
{
// slowmax == 50 for Wikimedia wikis if not logged in
URLEncoder.encode("A0|A1|A2|A3|A4|A5|A6|A7|A8|A9|A10|A11|A12|A13|A14|" +
"A15|A16|A17|A18|A19|A20|A21|A22|A23|A24|A25|A26|A27|A28|A29|A30|" +
"A31|A32|A33|A34|A35|A36|A37|A38|A39|A40|A41|A42|A43|A44|A45|A46|" +
"A47|A48|A49", "UTF-8"),
URLEncoder.encode("A50|A51|A52|A53|A54|A55|A56|A57|A58|A59|A60|A61|A62|" +
"A63|A64|A65|A66|A67|A68|A69|A70|A71|A72|A73|A74|A75|A76|A77|A78|A79|" +
"A80|A81|A82|A83|A84|A85|A86|A87|A88|A89|A90|A91|A92|A93|A94|A95|A96|" +
"A97|A98|A99", "UTF-8"),
URLEncoder.encode("A100", "UTF-8")
};
String[] actual = enWiki.constructTitleString(titles);
assertArrayEquals("constructTitleString", expected, actual);
}
// INNER CLASS TESTS
@Test
public void revisionGetText() throws Exception
{
Wiki.Revision rev = testWiki.getRevision(230472);
String text = rev.getText();
assertEquals("revision text: decoding", text, "''italic''" +
"\n'''&'''\n&&\n<>\n<>\n"\n");
}
} |
package ua.com.fielden.platform.web.view.master.metadata;
import static java.util.Optional.empty;
import static ua.com.fielden.platform.web.centre.EntityCentre.IMPORTS;
import static ua.com.fielden.platform.web.view.master.EntityMaster.ENTITY_TYPE;
import static ua.com.fielden.platform.web.view.master.EntityMaster.flattenedNameOf;
import static ua.com.fielden.platform.web.view.master.api.impl.SimpleMasterBuilder.createImports;
import java.util.LinkedHashSet;
import java.util.Optional;
import ua.com.fielden.platform.basic.IValueMatcherWithContext;
import ua.com.fielden.platform.dom.DomElement;
import ua.com.fielden.platform.dom.InnerTextElement;
import ua.com.fielden.platform.domain.metadata.DomainExplorerInsertionPoint;
import ua.com.fielden.platform.utils.ResourceLoader;
import ua.com.fielden.platform.web.centre.api.actions.EntityActionConfig;
import ua.com.fielden.platform.web.centre.api.resultset.impl.FunctionalActionKind;
import ua.com.fielden.platform.web.interfaces.IRenderable;
import ua.com.fielden.platform.web.view.master.api.IMaster;
public class DomainExplorerInsertionPointMaster implements IMaster<DomainExplorerInsertionPoint> {
private final IRenderable renderable;
public DomainExplorerInsertionPointMaster () {
final LinkedHashSet<String> importPaths = new LinkedHashSet<>();
importPaths.add("components/tg-domain-explorer");
importPaths.add("editors/tg-singleline-text-editor");
importPaths.add("polymer/@polymer/iron-icons/iron-icons");
importPaths.add("polymer/@polymer/paper-icon-button/paper-icon-button");
final DomElement searchItemsText = new DomElement("div").attr("slot", "property-action").attr("hidden", "[[!_searchText]]").add(new InnerTextElement("[[_calcMatchedItems(_searchText, _matchedItemOrder, _matchedItemsNumber)]]"))
.style("font-size: 0.9rem", "color:#757575", "margin-right: 8px");
final DomElement prevButton = new DomElement("paper-icon-button").attr("slot", "property-action").attr("hidden", "[[!_searchText]]").attr("icon", "icons:expand-less").attr("on-tap", "_goToPrevMatchedItem")
.style("width:24px","height:24px", "padding:4px", "color:#757575");
final DomElement nextButton = new DomElement("paper-icon-button").attr("slot", "property-action").attr("hidden", "[[!_searchText]]").attr("icon", "icons:expand-more").attr("on-tap", "_goToNextMatchedItem")
.style("width:24px","height:24px", "padding:4px", "color:#757575");
final DomElement domainFilter = new DomElement("tg-singleline-text-editor")
.attr("id", "domainFilter")
.attr("class", "filter-element")
.attr("slot", "filter-element")
.attr("entity", "{{_currBindingEntity}}")
.attr("original-entity", "{{_originalBindingEntity}}")
.attr("previous-modified-properties-holder", "[[_previousModifiedPropertiesHolder]]")
.attr("property-name", "domainFilter")
.attr("validation-callback", "[[doNotValidate]]")
.attr("prop-title", "Type to find domain type or property by title")
.attr("prop-desc", "Finds domain types or properties that match the search text")
.attr("current-state", "[[currentState]]")
.add(searchItemsText, prevButton, nextButton);
final DomElement domainExplorerDom = new DomElement("tg-domain-explorer")
.attr("id", "domainExplorer")
.attr("entity", "{{_currBindingEntity}}")
.attr("last-search-text", "{{_searchText}}")
.attr("matched-item-order", "{{_matchedItemOrder}}")
.attr("number-of-matched-items", "{{_matchedItemsNumber}}")
.attr("on-tg-load-sub-domain", "_loadSubDomain")
.add(domainFilter);
final StringBuilder prefDimBuilder = new StringBuilder();
prefDimBuilder.append("{'width': function() {return '100%'}, 'height': function() {return '100%'}, 'widthUnit': '', 'heightUnit': ''}");
final String entityMasterStr = ResourceLoader.getText("ua/com/fielden/platform/web/master/tg-entity-master-template.js")
.replace(IMPORTS, createImports(importPaths)
+ "\nimport { TgEntityBinderBehavior } from '/resources/binding/tg-entity-binder-behavior.js';\n")
.replace(ENTITY_TYPE, flattenedNameOf(DomainExplorerInsertionPoint.class))
.replace("<!--@tg-entity-master-content-->", domainExplorerDom.toString())
.replace("//@ready-callback", readyCallback())
.replace("@prefDim", prefDimBuilder.toString())
.replace("@noUiValue", "false")
.replace("@saveOnActivationValue", "true");
renderable = new IRenderable() {
@Override
public DomElement render() {
return new InnerTextElement(entityMasterStr);
}
};
}
private String readyCallback() {
return "self.classList.add('layout');\n"
+ "self._searchText = '';\n"
+ "self._matchedItemOrder = 0;\n"
+ "self._matchedItemsNumber = 0;\n"
+ "self.classList.add('vertical');\n"
+ "self.canLeave = function () {\n"
+ " return null;\n"
+ "}.bind(self);\n"
+ "self._showDataLoadingPromt = function (msg) {\n"
+ " this.$.domainExplorer.lock = true;\n"
+ " this._toastGreeting().text = msg;\n"
+ " this._toastGreeting().hasMore = false;\n"
+ " this._toastGreeting().showProgress = true;\n"
+ " this._toastGreeting().msgHeading = 'Info';\n"
+ " this._toastGreeting().isCritical = false;\n"
+ " this._toastGreeting().show();\n"
+ "}.bind(self);\n"
+ "self._showDataLoadedPromt = function (msg) {\n"
+ " this.$.domainExplorer.lock = false;\n"
+ " this._toastGreeting().text = msg;\n"
+ " this._toastGreeting().hasMore = false;\n"
+ " this._toastGreeting().showProgress = false;\n"
+ " this._toastGreeting().msgHeading = 'Info';\n"
+ " this._toastGreeting().isCritical = false;\n"
+ " this._toastGreeting().show();\n"
+ "}.bind(self);\n"
+"//Locks/Unlocks tg-domain-explorer's lock layer during insertion point action activation\n"
+ "self.disableViewForDescendants = function () {\n"
+ " TgEntityBinderBehavior.disableViewForDescendants.call(this);\n"
+ " self._showDataLoadingPromt('Loading domain...');\n"
+ "}.bind(self);\n"
+ "self.enableViewForDescendants = function () {\n"
+ " TgEntityBinderBehavior.enableViewForDescendants.call(this);\n"
+ " self._showDataLoadedPromt('Loading completed successfully');\n"
+ "}.bind(self);\n"
+ "//Is Needed to sent data to server.\n"
+ "self._isNecessaryForConversion = function (propertyName) { \n"
+ " return ['domainTypeName', 'loadedHierarchy', 'domainFilter', 'domainTypeHolderId', 'domainPropertyHolderId'].indexOf(propertyName) >= 0; \n"
+ "}; \n"
+ "self.$.domainFilter._onInput = function () {\n"
+ " // clear domain explorer filter timer if it is in progress.\n"
+ " this._cancelDomainExplorerFilterTimer();\n"
+ " this._domainExplorerFilterTimer = this.async(this._findTreeItems, 500);\n"
+ "}.bind(self);\n"
+ "self._cancelDomainExplorerFilterTimer = function () {\n"
+ " if (this._domainExplorerFilterTimer) {\n"
+ " this.cancelAsync(this._domainExplorerFilterTimer);\n"
+ " this._domainExplorerFilterTimer = null;\n"
+ " }\n"
+ "}.bind(self);\n"
+ "self._findTreeItems = function () {\n"
+ " this.$.domainExplorer.find(this.$.domainFilter._editingValue);\n"
+ "}.bind(self);\n"
+ "self._loadSubDomain = function (e) {\n"
+ " this.save();\n"
+ "}.bind(self);\n"
+ "self._calcMatchedItems= function (_searchText, _matchedItemOrder, _matchedItemsNumber) {\n"
+ " if (_searchText) {\n"
+ " return _matchedItemOrder + ' / ' + _matchedItemsNumber;\n"
+ " }\n"
+ " return '';\n"
+ "}.bind(self);\n"
+ "self._goToPrevMatchedItem = function (e) {\n"
+ " this.$.domainExplorer.goToPreviousMatchedItem();"
+ "}.bind(self);\n"
+ "self._goToNextMatchedItem = function (e) {\n"
+ " this.$.domainExplorer.goToNextMatchedItem();"
+ "}.bind(self);\n";
}
@Override
public IRenderable render() {
return renderable;
}
@Override
public Optional<Class<? extends IValueMatcherWithContext<DomainExplorerInsertionPoint, ?>>> matcherTypeFor(final String propName) {
return empty();
}
@Override
public EntityActionConfig actionConfig(final FunctionalActionKind actionKind, final int actionNumber) {
throw new UnsupportedOperationException("Getting of action configuration is not supported.");
}
} |
package com.alibaba.easyexcel.test.demo.web;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
/**
* web
*
* @author Jiaju Zhuang
**/
@Controller
public class WebTest {
@Autowired
private UploadDAO uploadDAO;
/**
* Excel
* <p>
* 1. excel {@link DownloadData}
* <p>
* 2.
* <p>
* 3. finishOutputStream,
*/
@GetMapping("download")
public void download(HttpServletResponse response) throws IOException {
// swagger postman
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// URLEncoder.encode easyexcel
String fileName = URLEncoder.encode("", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), DownloadData.class).sheet("").doWrite(data());
}
/**
* jsonExcel
*
* @since 2.1.1
*/
@GetMapping("downloadFailedUsingJson")
public void downloadFailedUsingJson(HttpServletResponse response) throws IOException {
// swagger postman
try {
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
// URLEncoder.encode easyexcel
String fileName = URLEncoder.encode("", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
EasyExcel.write(response.getOutputStream(), DownloadData.class).autoCloseStream(Boolean.FALSE).sheet("")
.doWrite(data());
} catch (Exception e) {
// response
response.reset();
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
Map<String, String> map = new HashMap<String, String>();
map.put("status", "failure");
map.put("message", "" + e.getMessage());
response.getWriter().println(JSON.toJSONString(map));
}
}
/**
*
* <p>
* 1. excel {@link UploadData}
* <p>
* 2. excelexcel{@link UploadDataListener}
* <p>
* 3.
*/
@PostMapping("upload")
@ResponseBody
public String upload(MultipartFile file) throws IOException {
EasyExcel.read(file.getInputStream(), UploadData.class, new UploadDataListener(uploadDAO)).sheet().doRead();
return "success";
}
private List<DownloadData> data() {
List<DownloadData> list = new ArrayList<DownloadData>();
for (int i = 0; i < 10; i++) {
DownloadData data = new DownloadData();
data.setString("" + 0);
data.setDate(new Date());
data.setDoubleData(0.56);
list.add(data);
}
return list;
}
} |
package org.yakindu.sct.domain.generic.extension;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.ui.shared.SharedStateModule;
import org.yakindu.sct.domain.extension.IDomainInjectorProvider;
import org.yakindu.sct.domain.generic.modules.EntryRuleRuntimeModule;
import org.yakindu.sct.domain.generic.modules.EntryRuleUIModule;
import org.yakindu.sct.domain.generic.modules.GenericEditorModule;
import org.yakindu.sct.domain.generic.modules.GenericGeneratorModule;
import org.yakindu.sct.domain.generic.modules.GenericSequencerModule;
import org.yakindu.sct.domain.generic.modules.GenericSimulationModule;
import org.yakindu.sct.domain.generic.modules.GenericTypeSystemModule;
import org.yakindu.sct.model.sgraph.State;
import org.yakindu.sct.model.sgraph.Statechart;
import org.yakindu.sct.model.sgraph.Transition;
import org.yakindu.sct.model.stext.STextRuntimeModule;
import org.yakindu.sct.model.stext.stext.Guard;
import org.yakindu.sct.model.stext.stext.StateSpecification;
import org.yakindu.sct.model.stext.stext.StatechartSpecification;
import org.yakindu.sct.model.stext.stext.TransitionSpecification;
import org.yakindu.sct.model.stext.ui.STextUiModule;
import org.yakindu.sct.model.stext.ui.internal.STextActivator;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.util.Modules;
/**
*
* @author andreas muelder - Initial contribution and API
* @author terfloth - added editorInjector
*
*/
public class GenericDomainInjectorProvider implements IDomainInjectorProvider {
private static final Map<String, Class<? extends EObject>> semanticTargetToRuleMap = new HashMap<String, Class<? extends EObject>>();
private Injector resourceInjector;
private Map<String, Injector> embeddedInjectors = new HashMap<String, Injector>();
static {
semanticTargetToRuleMap.put(Statechart.class.getName(), StatechartSpecification.class);
semanticTargetToRuleMap.put(Transition.class.getName(), TransitionSpecification.class);
semanticTargetToRuleMap.put(State.class.getName(), StateSpecification.class);
semanticTargetToRuleMap.put(Guard.class.getName(), Guard.class);
}
public Module getSharedStateModule() {
return new SharedStateModule();
}
public Module getLanguageRuntimeModule() {
return new STextRuntimeModule();
}
public Module getLanguageUIModule() {
return new STextUiModule(STextActivator.getInstance());
}
public Module getTypeSystemModule() {
return new GenericTypeSystemModule();
}
public Module getSimulationModule() {
return new GenericSimulationModule();
}
public Module getSequencerModule() {
return new GenericSequencerModule();
}
public Module getGeneratorModule(String generatorId) {
// currently there is only one module with shared bindings for all code
// generators
return new GenericGeneratorModule();
}
protected Module getResourceModule() {
Module uiModule = Modules.override(getLanguageRuntimeModule()).with(getLanguageUIModule());
Module result = Modules.override(uiModule).with(getSharedStateModule());
return Modules.override(result).with(getTypeSystemModule());
}
protected Module getEmbeddedEditorModule(Class<? extends EObject> rule) {
Module runtimeModule = Modules.override(getLanguageRuntimeModule()).with(new EntryRuleRuntimeModule(rule));
Module uiModule = Modules.override(getLanguageUIModule()).with(new EntryRuleUIModule(rule));
Module result = Modules.override(Modules.override(runtimeModule).with(uiModule)).with(getSharedStateModule());
return Modules.override(result).with(getTypeSystemModule());
}
@Override
public Injector getEmbeddedEditorInjector(String semanticTarget) {
if (embeddedInjectors.get(semanticTarget) == null) {
Class<? extends EObject> rule = semanticTargetToRuleMap.get(semanticTarget);
org.eclipse.core.runtime.Assert.isNotNull(rule);
embeddedInjectors.put(semanticTarget, Guice.createInjector(getEmbeddedEditorModule(rule)));
}
return embeddedInjectors.get(semanticTarget);
}
@Override
public Injector getResourceInjector() {
if (resourceInjector == null)
resourceInjector = Guice.createInjector(getResourceModule());
return resourceInjector;
}
@Override
public Injector getSimulationInjector() {
return Guice.createInjector(getSimulationModule());
}
@Override
public Injector getSequencerInjector() {
return Guice.createInjector(getSequencerModule());
}
@Override
public Injector getSequencerInjector(Module overrides) {
if (overrides != null) {
return Guice.createInjector(Modules.override(getSequencerModule()).with(overrides));
}
return getSequencerInjector();
}
@Override
public Injector getEditorInjector() {
return Guice.createInjector(new GenericEditorModule());
}
@Override
public Injector getGeneratorInjector(String generatorId) {
return getGeneratorInjector(generatorId, null);
}
@Override
public Injector getGeneratorInjector(String generatorId, Module overrides) {
Module result = null;
if (overrides != null) {
result = Modules.override(getGeneratorModule(generatorId)).with(overrides);
} else
result = getGeneratorModule(generatorId);
result = Modules.override(getSequencerModule()).with(result);
return Guice.createInjector(result);
}
} |
package com.opengamma.financial.analytics.conversion;
import static com.opengamma.financial.convention.InMemoryConventionBundleMaster.simpleNameSecurityId;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.threeten.bp.LocalDate;
import org.threeten.bp.Period;
import org.threeten.bp.ZoneId;
import org.threeten.bp.ZoneOffset;
import org.threeten.bp.ZonedDateTime;
import com.google.common.collect.ImmutableSet;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.instrument.InstrumentDefinition;
import com.opengamma.analytics.financial.instrument.InstrumentDefinitionWithData;
import com.opengamma.analytics.financial.instrument.annuity.AnnuityCapFloorCMSDefinition;
import com.opengamma.analytics.financial.instrument.annuity.AnnuityCapFloorCMSSpreadDefinition;
import com.opengamma.analytics.financial.instrument.annuity.AnnuityCapFloorIborDefinition;
import com.opengamma.analytics.financial.instrument.fra.ForwardRateAgreementDefinition;
import com.opengamma.analytics.financial.instrument.future.BondFutureDefinition;
import com.opengamma.analytics.financial.instrument.future.FederalFundsFutureSecurityDefinition;
import com.opengamma.analytics.financial.instrument.future.FederalFundsFutureTransactionDefinition;
import com.opengamma.analytics.financial.instrument.future.InterestRateFutureOptionMarginTransactionDefinition;
import com.opengamma.analytics.financial.instrument.future.InterestRateFutureSecurityDefinition;
import com.opengamma.analytics.financial.instrument.future.InterestRateFutureTransactionDefinition;
import com.opengamma.analytics.financial.instrument.swap.SwapDefinition;
import com.opengamma.analytics.financial.instrument.swap.SwapFixedInflationYearOnYearDefinition;
import com.opengamma.analytics.financial.instrument.swap.SwapFixedInflationZeroCouponDefinition;
import com.opengamma.analytics.financial.instrument.swap.SwapFixedONSimplifiedDefinition;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivative;
import com.opengamma.core.historicaltimeseries.HistoricalTimeSeries;
import com.opengamma.core.security.Security;
import com.opengamma.core.value.MarketDataRequirementNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.financial.analytics.fixedincome.InterestRateInstrumentType;
import com.opengamma.financial.analytics.timeseries.DateConstraint;
import com.opengamma.financial.analytics.timeseries.HistoricalTimeSeriesBundle;
import com.opengamma.financial.analytics.timeseries.HistoricalTimeSeriesFunctionUtils;
import com.opengamma.financial.convention.ConventionBundle;
import com.opengamma.financial.convention.ConventionBundleSource;
import com.opengamma.financial.security.capfloor.CapFloorCMSSpreadSecurity;
import com.opengamma.financial.security.capfloor.CapFloorSecurity;
import com.opengamma.financial.security.fra.FRASecurity;
import com.opengamma.financial.security.future.BondFutureSecurity;
import com.opengamma.financial.security.future.FederalFundsFutureSecurity;
import com.opengamma.financial.security.future.InterestRateFutureSecurity;
import com.opengamma.financial.security.irs.FloatingInterestRateSwapLeg;
import com.opengamma.financial.security.irs.InterestRateSwapLeg;
import com.opengamma.financial.security.irs.InterestRateSwapSecurity;
import com.opengamma.financial.security.option.IRFutureOptionSecurity;
import com.opengamma.financial.security.option.SwaptionSecurity;
import com.opengamma.financial.security.swap.FloatingInterestRateLeg;
import com.opengamma.financial.security.swap.FloatingRateType;
import com.opengamma.financial.security.swap.InflationIndexSwapLeg;
import com.opengamma.financial.security.swap.SwapLeg;
import com.opengamma.financial.security.swap.SwapSecurity;
import com.opengamma.financial.security.swap.YearOnYearInflationSwapSecurity;
import com.opengamma.financial.security.swap.ZeroCouponInflationSwapSecurity;
import com.opengamma.id.ExternalId;
import com.opengamma.id.ExternalIdBundle;
import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesResolutionResult;
import com.opengamma.master.historicaltimeseries.HistoricalTimeSeriesResolver;
import com.opengamma.timeseries.DoubleTimeSeries;
import com.opengamma.timeseries.date.localdate.LocalDateDoubleEntryIterator;
import com.opengamma.timeseries.date.localdate.LocalDateDoubleTimeSeries;
import com.opengamma.timeseries.precise.zdt.ImmutableZonedDateTimeDoubleTimeSeries;
import com.opengamma.timeseries.precise.zdt.ZonedDateTimeDoubleTimeSeries;
import com.opengamma.timeseries.precise.zdt.ZonedDateTimeDoubleTimeSeriesBuilder;
import com.opengamma.util.ArgumentChecker;
import com.opengamma.util.money.Currency;
/**
* Convert an OG-Financial Security to its OG-Analytics Derivative form as seen from now
*/
public class FixedIncomeConverterDataProvider {
/** The logger */
private static final Logger s_logger = LoggerFactory.getLogger(FixedIncomeConverterDataProvider.class);
private final ConventionBundleSource _conventionSource;
private final HistoricalTimeSeriesResolver _timeSeriesResolver;
public FixedIncomeConverterDataProvider(final ConventionBundleSource conventionSource, final HistoricalTimeSeriesResolver timeSeriesResolver) {
ArgumentChecker.notNull(conventionSource, "conventionSource");
ArgumentChecker.notNull(timeSeriesResolver, "timeSeriesResolver");
_conventionSource = conventionSource;
_timeSeriesResolver = timeSeriesResolver;
}
public ConventionBundleSource getConventionBundleSource() {
return _conventionSource;
}
public HistoricalTimeSeriesResolver getHistoricalTimeSeriesResolver() {
return _timeSeriesResolver;
}
/**
* Implementation of the conversion for a given instrument.
*/
protected abstract class Converter<S extends Security, D extends InstrumentDefinition<?>> {
/**
* Returns the time series requirements that will be needed for the {@link #convert} method.
*
* @param security the security, not null
* @return the set of requirements, the empty set if nothing is required, null if the conversion will not be possible (for example a missing timeseries)
*/
public abstract Set<ValueRequirement> getTimeSeriesRequirements(S security);
/**
* Converts the "security" and "definition" form to its "derivative" form.
*
* @param security the security, not null
* @param definition the definition, not null
* @param now the observation time, not null
* @param curveNames the names of the curves, not null
* @param timeSeries the bundle containing timeseries produced to satisfy those returned by {@link #getTimeSeriesRequirements}
* @return the derivative form, not null
* @deprecated Use the method that does not take curve names
*/
@Deprecated
public abstract InstrumentDerivative convert(S security, D definition, ZonedDateTime now, String[] curveNames, HistoricalTimeSeriesBundle timeSeries);
/**
* Converts the "security" and "definition" form to its "derivative" form.
*
* @param security the security, not null
* @param definition the definition, not null
* @param now the observation time, not null
* @param timeSeries the bundle containing timeseries produced to satisfy those returned by {@link #getTimeSeriesRequirements}
* @return the derivative form, not null
*/
public abstract InstrumentDerivative convert(S security, D definition, ZonedDateTime now, HistoricalTimeSeriesBundle timeSeries);
}
@SuppressWarnings("rawtypes")
protected Converter getConverter(final Security security, final InstrumentDefinition<?> definition) {
if (definition == null) {
throw new OpenGammaRuntimeException("Definition to convert was null for security " + security);
}
if (security instanceof BondFutureSecurity) {
return _bondFutureSecurity;
}
if (security instanceof FRASecurity) {
return _fraSecurity;
}
if (security instanceof CapFloorSecurity) {
if (((CapFloorSecurity) security).isIbor()) {
return _capFloorIborSecurity;
}
return _capFloorCMSSecurity;
}
if (security instanceof InterestRateFutureSecurity) {
if (definition instanceof InterestRateFutureTransactionDefinition) {
return _irFutureTrade;
}
return _irFutureSecurity;
}
if (security instanceof FederalFundsFutureSecurity) {
if (definition instanceof FederalFundsFutureTransactionDefinition) {
return _fedFundsFutureTrade;
}
return _fedFundsFutureSecurity;
}
if (security instanceof IRFutureOptionSecurity) {
if (definition instanceof InterestRateFutureOptionMarginTransactionDefinition) {
return _irFutureOptionSecurity;
}
}
if (security instanceof SwapSecurity) {
if (definition instanceof SwapFixedInflationYearOnYearDefinition) {
return _yearOnYearInflationSwapSecurity;
}
if (definition instanceof SwapFixedInflationZeroCouponDefinition) {
return _zeroCouponInflationSwapSecurity;
}
if (definition instanceof SwapFixedONSimplifiedDefinition) {
return _default;
}
return _swapSecurity;
}
if (security instanceof InterestRateSwapSecurity) {
return _irsSecurity;
}
if (security instanceof CapFloorCMSSpreadSecurity) {
return _capFloorCMSSpreadSecurity;
}
if (security instanceof SwaptionSecurity) {
return _swaptionSecurity;
}
return _default;
}
@SuppressWarnings("unchecked")
public Set<ValueRequirement> getConversionTimeSeriesRequirements(final Security security, final InstrumentDefinition<?> definition) {
return getConverter(security, definition).getTimeSeriesRequirements(security);
}
/**
* @param security The security, not null
* @param definition The definition, not null
* @param now The valuation time, not null
* @param curveNames The curve names, not null
* @param timeSeries The fixing time series, not null
* @return An instrument derivative
* @deprecated Use the version that does not take yield curve names
*/
@SuppressWarnings("unchecked")
@Deprecated
public InstrumentDerivative convert(final Security security, final InstrumentDefinition<?> definition, final ZonedDateTime now, final String[] curveNames,
final HistoricalTimeSeriesBundle timeSeries) {
return getConverter(security, definition).convert(security, definition, now, curveNames, timeSeries);
}
/**
* @param security The security, not null
* @param definition The definition, not null
* @param now The valuation time, not null
* @param timeSeries The fixing time series, not null
* @return An instrument derivative
*/
@SuppressWarnings("unchecked")
public InstrumentDerivative convert(final Security security, final InstrumentDefinition<?> definition, final ZonedDateTime now, final HistoricalTimeSeriesBundle timeSeries) {
return getConverter(security, definition).convert(security, definition, now, timeSeries);
}
protected ConventionBundleSource getConventionSource() {
return _conventionSource;
}
protected HistoricalTimeSeriesResolver getTimeSeriesResolver() {
return _timeSeriesResolver;
}
private final Converter<SwaptionSecurity, InstrumentDefinition<?>> _swaptionSecurity = new Converter<SwaptionSecurity, InstrumentDefinition<?>>() {
@Override
public Set<ValueRequirement> getTimeSeriesRequirements(final SwaptionSecurity security) {
if (security.getCurrency().equals(Currency.BRL)) {
final ConventionBundle brlSwapConvention = _conventionSource.getConventionBundle(simpleNameSecurityId("BRL_DI_SWAP"));
final ExternalId indexId = brlSwapConvention.getSwapFloatingLegInitialRate();
final ConventionBundle indexConvention = getConventionSource().getConventionBundle(indexId);
if (indexConvention == null) {
throw new OpenGammaRuntimeException("No conventions found for floating reference rate " + indexId);
}
final ExternalIdBundle indexIdBundle = indexConvention.getIdentifiers();
final HistoricalTimeSeriesResolutionResult timeSeries = getTimeSeriesResolver().resolve(indexIdBundle, null, null, null, MarketDataRequirementNames.MARKET_VALUE, null);
if (timeSeries == null) {
return null;
}
return Collections.singleton(HistoricalTimeSeriesFunctionUtils.createHTSRequirement(timeSeries, MarketDataRequirementNames.MARKET_VALUE,
DateConstraint.VALUATION_TIME.minus(Period.ofDays(360)).previousWeekDay(), true, DateConstraint.VALUATION_TIME, false));
}
return Collections.emptySet();
}
@Override
public InstrumentDerivative convert(final SwaptionSecurity security, final InstrumentDefinition<?> definition, final ZonedDateTime now, final String[] curveNames,
final HistoricalTimeSeriesBundle timeSeries) {
if (security.getCurrency().equals(Currency.BRL)) {
@SuppressWarnings("unchecked")
final InstrumentDefinitionWithData<?, ZonedDateTimeDoubleTimeSeries> brlDefinition = (InstrumentDefinitionWithData<?, ZonedDateTimeDoubleTimeSeries>) definition;
final ConventionBundle brlSwapConvention = _conventionSource.getConventionBundle(simpleNameSecurityId("BRL_DI_SWAP"));
final ExternalId indexId = brlSwapConvention.getSwapFloatingLegInitialRate();
final ConventionBundle indexConvention = getConventionSource().getConventionBundle(indexId);
if (indexConvention == null) {
throw new OpenGammaRuntimeException("No conventions found for floating reference rate " + indexId);
}
final ExternalIdBundle indexIdBundle = indexConvention.getIdentifiers();
final HistoricalTimeSeries ts = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, indexIdBundle);
if (ts == null) {
throw new OpenGammaRuntimeException("Could not get price time series for " + indexIdBundle);
}
LocalDateDoubleTimeSeries localDateTS = ts.getTimeSeries();
//TODO this normalization should not be done here
localDateTS = localDateTS.divide(100);
final ZonedDateTimeDoubleTimeSeries indexTS = convertTimeSeries(now.getZone(), localDateTS);
// TODO: remove the zone
return brlDefinition.toDerivative(now, indexTS, curveNames);
}
return definition.toDerivative(now, curveNames);
}
@Override
public InstrumentDerivative convert(final SwaptionSecurity security, final InstrumentDefinition<?> definition, final ZonedDateTime now, final HistoricalTimeSeriesBundle timeSeries) {
if (security.getCurrency().equals(Currency.BRL)) {
@SuppressWarnings("unchecked")
final InstrumentDefinitionWithData<?, ZonedDateTimeDoubleTimeSeries> brlDefinition = (InstrumentDefinitionWithData<?, ZonedDateTimeDoubleTimeSeries>) definition;
final ConventionBundle brlSwapConvention = _conventionSource.getConventionBundle(simpleNameSecurityId("BRL_DI_SWAP"));
final ExternalId indexId = brlSwapConvention.getSwapFloatingLegInitialRate();
final ConventionBundle indexConvention = getConventionSource().getConventionBundle(indexId);
if (indexConvention == null) {
throw new OpenGammaRuntimeException("No conventions found for floating reference rate " + indexId);
}
final ExternalIdBundle indexIdBundle = indexConvention.getIdentifiers();
final HistoricalTimeSeries ts = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, indexIdBundle);
if (ts == null) {
throw new OpenGammaRuntimeException("Could not get price time series for " + indexIdBundle);
}
LocalDateDoubleTimeSeries localDateTS = ts.getTimeSeries();
//TODO this normalization should not be done here
localDateTS = localDateTS.divide(100);
final ZonedDateTimeDoubleTimeSeries indexTS = convertTimeSeries(now.getZone(), localDateTS);
// TODO: remove the zone
return brlDefinition.toDerivative(now, indexTS);
}
return definition.toDerivative(now);
}
};
private final Converter<BondFutureSecurity, BondFutureDefinition> _bondFutureSecurity = new Converter<BondFutureSecurity, BondFutureDefinition>() {
@Override
public Set<ValueRequirement> getTimeSeriesRequirements(final BondFutureSecurity security) {
return Collections.emptySet();
}
@Override
public InstrumentDerivative convert(final BondFutureSecurity security, final BondFutureDefinition definition, final ZonedDateTime now, final String[] curveNames,
final HistoricalTimeSeriesBundle timeSeries) {
// TODO - CASE - Future refactor - See notes in convert(InterestRateFutureSecurity)
// Get the time-dependent reference data required to price the Analytics Derivative
final Double referencePrice = 0.0;
// Construct the derivative as seen from now
return definition.toDerivative(now, referencePrice, curveNames);
}
@Override
public InstrumentDerivative convert(final BondFutureSecurity security, final BondFutureDefinition definition, final ZonedDateTime now,
final HistoricalTimeSeriesBundle timeSeries) {
// TODO - CASE - Future refactor - See notes in convert(InterestRateFutureSecurity)
// Get the time-dependent reference data required to price the Analytics Derivative
final Double referencePrice = 0.0;
// Construct the derivative as seen from now
return definition.toDerivative(now, referencePrice);
}
};
private final Converter<FRASecurity, ForwardRateAgreementDefinition> _fraSecurity = new Converter<FRASecurity, ForwardRateAgreementDefinition>() {
@Override
public Set<ValueRequirement> getTimeSeriesRequirements(final FRASecurity security) {
final ExternalId indexId = security.getUnderlyingId();
final ConventionBundle indexConvention = getConventionSource().getConventionBundle(indexId);
if (indexConvention == null) {
throw new OpenGammaRuntimeException("No conventions found for floating reference rate " + indexId);
}
final ExternalIdBundle indexIdBundle = indexConvention.getIdentifiers();
final HistoricalTimeSeriesResolutionResult timeSeries = getTimeSeriesResolver().resolve(indexIdBundle, null, null, null, MarketDataRequirementNames.MARKET_VALUE, null);
if (timeSeries == null) {
return null;
}
return Collections.singleton(HistoricalTimeSeriesFunctionUtils.createHTSRequirement(timeSeries, MarketDataRequirementNames.MARKET_VALUE,
DateConstraint.VALUATION_TIME.minus(Period.ofDays(7)).previousWeekDay(), true, DateConstraint.VALUATION_TIME, false));
}
@SuppressWarnings("synthetic-access")
@Override
public InstrumentDerivative convert(final FRASecurity security, final ForwardRateAgreementDefinition definition, final ZonedDateTime now, final String[] curveNames,
final HistoricalTimeSeriesBundle timeSeries) {
final ExternalId indexId = security.getUnderlyingId();
final ConventionBundle indexConvention = _conventionSource.getConventionBundle(indexId);
if (indexConvention == null) {
throw new OpenGammaRuntimeException("No conventions found for floating reference rate " + indexId);
}
final ExternalIdBundle indexIdBundle = indexConvention.getIdentifiers();
final HistoricalTimeSeries ts = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, indexIdBundle);
if (ts == null) {
throw new OpenGammaRuntimeException("Could not get price time series for " + indexIdBundle);
}
LocalDateDoubleTimeSeries localDateTS = ts.getTimeSeries();
//TODO this normalization should not be done here
localDateTS = localDateTS.divide(100);
final ZonedDateTimeDoubleTimeSeries indexTS = convertTimeSeries(now.getZone(), localDateTS);
// TODO: remove the zone
return definition.toDerivative(now, indexTS, curveNames);
}
@SuppressWarnings("synthetic-access")
@Override
public InstrumentDerivative convert(final FRASecurity security, final ForwardRateAgreementDefinition definition, final ZonedDateTime now,
final HistoricalTimeSeriesBundle timeSeries) {
final ExternalId indexId = security.getUnderlyingId();
final ConventionBundle indexConvention = _conventionSource.getConventionBundle(indexId);
if (indexConvention == null) {
throw new OpenGammaRuntimeException("No conventions found for floating reference rate " + indexId);
}
final ExternalIdBundle indexIdBundle = indexConvention.getIdentifiers();
final HistoricalTimeSeries ts = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, indexIdBundle);
if (ts == null) {
throw new OpenGammaRuntimeException("Could not get price time series for " + indexIdBundle);
}
LocalDateDoubleTimeSeries localDateTS = ts.getTimeSeries();
//TODO this normalization should not be done here
localDateTS = localDateTS.divide(100);
final ZonedDateTimeDoubleTimeSeries indexTS = convertTimeSeries(now.getZone(), localDateTS);
// TODO: remove the zone
return definition.toDerivative(now, indexTS);
}
};
private final Converter<CapFloorSecurity, AnnuityCapFloorIborDefinition> _capFloorIborSecurity = new Converter<CapFloorSecurity, AnnuityCapFloorIborDefinition>() {
@Override
public Set<ValueRequirement> getTimeSeriesRequirements(final CapFloorSecurity security) {
final HistoricalTimeSeriesResolutionResult timeSeries = getTimeSeriesResolver().resolve(security.getUnderlyingId().toBundle(), null, null, null, MarketDataRequirementNames.MARKET_VALUE, null);
if (timeSeries == null) {
return null;
}
return Collections.singleton(HistoricalTimeSeriesFunctionUtils.createHTSRequirement(timeSeries, MarketDataRequirementNames.MARKET_VALUE,
DateConstraint.VALUATION_TIME.minus(Period.ofDays(7)).previousWeekDay(), true, DateConstraint.VALUATION_TIME, false));
}
@Override
public InstrumentDerivative convert(final CapFloorSecurity security, final AnnuityCapFloorIborDefinition definition, final ZonedDateTime now, final String[] curveNames,
final HistoricalTimeSeriesBundle timeSeries) {
final ExternalId id = security.getUnderlyingId();
final HistoricalTimeSeries ts = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, security.getUnderlyingId());
if (ts == null) {
throw new OpenGammaRuntimeException("Could not get price time series for " + id);
}
LocalDateDoubleTimeSeries localDateTS = ts.getTimeSeries();
//TODO this normalization should not be done here
localDateTS = localDateTS.divide(100);
@SuppressWarnings("synthetic-access")
final ZonedDateTimeDoubleTimeSeries indexTS = convertTimeSeries(now.getZone(), localDateTS);
return definition.toDerivative(now, indexTS, curveNames);
}
@Override
public InstrumentDerivative convert(final CapFloorSecurity security, final AnnuityCapFloorIborDefinition definition, final ZonedDateTime now,
final HistoricalTimeSeriesBundle timeSeries) {
final ExternalId id = security.getUnderlyingId();
final HistoricalTimeSeries ts = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, security.getUnderlyingId());
if (ts == null) {
throw new OpenGammaRuntimeException("Could not get price time series for " + id);
}
LocalDateDoubleTimeSeries localDateTS = ts.getTimeSeries();
//TODO this normalization should not be done here
localDateTS = localDateTS.divide(100);
@SuppressWarnings("synthetic-access")
final ZonedDateTimeDoubleTimeSeries indexTS = convertTimeSeries(now.getZone(), localDateTS);
return definition.toDerivative(now, indexTS);
}
};
private final Converter<CapFloorSecurity, AnnuityCapFloorCMSDefinition> _capFloorCMSSecurity = new Converter<CapFloorSecurity, AnnuityCapFloorCMSDefinition>() {
@SuppressWarnings("synthetic-access")
@Override
public Set<ValueRequirement> getTimeSeriesRequirements(final CapFloorSecurity security) {
final ExternalId id = security.getUnderlyingId();
final ZonedDateTime capStartDate = security.getStartDate();
final LocalDate startDate = capStartDate.toLocalDate().minusDays(7); // To catch first fixing. SwapSecurity does not have this date.
final ValueRequirement requirement = getIndexTimeSeriesRequirement(getIndexIdBundle(id), startDate);
if (requirement == null) {
return null;
}
return Collections.singleton(requirement);
}
@SuppressWarnings("synthetic-access")
@Override
public InstrumentDerivative convert(final CapFloorSecurity security, final AnnuityCapFloorCMSDefinition definition, final ZonedDateTime now, final String[] curveNames,
final HistoricalTimeSeriesBundle timeSeries) {
final ExternalId id = security.getUnderlyingId();
final ZonedDateTimeDoubleTimeSeries indexTS = getIndexTimeSeries(getIndexIdBundle(id), now.getZone(), timeSeries);
return definition.toDerivative(now, indexTS, curveNames);
}
@SuppressWarnings("synthetic-access")
@Override
public InstrumentDerivative convert(final CapFloorSecurity security, final AnnuityCapFloorCMSDefinition definition, final ZonedDateTime now,
final HistoricalTimeSeriesBundle timeSeries) {
final ExternalId id = security.getUnderlyingId();
final ZonedDateTimeDoubleTimeSeries indexTS = getIndexTimeSeries(getIndexIdBundle(id), now.getZone(), timeSeries);
return definition.toDerivative(now, indexTS);
}
};
private final Converter<InterestRateFutureSecurity, InterestRateFutureTransactionDefinition> _irFutureTrade = new Converter<InterestRateFutureSecurity, InterestRateFutureTransactionDefinition>() {
@Override
public Set<ValueRequirement> getTimeSeriesRequirements(final InterestRateFutureSecurity security) {
final HistoricalTimeSeriesResolutionResult timeSeries = getTimeSeriesResolver().resolve(security.getExternalIdBundle(), null, null, null, MarketDataRequirementNames.MARKET_VALUE, null);
if (timeSeries == null) {
return null;
}
return Collections.singleton(HistoricalTimeSeriesFunctionUtils.createHTSRequirement(timeSeries, MarketDataRequirementNames.MARKET_VALUE,
DateConstraint.VALUATION_TIME.minus(Period.ofMonths(1)).previousWeekDay(), true, DateConstraint.VALUATION_TIME, true));
}
@Override
public InstrumentDerivative convert(final InterestRateFutureSecurity security, final InterestRateFutureTransactionDefinition definition, final ZonedDateTime now, final String[] curveNames,
final HistoricalTimeSeriesBundle timeSeries) {
final HistoricalTimeSeries ts = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, security.getExternalIdBundle());
if (ts == null) {
throw new OpenGammaRuntimeException("Could not get price time series for " + security);
}
final int length = ts.getTimeSeries().size();
if (length == 0) {
throw new OpenGammaRuntimeException("Price time series for " + security.getExternalIdBundle() + " was empty");
}
final double lastMarginPrice = ts.getTimeSeries().getLatestValue();
if (curveNames.length == 1) {
final String[] singleCurve = new String[] {curveNames[0], curveNames[0] };
return definition.toDerivative(now, lastMarginPrice, singleCurve);
}
return definition.toDerivative(now, lastMarginPrice, curveNames);
}
@Override
public InstrumentDerivative convert(final InterestRateFutureSecurity security, final InterestRateFutureTransactionDefinition definition, final ZonedDateTime now,
final HistoricalTimeSeriesBundle timeSeries) {
final HistoricalTimeSeries ts = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, security.getExternalIdBundle());
if (ts == null) {
throw new OpenGammaRuntimeException("Could not get price time series for " + security);
}
final int length = ts.getTimeSeries().size();
if (length == 0) {
throw new OpenGammaRuntimeException("Price time series for " + security.getExternalIdBundle() + " was empty");
}
final double lastMarginPrice = ts.getTimeSeries().getLatestValue();
return definition.toDerivative(now, lastMarginPrice);
}
};
private final Converter<InterestRateFutureSecurity, InterestRateFutureSecurityDefinition> _irFutureSecurity = new Converter<InterestRateFutureSecurity, InterestRateFutureSecurityDefinition>() {
@Override
public Set<ValueRequirement> getTimeSeriesRequirements(final InterestRateFutureSecurity security) {
final HistoricalTimeSeriesResolutionResult timeSeries = getTimeSeriesResolver().resolve(security.getExternalIdBundle(), null, null, null, MarketDataRequirementNames.MARKET_VALUE, null);
if (timeSeries == null) {
return null;
}
return Collections.singleton(HistoricalTimeSeriesFunctionUtils.createHTSRequirement(timeSeries, MarketDataRequirementNames.MARKET_VALUE,
DateConstraint.VALUATION_TIME.minus(Period.ofMonths(1)).previousWeekDay(), true, DateConstraint.VALUATION_TIME, true));
}
@Override
public InstrumentDerivative convert(final InterestRateFutureSecurity security, final InterestRateFutureSecurityDefinition definition, final ZonedDateTime now, final String[] curveNames,
final HistoricalTimeSeriesBundle timeSeries) {
final HistoricalTimeSeries ts = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, security.getExternalIdBundle());
if (ts == null) {
throw new OpenGammaRuntimeException("Could not get price time series for " + security);
}
final int length = ts.getTimeSeries().size();
if (length == 0) {
throw new OpenGammaRuntimeException("Price time series for " + security.getExternalIdBundle() + " was empty");
}
final double lastMarginPrice = ts.getTimeSeries().getLatestValue();
if (curveNames.length == 1) {
final String[] singleCurve = new String[] {curveNames[0], curveNames[0] };
return definition.toDerivative(now, lastMarginPrice, singleCurve);
}
return definition.toDerivative(now, lastMarginPrice, curveNames);
}
@Override
public InstrumentDerivative convert(final InterestRateFutureSecurity security, final InterestRateFutureSecurityDefinition definition, final ZonedDateTime now,
final HistoricalTimeSeriesBundle timeSeries) {
final HistoricalTimeSeries ts = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, security.getExternalIdBundle());
if (ts == null) {
throw new OpenGammaRuntimeException("Could not get price time series for " + security);
}
final int length = ts.getTimeSeries().size();
if (length == 0) {
throw new OpenGammaRuntimeException("Price time series for " + security.getExternalIdBundle() + " was empty");
}
final double lastMarginPrice = ts.getTimeSeries().getLatestValue();
return definition.toDerivative(now, lastMarginPrice);
}
};
private final Converter<FederalFundsFutureSecurity, FederalFundsFutureSecurityDefinition> _fedFundsFutureSecurity =
new Converter<FederalFundsFutureSecurity, FederalFundsFutureSecurityDefinition>() {
@Override
public Set<ValueRequirement> getTimeSeriesRequirements(final FederalFundsFutureSecurity security) {
final HistoricalTimeSeriesResolutionResult futureTS = getTimeSeriesResolver().resolve(security.getExternalIdBundle(), null, null, null, MarketDataRequirementNames.MARKET_VALUE, null);
if (futureTS == null) {
return null;
}
final HistoricalTimeSeriesResolutionResult underlyingTS = getTimeSeriesResolver().resolve(security.getUnderlyingId().toBundle(), null, null, null,
MarketDataRequirementNames.MARKET_VALUE, null);
if (underlyingTS == null) {
return null;
}
final Set<ValueRequirement> requirements = new HashSet<>();
requirements.add(HistoricalTimeSeriesFunctionUtils.createHTSRequirement(futureTS, MarketDataRequirementNames.MARKET_VALUE,
DateConstraint.VALUATION_TIME.minus(Period.ofMonths(1)).previousWeekDay(), true, DateConstraint.VALUATION_TIME, false));
requirements.add(HistoricalTimeSeriesFunctionUtils.createHTSRequirement(underlyingTS, MarketDataRequirementNames.MARKET_VALUE,
DateConstraint.VALUATION_TIME.minus(Period.ofMonths(4)).previousWeekDay(), true, DateConstraint.VALUATION_TIME, false));
return requirements;
}
@Override
public InstrumentDerivative convert(final FederalFundsFutureSecurity security, final FederalFundsFutureSecurityDefinition definition, final ZonedDateTime now, final String[] curveNames,
final HistoricalTimeSeriesBundle timeSeries) {
return convert(security, definition, now, timeSeries);
}
@Override
public InstrumentDerivative convert(final FederalFundsFutureSecurity security, final FederalFundsFutureSecurityDefinition definition, final ZonedDateTime now,
final HistoricalTimeSeriesBundle timeSeries) {
final HistoricalTimeSeries underlyingTS = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, security.getUnderlyingId().toBundle());
if (underlyingTS == null) {
throw new OpenGammaRuntimeException("Could not get underlying time series for " + security.getUnderlyingId());
}
if (underlyingTS.getTimeSeries().size() == 0) {
throw new OpenGammaRuntimeException("Time series for " + security.getUnderlyingId().toBundle() + " was empty");
}
return definition.toDerivative(now, convertTimeSeries(ZoneId.of("UTC"), underlyingTS.getTimeSeries()));
}
};
private final Converter<FederalFundsFutureSecurity, FederalFundsFutureTransactionDefinition> _fedFundsFutureTrade =
new Converter<FederalFundsFutureSecurity, FederalFundsFutureTransactionDefinition>() {
@Override
public Set<ValueRequirement> getTimeSeriesRequirements(final FederalFundsFutureSecurity security) {
final HistoricalTimeSeriesResolutionResult futureTS = getTimeSeriesResolver().resolve(security.getExternalIdBundle(), null, null, null, MarketDataRequirementNames.MARKET_VALUE, null);
if (futureTS == null) {
return null;
}
final HistoricalTimeSeriesResolutionResult underlyingTS = getTimeSeriesResolver().resolve(security.getUnderlyingId().toBundle(), null, null, null,
MarketDataRequirementNames.MARKET_VALUE, null);
if (underlyingTS == null) {
return null;
}
final Set<ValueRequirement> requirements = new HashSet<>();
requirements.add(HistoricalTimeSeriesFunctionUtils.createHTSRequirement(futureTS, MarketDataRequirementNames.MARKET_VALUE,
DateConstraint.VALUATION_TIME.minus(Period.ofMonths(1)).previousWeekDay(), true, DateConstraint.VALUATION_TIME, false));
requirements.add(HistoricalTimeSeriesFunctionUtils.createHTSRequirement(underlyingTS, MarketDataRequirementNames.MARKET_VALUE,
DateConstraint.VALUATION_TIME.minus(Period.ofMonths(4)).previousWeekDay(), true, DateConstraint.VALUATION_TIME, false));
return requirements;
}
@Override
public InstrumentDerivative convert(final FederalFundsFutureSecurity security, final FederalFundsFutureTransactionDefinition definition, final ZonedDateTime now, final String[] curveNames,
final HistoricalTimeSeriesBundle timeSeries) {
return convert(security, definition, now, timeSeries);
}
@SuppressWarnings("unchecked")
@Override
public InstrumentDerivative convert(final FederalFundsFutureSecurity security, final FederalFundsFutureTransactionDefinition definition, final ZonedDateTime now,
final HistoricalTimeSeriesBundle timeSeries) {
final HistoricalTimeSeries futureTS = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, security.getExternalIdBundle());
if (futureTS == null) {
throw new OpenGammaRuntimeException("Could not get price time series for " + security);
}
if (futureTS.getTimeSeries().size() == 0) {
throw new OpenGammaRuntimeException("Price time series for " + security.getExternalIdBundle() + " was empty");
}
final HistoricalTimeSeries underlyingTS = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, security.getUnderlyingId().toBundle());
if (underlyingTS == null) {
throw new OpenGammaRuntimeException("Could not get underlying time series for " + security.getUnderlyingId());
}
if (underlyingTS.getTimeSeries().size() == 0) {
throw new OpenGammaRuntimeException("Time series for " + security.getUnderlyingId().toBundle() + " was empty");
}
return definition.toDerivative(now, new DoubleTimeSeries[] {
convertTimeSeries(ZoneId.of("UTC"), underlyingTS.getTimeSeries()),
convertTimeSeries(ZoneId.of("UTC"), futureTS.getTimeSeries()) });
}
};
private final Converter<IRFutureOptionSecurity, InterestRateFutureOptionMarginTransactionDefinition> _irFutureOptionSecurity = new Converter<IRFutureOptionSecurity, InterestRateFutureOptionMarginTransactionDefinition>() { // CSIGNORE
@Override
public Set<ValueRequirement> getTimeSeriesRequirements(final IRFutureOptionSecurity security) {
final HistoricalTimeSeriesResolutionResult timeSeries = getTimeSeriesResolver().resolve(security.getExternalIdBundle(), null, null, null, MarketDataRequirementNames.MARKET_VALUE, null);
if (timeSeries == null) {
return null;
}
return Collections.singleton(HistoricalTimeSeriesFunctionUtils.createHTSRequirement(timeSeries, MarketDataRequirementNames.MARKET_VALUE,
DateConstraint.VALUATION_TIME.minus(Period.ofMonths(1)).previousWeekDay(), true, DateConstraint.VALUATION_TIME, false));
}
@Override
public InstrumentDerivative convert(final IRFutureOptionSecurity security, final InterestRateFutureOptionMarginTransactionDefinition definition, final ZonedDateTime now,
final String[] curveNames, final HistoricalTimeSeriesBundle timeSeries) {
final HistoricalTimeSeries ts = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, security.getExternalIdBundle());
Double lastMarginPrice;
if (now.toLocalDate().equals(definition.getTradeDate().toLocalDate())) {
lastMarginPrice = definition.getTradePrice();
} else {
if (ts == null) {
throw new OpenGammaRuntimeException("Could not get price time series for " + security);
}
final int length = ts.getTimeSeries().size();
if (length == 0) {
throw new OpenGammaRuntimeException("Price time series for " + security.getExternalIdBundle() + " was empty");
}
lastMarginPrice = ts.getTimeSeries().getLatestValue();
}
return definition.toDerivative(now, lastMarginPrice, curveNames);
}
@Override
public InstrumentDerivative convert(final IRFutureOptionSecurity security, final InterestRateFutureOptionMarginTransactionDefinition definition, final ZonedDateTime now,
final HistoricalTimeSeriesBundle timeSeries) {
final HistoricalTimeSeries ts = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, security.getExternalIdBundle());
Double lastMarginPrice;
if (now.toLocalDate().equals(definition.getTradeDate().toLocalDate())) {
lastMarginPrice = definition.getTradePrice();
} else {
if (ts == null) {
throw new OpenGammaRuntimeException("Could not get price time series for " + security);
}
final int length = ts.getTimeSeries().size();
if (length == 0) {
throw new OpenGammaRuntimeException("Price time series for " + security.getExternalIdBundle() + " was empty");
}
lastMarginPrice = ts.getTimeSeries().getLatestValue();
}
return definition.toDerivative(now, lastMarginPrice);
}
};
private final Converter<SwapSecurity, SwapDefinition> _swapSecurity = new Converter<SwapSecurity, SwapDefinition>() {
@SuppressWarnings("synthetic-access")
@Override
public Set<ValueRequirement> getTimeSeriesRequirements(final SwapSecurity security) {
Validate.notNull(security, "security");
final SwapLeg payLeg = security.getPayLeg();
final SwapLeg receiveLeg = security.getReceiveLeg();
final ZonedDateTime swapStartDate = security.getEffectiveDate();
final ZonedDateTime swapStartLocalDate = swapStartDate.toLocalDate().atStartOfDay(ZoneOffset.UTC);
final ValueRequirement payLegTS = getIndexTimeSeriesRequirement(payLeg, swapStartLocalDate);
final ValueRequirement receiveLegTS = getIndexTimeSeriesRequirement(receiveLeg, swapStartLocalDate);
final Set<ValueRequirement> requirements = new HashSet<>();
if (payLegTS != null) {
requirements.add(payLegTS);
}
if (receiveLegTS != null) {
requirements.add(receiveLegTS);
}
return requirements;
}
@Override
@SuppressWarnings({"synthetic-access" })
public InstrumentDerivative convert(final SwapSecurity security, final SwapDefinition definition, final ZonedDateTime now, final String[] curveNames, final HistoricalTimeSeriesBundle timeSeries) {
Validate.notNull(security, "security");
if (timeSeries == null) {
return definition.toDerivative(now, curveNames);
}
final SwapLeg payLeg = security.getPayLeg();
final SwapLeg receiveLeg = security.getReceiveLeg();
final ZonedDateTime fixingSeriesStartDate = security.getEffectiveDate().isBefore(now) ? security.getEffectiveDate() : now;
final ZonedDateTime fixingSeriesStartLocalDate = fixingSeriesStartDate.toLocalDate().atStartOfDay(ZoneOffset.UTC);
final ZonedDateTimeDoubleTimeSeries payLegTS = getIndexTimeSeries(payLeg, fixingSeriesStartLocalDate, now, timeSeries);
final ZonedDateTimeDoubleTimeSeries receiveLegTS = getIndexTimeSeries(receiveLeg, fixingSeriesStartLocalDate, now, timeSeries);
if (payLegTS != null) {
if (receiveLegTS != null) {
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {payLegTS, receiveLegTS }, curveNames);
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((FloatingInterestRateLeg) payLeg).getFloatingReferenceRateId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id, e);
}
}
if ((InterestRateInstrumentType.getInstrumentTypeFromSecurity(security) == InterestRateInstrumentType.SWAP_FIXED_CMS)
|| (InterestRateInstrumentType.getInstrumentTypeFromSecurity(security) == InterestRateInstrumentType.SWAP_CROSS_CURRENCY)) {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {payLegTS, payLegTS }, curveNames);
}
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {payLegTS }, curveNames);
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((FloatingInterestRateLeg) payLeg).getFloatingReferenceRateId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id, e);
}
}
if (receiveLegTS != null) {
if ((InterestRateInstrumentType.getInstrumentTypeFromSecurity(security) == InterestRateInstrumentType.SWAP_FIXED_CMS)
|| (InterestRateInstrumentType.getInstrumentTypeFromSecurity(security) == InterestRateInstrumentType.SWAP_CROSS_CURRENCY)) {
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {receiveLegTS, receiveLegTS }, curveNames);
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((FloatingInterestRateLeg) payLeg).getFloatingReferenceRateId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id, e);
}
}
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {receiveLegTS }, curveNames);
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((FloatingInterestRateLeg) receiveLeg).getFloatingReferenceRateId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id, e);
}
}
if (InterestRateInstrumentType.getInstrumentTypeFromSecurity(security) == InterestRateInstrumentType.SWAP_CROSS_CURRENCY) {
return definition.toDerivative(now, curveNames); // To deal with Fixed-Fixed cross currency swaps.
}
throw new OpenGammaRuntimeException("Could not get fixing series for either the pay or receive leg");
}
@Override
@SuppressWarnings({"synthetic-access" })
public InstrumentDerivative convert(final SwapSecurity security, final SwapDefinition definition, final ZonedDateTime now, final HistoricalTimeSeriesBundle timeSeries) {
Validate.notNull(security, "security");
if (timeSeries == null) {
return definition.toDerivative(now);
}
final SwapLeg payLeg = security.getPayLeg();
final SwapLeg receiveLeg = security.getReceiveLeg();
final ZonedDateTime fixingSeriesStartDate = security.getEffectiveDate().isBefore(now) ? security.getEffectiveDate() : now;
final ZonedDateTime fixingSeriesStartLocalDate = fixingSeriesStartDate.toLocalDate().atStartOfDay(ZoneOffset.UTC);
final ZonedDateTimeDoubleTimeSeries payLegTS = getIndexTimeSeries(payLeg, fixingSeriesStartLocalDate, now, timeSeries);
final ZonedDateTimeDoubleTimeSeries receiveLegTS = getIndexTimeSeries(receiveLeg, fixingSeriesStartLocalDate, now, timeSeries);
if (payLegTS != null) {
if (receiveLegTS != null) {
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {payLegTS, receiveLegTS });
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((FloatingInterestRateLeg) payLeg).getFloatingReferenceRateId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id, e);
}
}
if ((InterestRateInstrumentType.getInstrumentTypeFromSecurity(security) == InterestRateInstrumentType.SWAP_FIXED_CMS)
|| (InterestRateInstrumentType.getInstrumentTypeFromSecurity(security) == InterestRateInstrumentType.SWAP_CROSS_CURRENCY)) {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {payLegTS, payLegTS });
}
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {payLegTS });
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((FloatingInterestRateLeg) payLeg).getFloatingReferenceRateId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id + "; error was " + e.getMessage());
}
}
if (receiveLegTS != null) {
if ((InterestRateInstrumentType.getInstrumentTypeFromSecurity(security) == InterestRateInstrumentType.SWAP_FIXED_CMS)
|| (InterestRateInstrumentType.getInstrumentTypeFromSecurity(security) == InterestRateInstrumentType.SWAP_CROSS_CURRENCY)) {
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {receiveLegTS, receiveLegTS });
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((FloatingInterestRateLeg) payLeg).getFloatingReferenceRateId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id, e);
}
}
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {receiveLegTS });
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((FloatingInterestRateLeg) receiveLeg).getFloatingReferenceRateId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id, e);
}
}
if (InterestRateInstrumentType.getInstrumentTypeFromSecurity(security) == InterestRateInstrumentType.SWAP_CROSS_CURRENCY) {
return definition.toDerivative(now); // To deal with Fixed-Fixed cross currency swaps.
}
throw new OpenGammaRuntimeException("Could not get fixing series for either the pay or receive leg");
}
};
private final Converter<CapFloorCMSSpreadSecurity, AnnuityCapFloorCMSSpreadDefinition> _capFloorCMSSpreadSecurity = new Converter<CapFloorCMSSpreadSecurity, AnnuityCapFloorCMSSpreadDefinition>() {
@SuppressWarnings("synthetic-access")
@Override
public Set<ValueRequirement> getTimeSeriesRequirements(final CapFloorCMSSpreadSecurity security) {
final ExternalId longId = security.getLongId();
final ExternalId shortId = security.getShortId();
final ZonedDateTime capStartDate = security.getStartDate();
final LocalDate startDate = capStartDate.toLocalDate().minusDays(7); // To catch first fixing. SwapSecurity does not have this date.
final ValueRequirement indexLongTS = getIndexTimeSeriesRequirement(getIndexIdBundle(longId), startDate);
if (indexLongTS == null) {
return null;
}
final ValueRequirement indexShortTS = getIndexTimeSeriesRequirement(getIndexIdBundle(shortId), startDate);
if (indexShortTS == null) {
return null;
}
return ImmutableSet.of(indexLongTS, indexShortTS);
}
@SuppressWarnings("synthetic-access")
@Override
public InstrumentDerivative convert(final CapFloorCMSSpreadSecurity security, final AnnuityCapFloorCMSSpreadDefinition definition, final ZonedDateTime now, final String[] curveNames,
final HistoricalTimeSeriesBundle timeSeries) {
final ExternalId longId = security.getLongId();
final ExternalId shortId = security.getShortId();
final ZonedDateTimeDoubleTimeSeries indexLongTS = getIndexTimeSeries(getIndexIdBundle(longId), now.getZone(), timeSeries);
final ZonedDateTimeDoubleTimeSeries indexShortTS = getIndexTimeSeries(getIndexIdBundle(shortId), now.getZone(), timeSeries);
final ZonedDateTimeDoubleTimeSeries indexSpreadTS = indexLongTS.subtract(indexShortTS);
return definition.toDerivative(now, indexSpreadTS, curveNames);
}
@SuppressWarnings("synthetic-access")
@Override
public InstrumentDerivative convert(final CapFloorCMSSpreadSecurity security, final AnnuityCapFloorCMSSpreadDefinition definition, final ZonedDateTime now,
final HistoricalTimeSeriesBundle timeSeries) {
final ExternalId longId = security.getLongId();
final ExternalId shortId = security.getShortId();
final ZonedDateTimeDoubleTimeSeries indexLongTS = getIndexTimeSeries(getIndexIdBundle(longId), now.getZone(), timeSeries);
final ZonedDateTimeDoubleTimeSeries indexShortTS = getIndexTimeSeries(getIndexIdBundle(shortId), now.getZone(), timeSeries);
final ZonedDateTimeDoubleTimeSeries indexSpreadTS = indexLongTS.subtract(indexShortTS);
return definition.toDerivative(now, indexSpreadTS);
}
};
private final Converter<ZeroCouponInflationSwapSecurity, SwapFixedInflationZeroCouponDefinition> _zeroCouponInflationSwapSecurity =
new Converter<ZeroCouponInflationSwapSecurity, SwapFixedInflationZeroCouponDefinition>() {
@Override
public Set<ValueRequirement> getTimeSeriesRequirements(final ZeroCouponInflationSwapSecurity security) {
Validate.notNull(security, "security");
final SwapLeg payLeg = security.getPayLeg();
final SwapLeg receiveLeg = security.getReceiveLeg();
final ZonedDateTime swapStartDate = security.getEffectiveDate();
final ZonedDateTime swapStartLocalDate = swapStartDate.toLocalDate().atStartOfDay(ZoneOffset.UTC);
final ValueRequirement payLegTS = getIndexTimeSeriesRequirement(payLeg, swapStartLocalDate);
final ValueRequirement receiveLegTS = getIndexTimeSeriesRequirement(receiveLeg, swapStartLocalDate);
final Set<ValueRequirement> requirements = new HashSet<>();
if (payLegTS != null) {
requirements.add(payLegTS);
}
if (receiveLegTS != null) {
requirements.add(receiveLegTS);
}
return requirements;
}
@Override
public InstrumentDerivative convert(final ZeroCouponInflationSwapSecurity security, final SwapFixedInflationZeroCouponDefinition definition, final ZonedDateTime now, final String[] curveNames,
final HistoricalTimeSeriesBundle timeSeries) {
Validate.notNull(security, "security");
if (timeSeries == null) {
return definition.toDerivative(now, curveNames);
}
final SwapLeg payLeg = security.getPayLeg();
final SwapLeg receiveLeg = security.getReceiveLeg();
final ZonedDateTime fixingSeriesStartDate = security.getEffectiveDate().isBefore(now) ? security.getEffectiveDate() : now;
final ZonedDateTime fixingSeriesStartLocalDate = fixingSeriesStartDate.toLocalDate().atStartOfDay(ZoneOffset.UTC);
final ZonedDateTimeDoubleTimeSeries payLegTS = getIndexTimeSeries(payLeg, fixingSeriesStartLocalDate, now, timeSeries);
final ZonedDateTimeDoubleTimeSeries receiveLegTS = getIndexTimeSeries(receiveLeg, fixingSeriesStartLocalDate, now, timeSeries);
if (payLegTS != null) {
if (receiveLegTS != null) {
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {payLegTS, receiveLegTS }, curveNames);
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((InflationIndexSwapLeg) payLeg).getIndexId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id, e);
}
}
}
if (receiveLegTS != null) {
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {receiveLegTS }, curveNames);
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((InflationIndexSwapLeg) receiveLeg).getIndexId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id, e);
}
}
throw new OpenGammaRuntimeException("Could not get fixing series for either the pay or receive leg");
}
@Override
public InstrumentDerivative convert(final ZeroCouponInflationSwapSecurity security, final SwapFixedInflationZeroCouponDefinition definition, final ZonedDateTime now, final HistoricalTimeSeriesBundle timeSeries) {
Validate.notNull(security, "security");
if (timeSeries == null) {
return definition.toDerivative(now);
}
final SwapLeg payLeg = security.getPayLeg();
final SwapLeg receiveLeg = security.getReceiveLeg();
final ZonedDateTime fixingSeriesStartDate = security.getEffectiveDate().isBefore(now) ? security.getEffectiveDate() : now;
final ZonedDateTime fixingSeriesStartLocalDate = fixingSeriesStartDate.toLocalDate().atStartOfDay(ZoneOffset.UTC);
final ZonedDateTimeDoubleTimeSeries payLegTS = getIndexTimeSeries(payLeg, fixingSeriesStartLocalDate, now, timeSeries);
final ZonedDateTimeDoubleTimeSeries receiveLegTS = getIndexTimeSeries(receiveLeg, fixingSeriesStartLocalDate, now, timeSeries);
if (payLegTS != null) {
if (receiveLegTS != null) {
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {payLegTS, receiveLegTS });
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((InflationIndexSwapLeg) payLeg).getIndexId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id, e);
}
}
}
if (receiveLegTS != null) {
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {receiveLegTS, receiveLegTS });
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((InflationIndexSwapLeg) receiveLeg).getIndexId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id, e);
}
}
throw new OpenGammaRuntimeException("Could not get fixing series for either the pay or receive leg");
}
};
private final Converter<YearOnYearInflationSwapSecurity, SwapFixedInflationYearOnYearDefinition> _yearOnYearInflationSwapSecurity =
new Converter<YearOnYearInflationSwapSecurity, SwapFixedInflationYearOnYearDefinition>() {
@Override
public Set<ValueRequirement> getTimeSeriesRequirements(final YearOnYearInflationSwapSecurity security) {
Validate.notNull(security, "security");
final SwapLeg payLeg = security.getPayLeg();
final SwapLeg receiveLeg = security.getReceiveLeg();
final ZonedDateTime swapStartDate = security.getEffectiveDate();
final ZonedDateTime swapStartLocalDate = swapStartDate.toLocalDate().atStartOfDay(ZoneOffset.UTC);
final ValueRequirement payLegTS = getIndexTimeSeriesRequirement(payLeg, swapStartLocalDate);
final ValueRequirement receiveLegTS = getIndexTimeSeriesRequirement(receiveLeg, swapStartLocalDate);
final Set<ValueRequirement> requirements = new HashSet<>();
if (payLegTS != null) {
requirements.add(payLegTS);
}
if (receiveLegTS != null) {
requirements.add(receiveLegTS);
}
return requirements;
}
@Override
public InstrumentDerivative convert(final YearOnYearInflationSwapSecurity security, final SwapFixedInflationYearOnYearDefinition definition, final ZonedDateTime now, final String[] curveNames,
final HistoricalTimeSeriesBundle timeSeries) {
Validate.notNull(security, "security");
if (timeSeries == null) {
return definition.toDerivative(now, curveNames);
}
final SwapLeg payLeg = security.getPayLeg();
final SwapLeg receiveLeg = security.getReceiveLeg();
final ZonedDateTime fixingSeriesStartDate = security.getEffectiveDate().isBefore(now) ? security.getEffectiveDate() : now;
final ZonedDateTime fixingSeriesStartLocalDate = fixingSeriesStartDate.toLocalDate().atStartOfDay(ZoneOffset.UTC);
final ZonedDateTimeDoubleTimeSeries payLegTS = getIndexTimeSeries(payLeg, fixingSeriesStartLocalDate, now, timeSeries);
final ZonedDateTimeDoubleTimeSeries receiveLegTS = getIndexTimeSeries(receiveLeg, fixingSeriesStartLocalDate, now, timeSeries);
if (payLegTS != null) {
if (receiveLegTS != null) {
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {payLegTS, receiveLegTS }, curveNames);
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((InflationIndexSwapLeg) payLeg).getIndexId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id, e);
}
}
}
if (receiveLegTS != null) {
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {receiveLegTS }, curveNames);
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((InflationIndexSwapLeg) receiveLeg).getIndexId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id, e);
}
}
throw new OpenGammaRuntimeException("Could not get fixing series for either the pay or receive leg");
}
@Override
public InstrumentDerivative convert(final YearOnYearInflationSwapSecurity security, final SwapFixedInflationYearOnYearDefinition definition, final ZonedDateTime now, final HistoricalTimeSeriesBundle timeSeries) {
Validate.notNull(security, "security");
if (timeSeries == null) {
return definition.toDerivative(now);
}
final SwapLeg payLeg = security.getPayLeg();
final SwapLeg receiveLeg = security.getReceiveLeg();
final ZonedDateTime fixingSeriesStartDate = security.getEffectiveDate().isBefore(now) ? security.getEffectiveDate() : now;
final ZonedDateTime fixingSeriesStartLocalDate = fixingSeriesStartDate.toLocalDate().atStartOfDay(ZoneOffset.UTC);
final ZonedDateTimeDoubleTimeSeries payLegTS = getIndexTimeSeries(payLeg, fixingSeriesStartLocalDate, now, timeSeries);
final ZonedDateTimeDoubleTimeSeries receiveLegTS = getIndexTimeSeries(receiveLeg, fixingSeriesStartLocalDate, now, timeSeries);
if (payLegTS != null) {
if (receiveLegTS != null) {
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {payLegTS, receiveLegTS });
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((InflationIndexSwapLeg) payLeg).getIndexId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id, e);
}
}
}
if (receiveLegTS != null) {
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {receiveLegTS, receiveLegTS });
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((InflationIndexSwapLeg) receiveLeg).getIndexId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id, e);
}
}
throw new OpenGammaRuntimeException("Could not get fixing series for either the pay or receive leg");
}
};
private final Converter<Security, InstrumentDefinition<?>> _default = new Converter<Security, InstrumentDefinition<?>>() {
@Override
public Set<ValueRequirement> getTimeSeriesRequirements(final Security security) {
return Collections.emptySet();
}
@Override
public InstrumentDerivative convert(final Security security, final InstrumentDefinition<?> definition, final ZonedDateTime now, final String[] curveNames,
final HistoricalTimeSeriesBundle timeSeries) {
if (curveNames.length == 1) {
final String[] singleCurve = new String[] {curveNames[0], curveNames[0] };
return definition.toDerivative(now, singleCurve);
}
return definition.toDerivative(now, curveNames);
}
@Override
public InstrumentDerivative convert(final Security security, final InstrumentDefinition<?> definition, final ZonedDateTime now,
final HistoricalTimeSeriesBundle timeSeries) {
return definition.toDerivative(now);
}
};
private ValueRequirement getIndexTimeSeriesRequirement(final SwapLeg leg, final ZonedDateTime swapEffectiveDate) {
if (leg instanceof FloatingInterestRateLeg) {
final FloatingInterestRateLeg floatingLeg = (FloatingInterestRateLeg) leg;
final ExternalIdBundle id = getIndexIdForSwap(floatingLeg);
final LocalDate startDate = swapEffectiveDate.toLocalDate().minusDays(360);
// Implementation note: To catch first fixing. SwapSecurity does not have this date.
final HistoricalTimeSeriesResolutionResult ts = getTimeSeriesResolver().resolve(id, null, null, null, MarketDataRequirementNames.MARKET_VALUE, null);
if (ts == null) {
return null;
}
return HistoricalTimeSeriesFunctionUtils.createHTSRequirement(ts, MarketDataRequirementNames.MARKET_VALUE,
DateConstraint.of(startDate), true, DateConstraint.VALUATION_TIME, true);
} else if (leg instanceof InflationIndexSwapLeg) {
final InflationIndexSwapLeg inflationIndexLeg = (InflationIndexSwapLeg) leg;
final ExternalIdBundle id = getIndexIdForInflationSwap(inflationIndexLeg);
final LocalDate startDate = swapEffectiveDate.toLocalDate().minusDays(360);
// Implementation note: To catch first fixing. SwapSecurity does not have this date.
final HistoricalTimeSeriesResolutionResult ts = getTimeSeriesResolver().resolve(id, null, null, null, MarketDataRequirementNames.MARKET_VALUE, null);
if (ts == null) {
return null;
}
return HistoricalTimeSeriesFunctionUtils.createHTSRequirement(ts, MarketDataRequirementNames.MARKET_VALUE,
DateConstraint.of(startDate), true, DateConstraint.VALUATION_TIME, true);
}
return null;
}
private ValueRequirement getIndexTimeSeriesRequirement(final InterestRateSwapLeg leg, final ZonedDateTime swapEffectiveDate) {
if (leg instanceof FloatingInterestRateSwapLeg) {
final FloatingInterestRateSwapLeg floatingLeg = (FloatingInterestRateSwapLeg) leg;
final ExternalIdBundle id = getIndexIdForSwap(floatingLeg);
final LocalDate startDate = swapEffectiveDate.toLocalDate().minusDays(360);
// Implementation note: To catch first fixing. SwapSecurity does not have this date.
final HistoricalTimeSeriesResolutionResult ts = getTimeSeriesResolver().resolve(id, null, null, null, MarketDataRequirementNames.MARKET_VALUE, null);
if (ts == null) {
return null;
}
return HistoricalTimeSeriesFunctionUtils.createHTSRequirement(ts, MarketDataRequirementNames.MARKET_VALUE,
DateConstraint.of(startDate), true, DateConstraint.VALUATION_TIME, true);
}
return null;
}
private ZonedDateTimeDoubleTimeSeries getIndexTimeSeries(final SwapLeg leg, final ZonedDateTime swapEffectiveDate, final ZonedDateTime now,
final HistoricalTimeSeriesBundle timeSeries) {
if (leg instanceof FloatingInterestRateLeg) {
final FloatingInterestRateLeg floatingLeg = (FloatingInterestRateLeg) leg;
final ExternalIdBundle id = getIndexIdForSwap(floatingLeg);
// Implementation note: To catch first fixing. SwapSecurity does not have this date.
if (now.isBefore(swapEffectiveDate)) { // TODO: review if this is the correct condition
return ImmutableZonedDateTimeDoubleTimeSeries.ofEmpty(now.getZone());
}
final HistoricalTimeSeries ts = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, id);
if (ts == null) {
s_logger.info("Could not get time series of underlying index " + id.getExternalIds().toString() + " bundle used was " + id);
return ImmutableZonedDateTimeDoubleTimeSeries.ofEmpty(now.getZone());
}
if (ts.getTimeSeries().isEmpty()) {
return ImmutableZonedDateTimeDoubleTimeSeries.ofEmpty(now.getZone());
}
LocalDateDoubleTimeSeries localDateTS = ts.getTimeSeries();
//TODO remove me when KWCDC Curncy is normalised correctly
if (localDateTS.getLatestValue() > 0.50) {
localDateTS = localDateTS.divide(100);
}
return convertTimeSeries(now.getZone(), localDateTS);
} else if (leg instanceof InflationIndexSwapLeg) {
final InflationIndexSwapLeg indexLeg = (InflationIndexSwapLeg) leg;
final ExternalIdBundle id = getIndexIdForInflationSwap(indexLeg);
// Implementation note: To catch first fixing. SwapSecurity does not have this date.
if (now.isBefore(swapEffectiveDate)) { // TODO: review if this is the correct condition
return ImmutableZonedDateTimeDoubleTimeSeries.ofEmpty(now.getZone());
}
final HistoricalTimeSeries ts = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, id);
if (ts == null) {
s_logger.info("Could not get time series of underlying index " + id.getExternalIds().toString() + " bundle used was " + id);
return ImmutableZonedDateTimeDoubleTimeSeries.ofEmpty(now.getZone());
}
if (ts.getTimeSeries().isEmpty()) {
return ImmutableZonedDateTimeDoubleTimeSeries.ofEmpty(now.getZone());
}
LocalDateDoubleTimeSeries localDateTS = ts.getTimeSeries();
//TODO remove me when KWCDC Curncy is normalised correctly
if (localDateTS.getLatestValue() > 0.50) {
localDateTS = localDateTS.divide(100);
}
return convertTimeSeries(now.getZone(), localDateTS);
}
return null;
}
private ZonedDateTimeDoubleTimeSeries getIndexTimeSeries(final InterestRateSwapLeg leg, final ZonedDateTime swapEffectiveDate, final ZonedDateTime now,
final HistoricalTimeSeriesBundle timeSeries) {
if (leg instanceof FloatingInterestRateSwapLeg) {
final FloatingInterestRateSwapLeg floatingLeg = (FloatingInterestRateSwapLeg) leg;
final ExternalIdBundle id = getIndexIdForSwap(floatingLeg);
// Implementation note: To catch first fixing. SwapSecurity does not have this date.
if (now.isBefore(swapEffectiveDate)) { // TODO: review if this is the correct condition
return ImmutableZonedDateTimeDoubleTimeSeries.ofEmpty(now.getZone());
}
final HistoricalTimeSeries ts = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, id);
if (ts == null) {
s_logger.info("Could not get time series of underlying index " + id.getExternalIds().toString() + " bundle used was " + id);
return ImmutableZonedDateTimeDoubleTimeSeries.ofEmpty(now.getZone());
}
if (ts.getTimeSeries().isEmpty()) {
return ImmutableZonedDateTimeDoubleTimeSeries.ofEmpty(now.getZone());
}
LocalDateDoubleTimeSeries localDateTS = ts.getTimeSeries();
//TODO remove me when KWCDC Curncy is normalised correctly
if (localDateTS.getLatestValue() > 0.50) {
localDateTS = localDateTS.divide(100);
}
return convertTimeSeries(now.getZone(), localDateTS);
}
return null;
}
private final Converter<InterestRateSwapSecurity, SwapDefinition> _irsSecurity = new Converter<InterestRateSwapSecurity, SwapDefinition>() {
@SuppressWarnings("synthetic-access")
@Override
public Set<ValueRequirement> getTimeSeriesRequirements(final InterestRateSwapSecurity security) {
Validate.notNull(security, "security");
final InterestRateSwapLeg payLeg = security.getPayLeg();
final InterestRateSwapLeg receiveLeg = security.getReceiveLeg();
final ZonedDateTime swapStartDate = security.getEffectiveDate().atStartOfDay(ZoneOffset.UTC);
final ZonedDateTime swapStartLocalDate = swapStartDate.toLocalDate().atStartOfDay(ZoneOffset.UTC);
final ValueRequirement payLegTS = getIndexTimeSeriesRequirement(payLeg, swapStartLocalDate);
final ValueRequirement receiveLegTS = getIndexTimeSeriesRequirement(receiveLeg, swapStartLocalDate);
final Set<ValueRequirement> requirements = new HashSet<>();
if (payLegTS != null) {
requirements.add(payLegTS);
}
if (receiveLegTS != null) {
requirements.add(receiveLegTS);
}
return requirements;
}
@Override
@SuppressWarnings({"synthetic-access" })
public InstrumentDerivative convert(final InterestRateSwapSecurity security, final SwapDefinition definition, final ZonedDateTime now, final String[] curveNames, final HistoricalTimeSeriesBundle timeSeries) {
Validate.notNull(security, "security");
if (timeSeries == null) {
return definition.toDerivative(now, curveNames);
}
final InterestRateSwapLeg payLeg = security.getPayLeg();
final InterestRateSwapLeg receiveLeg = security.getReceiveLeg();
final ZonedDateTime effectiveDate = security.getEffectiveDate().atStartOfDay(ZoneOffset.UTC);
final ZonedDateTime fixingSeriesStartDate = effectiveDate.isBefore(now) ? effectiveDate : now;
final ZonedDateTime fixingSeriesStartLocalDate = fixingSeriesStartDate.toLocalDate().atStartOfDay(ZoneOffset.UTC);
final ZonedDateTimeDoubleTimeSeries payLegTS = getIndexTimeSeries(payLeg, fixingSeriesStartLocalDate, now, timeSeries);
final ZonedDateTimeDoubleTimeSeries receiveLegTS = getIndexTimeSeries(receiveLeg, fixingSeriesStartLocalDate, now, timeSeries);
if (payLegTS != null) {
if (receiveLegTS != null) {
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {payLegTS, receiveLegTS }, curveNames);
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((FloatingInterestRateSwapLeg) payLeg).getFloatingReferenceRateId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id, e);
}
}
if ((InterestRateInstrumentType.getInstrumentTypeFromSecurity(security) == InterestRateInstrumentType.SWAP_FIXED_CMS)
|| (InterestRateInstrumentType.getInstrumentTypeFromSecurity(security) == InterestRateInstrumentType.SWAP_CROSS_CURRENCY)) {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {payLegTS, payLegTS }, curveNames);
}
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {payLegTS }, curveNames);
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((FloatingInterestRateSwapLeg) payLeg).getFloatingReferenceRateId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id, e);
}
}
if (receiveLegTS != null) {
if ((InterestRateInstrumentType.getInstrumentTypeFromSecurity(security) == InterestRateInstrumentType.SWAP_FIXED_CMS)
|| (InterestRateInstrumentType.getInstrumentTypeFromSecurity(security) == InterestRateInstrumentType.SWAP_CROSS_CURRENCY)) {
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {receiveLegTS, receiveLegTS }, curveNames);
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((FloatingInterestRateSwapLeg) payLeg).getFloatingReferenceRateId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id, e);
}
}
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {receiveLegTS, receiveLegTS }, curveNames);
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((FloatingInterestRateSwapLeg) receiveLeg).getFloatingReferenceRateId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id, e);
}
}
if (InterestRateInstrumentType.getInstrumentTypeFromSecurity(security) == InterestRateInstrumentType.SWAP_CROSS_CURRENCY) {
return definition.toDerivative(now, curveNames); // To deal with Fixed-Fixed cross currency swaps.
}
throw new OpenGammaRuntimeException("Could not get fixing series for either the pay or receive leg");
}
@Override
@SuppressWarnings({"synthetic-access" })
public InstrumentDerivative convert(final InterestRateSwapSecurity security, final SwapDefinition definition, final ZonedDateTime now, final HistoricalTimeSeriesBundle timeSeries) {
Validate.notNull(security, "security");
if (timeSeries == null) {
return definition.toDerivative(now);
}
final InterestRateSwapLeg payLeg = security.getPayLeg();
final InterestRateSwapLeg receiveLeg = security.getReceiveLeg();
final ZonedDateTime effectiveDate = security.getEffectiveDate().atStartOfDay(ZoneOffset.UTC);
final ZonedDateTime fixingSeriesStartDate = effectiveDate.isBefore(now) ? effectiveDate : now;
final ZonedDateTime fixingSeriesStartLocalDate = fixingSeriesStartDate.toLocalDate().atStartOfDay(ZoneOffset.UTC);
final ZonedDateTimeDoubleTimeSeries payLegTS = getIndexTimeSeries(payLeg, fixingSeriesStartLocalDate, now, timeSeries);
final ZonedDateTimeDoubleTimeSeries receiveLegTS = getIndexTimeSeries(receiveLeg, fixingSeriesStartLocalDate, now, timeSeries);
if (payLegTS != null) {
if (receiveLegTS != null) {
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {payLegTS, receiveLegTS });
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((FloatingInterestRateSwapLeg) payLeg).getFloatingReferenceRateId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id, e);
}
}
if ((InterestRateInstrumentType.getInstrumentTypeFromSecurity(security) == InterestRateInstrumentType.SWAP_FIXED_CMS)
|| (InterestRateInstrumentType.getInstrumentTypeFromSecurity(security) == InterestRateInstrumentType.SWAP_CROSS_CURRENCY)) {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {payLegTS, payLegTS });
}
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {payLegTS, payLegTS });
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((FloatingInterestRateSwapLeg) payLeg).getFloatingReferenceRateId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id + "; error was " + e.getMessage());
}
}
if (receiveLegTS != null) {
if ((InterestRateInstrumentType.getInstrumentTypeFromSecurity(security) == InterestRateInstrumentType.SWAP_FIXED_CMS)
|| (InterestRateInstrumentType.getInstrumentTypeFromSecurity(security) == InterestRateInstrumentType.SWAP_CROSS_CURRENCY)) {
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {receiveLegTS, receiveLegTS });
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((FloatingInterestRateSwapLeg) payLeg).getFloatingReferenceRateId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id, e);
}
}
try {
return definition.toDerivative(now, new ZonedDateTimeDoubleTimeSeries[] {receiveLegTS, receiveLegTS });
} catch (final OpenGammaRuntimeException e) {
final ExternalId id = ((FloatingInterestRateSwapLeg) receiveLeg).getFloatingReferenceRateId();
throw new OpenGammaRuntimeException("Could not get fixing value for series with identifier " + id, e);
}
}
if (InterestRateInstrumentType.getInstrumentTypeFromSecurity(security) == InterestRateInstrumentType.SWAP_CROSS_CURRENCY) {
return definition.toDerivative(now); // To deal with Fixed-Fixed cross currency swaps.
}
throw new OpenGammaRuntimeException("Could not get fixing series for either the pay or receive leg");
}
};
private ExternalIdBundle getIndexIdForSwap(final FloatingInterestRateLeg floatingLeg) {
if (floatingLeg.getFloatingRateType().isIbor() || floatingLeg.getFloatingRateType().equals(FloatingRateType.OIS) || floatingLeg.getFloatingRateType().equals(FloatingRateType.CMS)) {
return getIndexIdBundle(floatingLeg.getFloatingReferenceRateId());
}
return ExternalIdBundle.of(floatingLeg.getFloatingReferenceRateId());
}
private ExternalIdBundle getIndexIdForSwap(final FloatingInterestRateSwapLeg floatingLeg) {
return ExternalIdBundle.of(floatingLeg.getFloatingReferenceRateId());
}
private ExternalIdBundle getIndexIdForInflationSwap(final InflationIndexSwapLeg inflationIndexLeg) {
return getIndexIdBundle(inflationIndexLeg.getIndexId());
}
/**
* Returns the ExternalIDBundle associated to an ExternalId as stored in the convention source.
*
* @param indexId The external id.
* @return The bundle.
*/
private ExternalIdBundle getIndexIdBundle(final ExternalId indexId) {
final ConventionBundle indexConvention = getConventionSource().getConventionBundle(indexId);
if (indexConvention == null) {
throw new OpenGammaRuntimeException("No conventions found for floating reference rate " + indexId);
}
return indexConvention.getIdentifiers();
}
private ValueRequirement getIndexTimeSeriesRequirement(final ExternalIdBundle id, final LocalDate startDate) {
final HistoricalTimeSeriesResolutionResult timeSeries = getTimeSeriesResolver().resolve(id, null, null, null, MarketDataRequirementNames.MARKET_VALUE, null);
if (timeSeries == null) {
return null;
}
return HistoricalTimeSeriesFunctionUtils.createHTSRequirement(timeSeries, MarketDataRequirementNames.MARKET_VALUE,
DateConstraint.of(startDate), true, DateConstraint.VALUATION_TIME, true);
}
/**
* Returns the time series to be used in the toDerivative method.
*
* @param id The ExternalId bundle.
* @param startDate The time series start date (included in the time series).
* @param timeZone The time zone to use for the returned series
* @param dataSource The time series data source.
* @return The time series.
*/
private static ZonedDateTimeDoubleTimeSeries getIndexTimeSeries(final ExternalIdBundle id, final ZoneId timeZone, final HistoricalTimeSeriesBundle timeSeries) {
final HistoricalTimeSeries ts = timeSeries.get(MarketDataRequirementNames.MARKET_VALUE, id);
// Implementation note: the normalization take place in the getHistoricalTimeSeries
if (ts == null) {
throw new OpenGammaRuntimeException("Could not get time series of underlying index " + id.getExternalIds().toString());
}
if (ts.getTimeSeries().isEmpty()) {
return ImmutableZonedDateTimeDoubleTimeSeries.ofEmpty(timeZone);
}
return convertTimeSeries(timeZone, ts.getTimeSeries());
}
private static ZonedDateTimeDoubleTimeSeries convertTimeSeries(final ZoneId timeZone, final LocalDateDoubleTimeSeries localDateTS) {
// FIXME CASE Converting a daily historical time series to an arbitrary time. Bad idea
final ZonedDateTimeDoubleTimeSeriesBuilder bld = ImmutableZonedDateTimeDoubleTimeSeries.builder(timeZone);
for (final LocalDateDoubleEntryIterator it = localDateTS.iterator(); it.hasNext();) {
final LocalDate date = it.nextTime();
final ZonedDateTime zdt = date.atStartOfDay(timeZone);
bld.put(zdt, it.currentValueFast());
}
return bld.build();
}
} |
package com.tlear.pegasus;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import java.util.HashMap;
public class Ship {
private Hitbox hitBox;
// Ship model position
private float x;
private float y;
// Ship display position
private float dispX;
private float dispY;
// Ship textures
private HashMap<ShipDirection, Texture> shipImages;
private HashMap<ShipDirection, TextureRegion> shipTextures;
// Other textures
private BitmapFont font;
// Ship movement model
private float shipAngle;
private float shipSpeed;
private ShipDirection shipDirection;
public float rotationalVelocity;
// Constraints
private int maxSpeed;
private int maxRotationalVelocity;
// Ship texture size
private int shipTexWidth;
private int shipTexHeight;
// Ship model size
private int shipWidth;
private int shipHeight;
private Vector2 shipCentre;
// Stage size
private int windowWidth;
private int windowHeight;
// Hitbox offsets
private float offX;
private float offY;
// Laser variables
private boolean firingLaser;
private Vector2 laserTarget;
// Parts
private ShipLaser laserTurret;
// Debug
private boolean debugMode;
private String debugString;
public Ship(int windowWidth, int windowHeight) {
/* Load textures */
// Set up maps of directions
shipImages = new HashMap<ShipDirection, Texture>();
shipImages.put(ShipDirection.NONE, new Texture(Gdx.files.internal("ship.png")));
shipImages.put(ShipDirection.FORWARD, new Texture(Gdx.files.internal("shipForward.png")));
shipImages.put(ShipDirection.BACKWARD, new Texture(Gdx.files.internal("shipBackward.png")));
shipImages.put(ShipDirection.LEFT, new Texture(Gdx.files.internal("shipLeft.png")));
shipImages.put(ShipDirection.RIGHT, new Texture(Gdx.files.internal("shipRight.png")));
shipTextures = new HashMap<ShipDirection, TextureRegion>();
shipTextures.put(ShipDirection.NONE, new TextureRegion(shipImages.get(ShipDirection.NONE)));
shipTextures.put(ShipDirection.FORWARD, new TextureRegion(shipImages.get(ShipDirection.FORWARD)));
shipTextures.put(ShipDirection.BACKWARD, new TextureRegion(shipImages.get(ShipDirection.BACKWARD)));
shipTextures.put(ShipDirection.LEFT, new TextureRegion(shipImages.get(ShipDirection.LEFT)));
shipTextures.put(ShipDirection.RIGHT, new TextureRegion(shipImages.get(ShipDirection.RIGHT)));
// Load other textures
font = new BitmapFont();
font.setColor(Color.GREEN);
// Initialise speed and rotation
shipSpeed = 0f;
shipAngle = 0f;
rotationalVelocity = 0f;
shipDirection = ShipDirection.NONE;
// Initialise ship texture size
shipTexWidth = 95;
shipTexHeight = 108;
// Initalise the ship model size
shipWidth = 60;
shipHeight = 100;
// Initialise position
x = windowWidth / 2 - shipTexWidth / 2;
y = windowHeight / 2 - shipTexHeight / 2;
// Initialise display position - centre of screen for Pegasus
dispX = x;
dispY = y;
shipCentre = new Vector2(x + shipTexWidth / 2, y + shipTexHeight / 2);
// Initialise the hitbox to always be contained inside the ship's texture
// regardless of the rotation
hitBox = new Hitbox();
hitBox.width = hitBox.height = (float) Math.sqrt((Math.pow((double) shipWidth, 2.0) / 2.0));
offX = (shipTexWidth / 2) - (hitBox.width / 2);
offY = (shipTexHeight / 2) - (hitBox.height / 2);
hitBox.x = x + offX;
hitBox.y = y + offY;
hitBox.dispX = hitBox.x;
hitBox.dispY = hitBox.y;
// Initialise parts
laserTurret = new ShipLaser(new Vector2(shipTexWidth / 2, shipTexHeight / 2));
laserTurret.addX(-laserTurret.getTexWidth() / 2);
laserTurret.addY(-laserTurret.getTexHeight() / 2);
// Initialise window
this.windowWidth = windowWidth;
this.windowHeight = windowHeight;
// Initialise constraints
maxSpeed = 200;
maxRotationalVelocity = 2;
// Initialise laser
firingLaser = false;
laserTarget = new Vector2();
// Set debug mode
debugMode = true;
debugString = "";
}
public void draw(SpriteBatch batch, ShapeRenderer shapeRenderer) {
batch.begin();
// Draw ship
batch.draw(shipTextures.get(shipDirection), dispX, dispY, shipTexWidth / 2, shipTexHeight / 2, shipTexWidth, shipTexHeight, 1.0f, 1.0f, shipAngle);
batch.end();
shapeRenderer.begin(ShapeType.Line);
//Draw laser
if (firingLaser) {
shapeRenderer.setColor(1, 0, 0, 1);
shapeRenderer.line(new Vector2(x + shipTexWidth / 2, y + shipTexHeight / 2), laserTarget);
}
shapeRenderer.end();
// Draw laser turret after laser
batch.begin();
batch.draw(laserTurret.getTextureRegion(), dispX + laserTurret.getX(), dispY + laserTurret.getY(), laserTurret.getTexWidth() / 2, laserTurret.getTexHeight() / 2, laserTurret.getTexWidth(), laserTurret.getTexHeight(), 1.0f, 1.0f, laserTurret.getAngle());
batch.end();
// Draw debug info last always
if (debugMode) {
//Draw debug info
shapeRenderer.begin(ShapeType.Line);
shapeRenderer.setColor(0, 1, 0, 1);
shapeRenderer.rect(hitBox.dispX, hitBox.dispY, hitBox.width, hitBox.height);
shapeRenderer.end();
batch.begin();
font.drawMultiLine(batch, debugString, 10, windowHeight-10);
batch.end();
}
// Move the ship
double dx = shipSpeed * Math.cos(degreesToRadians(shipAngle+90)) * Gdx.graphics.getDeltaTime();
double dy = shipSpeed * Math.sin(degreesToRadians(shipAngle+90)) * Gdx.graphics.getDeltaTime();
x += dx;
y += dy;
shipAngle += rotationalVelocity;
if (!firingLaser) laserTurret.addAngle(rotationalVelocity);
checkOutOfBounds();
hitBox.x = x + offX;
hitBox.y = y + offY;
shipCentre = new Vector2(x + shipTexWidth / 2, y + shipTexHeight / 2);
if (debugMode) {
debugString = "Speed: " + shipSpeed;
debugString+= "\nAngle: " + (int) shipAngle;
debugString+= "\nx: " + (int) x;
debugString+= "\ny: " + (int) y;
debugString+= "\nRotVel: " + (double) ((int) (rotationalVelocity*100)) / 100 + "º";
debugString+= "\nFiring: " + firingLaser;
debugString+= "\nTarget: " + laserTarget.toString();
debugString+= "\nTurret Angle: " + laserTurret.getAngle();
}
}
public void addAngle(float a) {
if (Math.abs(rotationalVelocity + a) <= maxRotationalVelocity) {
rotationalVelocity += a;
shipDirection = a > 0 ? ShipDirection.LEFT : ShipDirection.RIGHT;
}
}
public void addSpeed(int s) {
if (shipSpeed + s <= maxSpeed && shipSpeed + s >= -maxSpeed / 2) {
shipSpeed += s;
shipDirection = s > 0 ? ShipDirection.FORWARD : ShipDirection.BACKWARD;
} else {
shipDirection = shipDirection != ShipDirection.NONE ? shipDirection : ShipDirection.NONE;
}
}
public void fire(Vector3 pos) {
// Fires the ship's laser at the position
firingLaser = true;
laserTarget = new Vector2(pos.x, pos.y);
Vector2 laserVector = new Vector2(laserTarget);
laserVector.sub(shipCentre);
float a = radiansToDegrees(Math.atan(laserVector.y / laserVector.x)) - 90;
if (laserTarget.x < shipCentre.x) a += 180;
laserTurret.setAngle(a);
}
public void reset() {
// Set no direction and not firing
shipDirection = ShipDirection.NONE;
firingLaser = false;
}
public void stopMoving() {
shipSpeed = 0;
rotationalVelocity = 0;
shipDirection = ShipDirection.NONE;
}
public void dispose() {
font.dispose();
}
public void setDirection(ShipDirection d) {
shipDirection = d;
}
private double degreesToRadians(float deg) {
return deg * Math.PI / 180;
}
private float radiansToDegrees(double rad) {
return (float) (rad * 180 / Math.PI);
}
private void checkOutOfBounds() {
if (x > windowWidth - shipWidth/2) {
x = -shipWidth/2;
} else if (x < -shipWidth/2) {
x = windowWidth - shipWidth/2;
}
if (y > windowHeight - shipHeight/2) {
y = -shipHeight/2;
} else if (y < -shipHeight/2) {
y = windowHeight - shipHeight/2;
}
}
} |
package com.heroku.theinternet.pages.web;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import ru.yandex.qatools.allure.annotations.Step;
import ru.yandex.qatools.htmlelements.annotations.Name;
import com.frameworkium.pages.internal.BasePage;
import com.frameworkium.pages.internal.Visible;
public class IFramePage extends BasePage<IFramePage> {
@Visible
@Name("Wysiwyg editor iframe")
@FindBy(css = "iframe#mce_0_ifr")
private WebElement wysiwygIFrame;
@Name("Bold Button")
@Visible
@FindBy(css = "div[aria-label='Bold'] button")
private WebElement boldButton;
@Name("Wysiwyg editor")
//This is within the iframe so while it'll be physically visible
//when the page loads, it WILL NOT be 'visible' to the
//driver (ie selenium will not be able to 'see' it) until we
//switchTo it - see below
@FindBy(id = "tinymce")
private WebElement wysiwygTextBox;
@Step("Clear text in editor")
public void clearTextInEditor() {
//Switch driver context to the iframe
driver.switchTo().frame(wysiwygIFrame);
//Perform actions within the iframe
wysiwygTextBox.clear();
//Switch back to the main page before returning
driver.switchTo().parentFrame();
}
@Step("Enter text in editor")
public void enterTextInEditor(String text) {
//Switch driver context to the iframe
driver.switchTo().frame(wysiwygIFrame);
//Perform actions within the iframe
wysiwygTextBox.sendKeys(text);
//Switch back to the main page before returning
driver.switchTo().parentFrame();
}
@Step("Get editor text")
public String getTextInEditor() {
//Switch driver context to the iframe
driver.switchTo().frame(wysiwygIFrame);
//Perform actions within the iframe
String text = wysiwygTextBox.getText();
//Switch back to the main page before returning
driver.switchTo().parentFrame();
return text;
}
@Step("Enter Bold Text")
public void enterBoldTextInEditor(String text) {
//Click bold button (As it's NOT in the iframe)
boldButton.click();
//Switch driver context to the iframe
driver.switchTo().frame(wysiwygIFrame);
//Perform actions within the iframe
wysiwygTextBox.sendKeys(text);
//Switch back to the main page before returning
driver.switchTo().parentFrame();
//Unclick bold button (still not in the iframe!)
boldButton.click();
}
} |
package hudson.plugins.git.browser;
import hudson.model.Run;
import hudson.plugins.git.GitChangeLogParser;
import hudson.plugins.git.GitChangeSet;
import hudson.plugins.git.GitChangeSet.Path;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import static org.junit.Assert.*;
import org.junit.Test;
import org.xml.sax.SAXException;
public class GitoriousWebTest {
private static final String GITORIOUS_URL = "https://SERVER/PROJECT";
private final GitoriousWeb gitoriousWeb = new GitoriousWeb(GITORIOUS_URL);
/**
* Test method for {@link hudson.plugins.git.browser.GitoriousWeb#getUrl()}.
* @throws MalformedURLException
*/
@Test
public void testGetUrl() throws IOException {
assertEquals(String.valueOf(gitoriousWeb.getUrl()), GITORIOUS_URL + "/");
}
/**
* Test method for {@link hudson.plugins.git.browser.GitoriousWeb#getUrl()}.
* @throws MalformedURLException
*/
@Test
public void testGetUrlForRepoWithTrailingSlash() throws IOException {
assertEquals(String.valueOf(new GitoriousWeb(GITORIOUS_URL + "/").getUrl()), GITORIOUS_URL + "/");
}
/**
* Test method for {@link hudson.plugins.git.browser.GitoriousWeb#getChangeSetLink(hudson.plugins.git.GitChangeSet)}.
* @throws SAXException
* @throws IOException
*/
@Test
public void testGetChangeSetLinkGitChangeSet() throws IOException, SAXException {
final URL changeSetLink = gitoriousWeb.getChangeSetLink(createChangeSet("rawchangelog"));
assertEquals(GITORIOUS_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d", changeSetLink.toString());
}
/**
* Test method for {@link hudson.plugins.git.browser.GitoriousWeb#getDiffLink(hudson.plugins.git.GitChangeSet.Path)}.
* @throws SAXException
* @throws IOException
*/
@Test
public void testGetDiffLinkPath() throws IOException, SAXException {
final HashMap<String, Path> pathMap = createPathMap("rawchangelog");
final Path modified1 = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java");
assertEquals(GITORIOUS_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d/diffs?diffmode=sidebyside&fragment=1#src/main/java/hudson/plugins/git/browser/GithubWeb.java", gitoriousWeb.getDiffLink(modified1).toString());
// For added files returns a link to the commit.
final Path added = pathMap.get("src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file");
assertEquals(GITORIOUS_URL + "/commit/396fc230a3db05c427737aa5c2eb7856ba72b05d/diffs?diffmode=sidebyside&fragment=1#src/test/resources/hudson/plugins/git/browser/rawchangelog-with-deleted-file", gitoriousWeb.getDiffLink(added).toString());
}
/**
* Test method for {@link hudson.plugins.git.browser.GithubWeb#getFileLink(hudson.plugins.git.GitChangeSet.Path)}.
* @throws SAXException
* @throws IOException
*/
@Test
public void testGetFileLinkPath() throws IOException, SAXException {
final HashMap<String,Path> pathMap = createPathMap("rawchangelog");
final Path path = pathMap.get("src/main/java/hudson/plugins/git/browser/GithubWeb.java");
final URL fileLink = gitoriousWeb.getFileLink(path);
assertEquals(GITORIOUS_URL + "/blobs/396fc230a3db05c427737aa5c2eb7856ba72b05d/src/main/java/hudson/plugins/git/browser/GithubWeb.java", String.valueOf(fileLink));
}
/**
* Test method for {@link hudson.plugins.git.browser.GithubWeb#getFileLink(hudson.plugins.git.GitChangeSet.Path)}.
* @throws SAXException
* @throws IOException
*/
@Test
public void testGetFileLinkPathForDeletedFile() throws IOException, SAXException {
final HashMap<String,Path> pathMap = createPathMap("rawchangelog-with-deleted-file");
final Path path = pathMap.get("bar");
final URL fileLink = gitoriousWeb.getFileLink(path);
assertEquals(GITORIOUS_URL + "/commit/fc029da233f161c65eb06d0f1ed4f36ae81d1f4f/diffs?diffmode=sidebyside&fragment=1#bar", String.valueOf(fileLink));
}
private GitChangeSet createChangeSet(String rawchangelogpath) throws IOException, SAXException {
final File rawchangelog = new File(GitoriousWebTest.class.getResource(rawchangelogpath).getFile());
final GitChangeLogParser logParser = new GitChangeLogParser(false);
final List<GitChangeSet> changeSetList = logParser.parse((Run) null, null, rawchangelog).getLogs();
return changeSetList.get(0);
}
/**
* @param changelog
* @return
* @throws IOException
* @throws SAXException
*/
private HashMap<String, Path> createPathMap(final String changelog) throws IOException, SAXException {
final HashMap<String, Path> pathMap = new HashMap<String, Path>();
final Collection<Path> changeSet = createChangeSet(changelog).getPaths();
for (final Path path : changeSet) {
pathMap.put(path.getPath(), path);
}
return pathMap;
}
} |
package io.teknek.zookeeper;
import java.util.Properties;
import io.teknek.daemon.TeknekDaemon;
import io.teknek.datalayer.WorkerDaoException;
import io.teknek.plan.Plan;
import junit.framework.Assert;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.test.InstanceSpec;
import org.apache.curator.test.QuorumConfigBuilder;
import org.apache.curator.test.TestingZooKeeperServer;
import org.apache.zookeeper.ZooKeeper;
import org.junit.Test;
public class TestRestablishingKeeper extends EmbeddedZooKeeperServer {
@Test
public void showAutoRecovery() throws Exception {
Properties p = new Properties();
p.put(TeknekDaemon.ZK_SERVER_LIST, zookeeperTestServer.getInstanceSpec().getConnectString());
final TeknekDaemon td = new TeknekDaemon(p);
int port = zookeeperTestServer.getInstanceSpec().getPort();
System.out.println(zookeeperTestServer.getInstanceSpec().getConnectString());
RestablishingKeeper k = new RestablishingKeeper(zookeeperTestServer.getInstanceSpec().getConnectString()){
@Override
public void onReconnect(ZooKeeper zk, CuratorFramework framework){
try {
td.getWorkerDao().createZookeeperBase(zk);
} catch (WorkerDaoException e) {
throw new RuntimeException(e);
}
}
};
//Assert.assertEquals(1, k.getReestablished());
Plan plan = new Plan().withName("abc");
td.getWorkerDao().createOrUpdatePlan(plan, k.getZooKeeper());
Assert.assertEquals(1, td.getWorkerDao().finalAllPlanNames(k.getZooKeeper()).size());
zookeeperTestServer.stop();
try {
td.getWorkerDao().finalAllPlanNames(k.getZooKeeper());
Assert.fail("Dao should have failed");
} catch (Exception ex){ }
try {
Assert.assertEquals(1, td.getWorkerDao().finalAllPlanNames(k.getZooKeeper()).size());
Assert.fail("Dao should have failed");
} catch (Exception ex){ }
zookeeperTestServer.start();
Thread.sleep(3000);
Assert.assertEquals(0, td.getWorkerDao().finalAllPlanNames(k.getZooKeeper()).size());
Assert.assertEquals(2, k.getReestablished());
}
} |
package org.animotron.statement.operator;
import org.animotron.ATest;
import org.animotron.expression.JExpression;
import org.animotron.statement.query.GET;
import org.junit.Test;
import static org.animotron.expression.JExpression._;
import static org.animotron.expression.JExpression.__;
import static org.animotron.expression.JExpression.value;
/**
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
*
*/
public class SimpleTest extends ATest {
@Test
public void an() throws Throwable {
__(
new JExpression(
_(DEF._, "AA")
),
new JExpression(
_(DEF._, "BB", _(AN._, "AA", value("a@b")))
)
);
JExpression C = new JExpression(
_(DEF._, "CC", _(AN._, "BB"))
);
assertAnimoResultOneStep(C, "def CC BB.");// AA \"a@b\".");
}
@Test
public void get() throws Throwable {
__(
new JExpression(
_(DEF._, "A")
),
new JExpression(
_(DEF._, "B", _(AN._, "A", value("a@b")))
)
);
JExpression C = new JExpression(
_(DEF._, "C", _(GET._, "A", _(AN._, "B")))
);
assertAnimoResult(C, "def C \"a@b\".");
}
} |
package com.eclipsesource.gerrit.plugins.fileattachment.api.test.client;
/**
* @author Florian Zoubek
*
*/
public class RestFileAttachmentClientFactoryTest {
// There are currently not reasonable test cases for
// RestFileAttachmentClientFactory
} |
package net.sf.taverna.t2.workflowmodel.processor.dispatch.layers;
import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.UUID;
import java.util.Map.Entry;
import net.sf.taverna.t2.invocation.Event;
import net.sf.taverna.t2.provenance.connector.ProvenanceConnector;
import net.sf.taverna.t2.provenance.item.ActivityProvenanceItem;
import net.sf.taverna.t2.provenance.item.ErrorProvenanceItem;
import net.sf.taverna.t2.provenance.item.InputDataProvenanceItem;
import net.sf.taverna.t2.provenance.item.IterationProvenanceItem;
import net.sf.taverna.t2.provenance.item.OutputDataProvenanceItem;
import net.sf.taverna.t2.provenance.item.ProcessProvenanceItem;
import net.sf.taverna.t2.provenance.item.ProcessorProvenanceItem;
import net.sf.taverna.t2.provenance.item.ProvenanceItem;
import net.sf.taverna.t2.provenance.item.WorkflowProvenanceItem;
import net.sf.taverna.t2.reference.ExternalReferenceSPI;
import net.sf.taverna.t2.reference.Identified;
import net.sf.taverna.t2.reference.ReferenceService;
import net.sf.taverna.t2.reference.ReferenceSet;
import net.sf.taverna.t2.reference.T2Reference;
import net.sf.taverna.t2.reference.T2ReferenceType;
import net.sf.taverna.t2.workflowmodel.Dataflow;
import net.sf.taverna.t2.workflowmodel.processor.activity.Activity;
import net.sf.taverna.t2.workflowmodel.processor.activity.AsynchronousActivity;
import net.sf.taverna.t2.workflowmodel.processor.dispatch.AbstractDispatchLayer;
import net.sf.taverna.t2.workflowmodel.processor.dispatch.events.DispatchCompletionEvent;
import net.sf.taverna.t2.workflowmodel.processor.dispatch.events.DispatchErrorEvent;
import net.sf.taverna.t2.workflowmodel.processor.dispatch.events.DispatchJobEvent;
import net.sf.taverna.t2.workflowmodel.processor.dispatch.events.DispatchJobQueueEvent;
import net.sf.taverna.t2.workflowmodel.processor.dispatch.events.DispatchResultEvent;
import org.apache.log4j.Logger;
/**
* Sits above the {@link Invoke} layer and collects information about the
* current workflow run to be stored by the {@link ProvenanceConnector}.
*
* @author Ian Dunlop
* @author Stian Soiland-Reyes
*
*/
public class IntermediateProvenance extends AbstractDispatchLayer<String> {
Logger logger = Logger.getLogger(IntermediateProvenance.class);
private ProvenanceConnector connector;
Map<String, Map<String, IterationProvenanceItem>> processToIndexes = new HashMap<String, Map<String, IterationProvenanceItem>>();
private Map<ActivityProvenanceItem, List<Object>> activityProvenanceItemMap = new HashMap<ActivityProvenanceItem, List<Object>>();
private Map<InputDataProvenanceItem, List<Object>> inputDataProvenanceItemMap = new HashMap<InputDataProvenanceItem, List<Object>>();
// private List<ActivityProvenanceItem> activityProvenanceItemList = new
// ArrayList<ActivityProvenanceItem>();
// private List<InputDataProvenanceItem> inputDataProvenanceItemList = new
// ArrayList<InputDataProvenanceItem>();
private WorkflowProvenanceItem workflowItem;
public void configure(String o) {
}
/**
* A set of provenance events for a particular owning process has been
* finished with so you can remove all the {@link IterationProvenanceItem}s
* from the map
*/
@Override
public void finishedWith(String owningProcess) {
processToIndexes.remove(owningProcess);
}
public String getConfiguration() {
return null;
}
protected Map<String, IterationProvenanceItem> getIndexesByProcess(
String owningProcess) {
synchronized (processToIndexes) {
Map<String, IterationProvenanceItem> indexes = processToIndexes
.get(owningProcess);
if (indexes == null) {
indexes = new HashMap<String, IterationProvenanceItem>();
processToIndexes.put(owningProcess, indexes);
}
return indexes;
}
}
protected IterationProvenanceItem getIterationProvItem(Event<?> event) {
String owningProcess = event.getOwningProcess();
int[] originalIndex = event.getIndex();
int[] index = event.getIndex();
String indexStr = indexStr(index);
Map<String, IterationProvenanceItem> indexes = getIndexesByProcess(owningProcess);
IterationProvenanceItem iterationProvenanceItem = null;
synchronized (indexes) {
// find the iteration item for the int index eg [1]
iterationProvenanceItem = indexes.get(indexStr);
// if it is null then strip the index and look again
while (iterationProvenanceItem == null) {
try {
index = removeLastIndex(index);
iterationProvenanceItem = indexes.get(indexStr(index));
// if we have a 'parent' iteration then create a new
// iteration for the original index and link it to the
// activity and the input data
// FIXME should this be linked to the parent iteration
// instead?
if (iterationProvenanceItem != null) {
// set the index to the one from the event
IterationProvenanceItem iterationProvenanceItem1 = new IterationProvenanceItem(
originalIndex);
iterationProvenanceItem1.setProcessId(owningProcess);
iterationProvenanceItem1.setIdentifier(UUID
.randomUUID().toString());
for (Entry<ActivityProvenanceItem, List<Object>> entrySet : activityProvenanceItemMap
.entrySet()) {
List<Object> value = entrySet.getValue();
int[] newIndex = (int[]) value.get(0);
String owner = (String) value.get(1);
String indexString = indexStr(newIndex);
String indexString2 = indexStr(index);
if (owningProcess.equalsIgnoreCase(owner)
&& indexString
.equalsIgnoreCase(indexString2)) {
iterationProvenanceItem1.setParentId(entrySet
.getKey().getIdentifier());
}
}
for (Entry<InputDataProvenanceItem, List<Object>> entrySet : inputDataProvenanceItemMap
.entrySet()) {
List<Object> value = entrySet.getValue();
int[] newIndex = (int[]) value.get(0);
String owner = (String) value.get(1);
String indexString = indexStr(newIndex);
String indexString2 = indexStr(index);
if (owningProcess.equalsIgnoreCase(owner)
&& indexString
.equalsIgnoreCase(indexString2)) {
iterationProvenanceItem1
.setInputDataItem(entrySet.getKey());
}
}
// for (ActivityProvenanceItem item :
// activityProvenanceItemList) {
// if (owningProcess.equalsIgnoreCase(item
// .getProcessId())) {
// iterationProvenanceItem1.setParentId(item
// .getIdentifier());
// for (InputDataProvenanceItem item :
// inputDataProvenanceItemList) {
// if (owningProcess.equalsIgnoreCase(item
// .getProcessId())) {
// iterationProvenanceItem1.setInputDataItem(item);
// indexes.put(indexStr, iterationProvenanceItem1);
// return iterationProvenanceItem1;
// add this new iteration item to the map
getIndexesByProcess(event.getOwningProcess()).put(
indexStr(event.getIndex()),
iterationProvenanceItem1);
return iterationProvenanceItem1;
}
// if we have not found an iteration items and the index
// [] then something is wrong
// remove the last index in the int array before we go
// back
// through the while
} catch (IllegalStateException e) {
logger
.warn("Cannot find a parent iteration with index [] for owning process: "
+ owningProcess
+ "Workflow invocation is in an illegal state");
throw e;
}
}
// if (iterationProvenanceItem == null) {
// logger.info("Iteration item was null for: "
// + event.getOwningProcess() + " " + event.getIndex());
// System.out.println("Iteration item was null for: "
// + event.getOwningProcess() + " " + event.getIndex());
// iterationProvenanceItem = new IterationProvenanceItem(index);
// iterationProvenanceItem.setProcessId(owningProcess);
// iterationProvenanceItem.setIdentifier(UUID.randomUUID()
// .toString());
// // for (ActivityProvenanceItem
// item:activityProvenanceItemList)
// // if (owningProcess.equalsIgnoreCase(item.getProcessId())) {
// // iterationProvenanceItem.setParentId(item.getIdentifier());
// // for (InputDataProvenanceItem item:
// // inputDataProvenanceItemList) {
// // if (owningProcess.equalsIgnoreCase(item.getProcessId())) {
// // iterationProvenanceItem.setInputDataItem(item);
// indexes.put(indexStr, iterationProvenanceItem);
}
return iterationProvenanceItem;
}
private String indexStr(int[] index) {
String indexStr = "";
for (int ind : index) {
indexStr += ":" + ind;
}
return indexStr;
}
/**
* Remove the last index of the int array in the form 1:2:3 etc
*
* @param index
* @return
*/
@SuppressWarnings("unused")
private String[] stripLastIndex(int[] index) {
String indexStr = "";
for (int ind : index) {
indexStr += ":" + ind;
}
// will be in form :1:2:3
String[] split = indexStr.split(":");
return split;
}
/**
* Remove the last value in the int array
*
* @param index
* @return
*/
private int[] removeLastIndex(int[] index) {
if (index.length == 0) {
throw new IllegalStateException(
"There is no parent iteration of index [] for this result");
}
int[] newIntArray = new int[index.length - 1];
for (int i = 0; i < index.length - 1; i++) {
newIntArray[i] = index[i];
}
return newIntArray;
}
/**
* Create an {@link ErrorProvenanceItem} and send across to the
* {@link ProvenanceConnector}
*/
@Override
public void receiveError(DispatchErrorEvent errorEvent) {
IterationProvenanceItem iterationProvItem = getIterationProvItem(errorEvent);
// get using errorEvent.getOwningProcess();
ErrorProvenanceItem errorItem = new ErrorProvenanceItem(errorEvent
.getCause(), errorEvent.getMessage(), errorEvent
.getFailureType(), errorEvent.getOwningProcess());
errorItem.setIdentifier(UUID.randomUUID().toString());
errorItem.setParentId(iterationProvItem.getIdentifier());
// iterationProvItem.setErrorItem(errorItem);
// FIXME don't need to add to the processor item earlier
getConnector().addProvenanceItem(errorItem, errorEvent.getContext());
super.receiveError(errorEvent);
}
/**
* Create the {@link ProvenanceItem}s and send them all across to the
* {@link ProvenanceConnector} except for the
* {@link IterationProvenanceItem}, this one is told what it's inputs are
* but has to wait until the results are received before being sent across.
* Each item has a unique identifier and also knows who its parent item is
*/
@Override
public void receiveJob(DispatchJobEvent jobEvent) {
// FIXME do we need this ProcessProvenanceItem?
ProcessProvenanceItem provenanceItem;
provenanceItem = new ProcessProvenanceItem(jobEvent.getOwningProcess());
provenanceItem.setIdentifier(UUID.randomUUID().toString());
provenanceItem.setParentId(workflowItem.getIdentifier());
ProcessorProvenanceItem processorProvItem;
processorProvItem = new ProcessorProvenanceItem(jobEvent
.getOwningProcess());
processorProvItem.setIdentifier(UUID.randomUUID().toString());
processorProvItem.setParentId(provenanceItem.getIdentifier());
provenanceItem.setProcessId(jobEvent.getOwningProcess());
getConnector().addProvenanceItem(provenanceItem, jobEvent.getContext());
getConnector().addProvenanceItem(processorProvItem, jobEvent.getContext());
IterationProvenanceItem iterationProvItem = null;
iterationProvItem = new IterationProvenanceItem(jobEvent.getIndex());
iterationProvItem.setIdentifier(UUID.randomUUID().toString());
ReferenceService referenceService = jobEvent.getContext()
.getReferenceService();
InputDataProvenanceItem inputDataItem = new InputDataProvenanceItem(
jobEvent.getData(), referenceService);
inputDataItem.setIdentifier(UUID.randomUUID().toString());
inputDataItem.setParentId(iterationProvItem.getIdentifier());
inputDataItem.setProcessId(jobEvent.getOwningProcess());
List<Object> inputIndexOwnerList = new ArrayList<Object>();
inputIndexOwnerList.add(jobEvent.getIndex());
inputIndexOwnerList.add(jobEvent.getOwningProcess());
inputDataProvenanceItemMap.put(inputDataItem, inputIndexOwnerList);
// inputDataProvenanceItemList.add(inputDataItem);
iterationProvItem.setInputDataItem(inputDataItem);
iterationProvItem.setIteration(jobEvent.getIndex());
iterationProvItem.setProcessId(jobEvent.getOwningProcess());
for (Activity<?> activity : jobEvent.getActivities()) {
if (activity instanceof AsynchronousActivity) {
ActivityProvenanceItem activityProvItem = new ActivityProvenanceItem(
activity);
activityProvItem.setIdentifier(UUID.randomUUID().toString());
iterationProvItem.setParentId(activityProvItem.getIdentifier());
// getConnector().addProvenanceItem(iterationProvItem);
activityProvItem.setParentId(processorProvItem.getIdentifier());
// processorProvItem.setActivityProvenanceItem(activityProvItem);
activityProvItem.setProcessId(jobEvent.getOwningProcess());
List<Object> activityIndexOwnerList = new ArrayList<Object>();
activityIndexOwnerList.add(jobEvent.getOwningProcess());
activityIndexOwnerList.add(jobEvent.getIndex());
activityProvenanceItemMap.put(activityProvItem,
inputIndexOwnerList);
// activityProvenanceItemList.add(activityProvItem);
// activityProvItem.setIterationProvenanceItem(iterationProvItem);
getConnector().addProvenanceItem(activityProvItem, jobEvent.getContext());
break;
}
}
getIndexesByProcess(jobEvent.getOwningProcess()).put(
indexStr(jobEvent.getIndex()), iterationProvItem);
super.receiveJob(jobEvent);
}
@Override
public void receiveJobQueue(DispatchJobQueueEvent jobQueueEvent) {
super.receiveJobQueue(jobQueueEvent);
}
/**
* Populate an {@link OutputDataProvenanceItem} with the results and attach
* it to the appropriate {@link IterationProvenanceItem}. Then send the
* {@link IterationProvenanceItem} across to the {@link ProvenanceConnector}
*/
@Override
public void receiveResult(DispatchResultEvent resultEvent) {
// FIXME use the connector from the result event context
IterationProvenanceItem iterationProvItem = getIterationProvItem(resultEvent);
ReferenceService referenceService = resultEvent.getContext()
.getReferenceService();
OutputDataProvenanceItem outputDataItem = new OutputDataProvenanceItem(
resultEvent.getData(), referenceService);
outputDataItem.setIdentifier(UUID.randomUUID().toString());
outputDataItem.setProcessId(resultEvent.getOwningProcess());
outputDataItem.setParentId(iterationProvItem.getIdentifier());
iterationProvItem.setOutputDataItem(outputDataItem);
getConnector().addProvenanceItem(iterationProvItem, resultEvent.getContext());
// getConnector().addProvenanceItem(outputDataItem);
super.receiveResult(resultEvent);
}
@Override
public void receiveResultCompletion(DispatchCompletionEvent completionEvent) {
// TODO Auto-generated method stub
super.receiveResultCompletion(completionEvent);
}
/**
* Tell this layer what {@link ProvenanceConnector} implementation is being
* used to capture the {@link ProvenanceItem}s. NOTE: should probably use
* the connector from the result events context where possible
*
* @param connector
*/
public void setConnector(ProvenanceConnector connector) {
this.connector = connector;
}
public ProvenanceConnector getConnector() {
return connector;
}
/**
* So that the {@link ProvenanceItem}s know which {@link Dataflow} has been
* enacted this layer has to know about the {@link WorkflowProvenanceItem}
*
* @param workflowItem
*/
public void setWorkflow(WorkflowProvenanceItem workflowItem) {
this.workflowItem = workflowItem;
}
public static String SerializeParam(Object ParamValue) {
ByteArrayOutputStream BStream = new ByteArrayOutputStream();
XMLEncoder encoder = new XMLEncoder(BStream);
encoder.writeObject(ParamValue);
encoder.close();
return BStream.toString();
}
public static Object DeserializeParam (String SerializedParam) {
InputStream IStream = new ByteArrayInputStream(SerializedParam.getBytes());
XMLDecoder decoder = new XMLDecoder(IStream);
Object output = decoder.readObject();
decoder.close();
return output;
}
} |
package org.helm.notation2;
import java.io.IOException;
import java.math.BigDecimal;
import org.helm.notation.CalculationException;
import org.helm.notation2.ContainerHELM2;
import org.helm.notation2.InterConnections;
import org.helm.notation2.calculation.ExtinctionCoefficient;
import org.helm.notation2.exception.ExtinctionCoefficientException;
import org.helm.notation2.exception.HELM2HandledException;
import org.helm.notation2.parser.StateMachineParser;
import org.helm.notation2.parser.exceptionparser.ExceptionState;
import org.jdom.JDOMException;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* ExtinctionCalculatorTest
*
* @author hecht
*/
public class ExtinctionCalculatorTest {
StateMachineParser parser;
@Test
public void testCalculationOnePeptide() throws ExceptionState, IOException, JDOMException, ExtinctionCoefficientException, CalculationException
{
parser = new StateMachineParser();
String test = "PEPTIDE1{C}|PEPTIDE2{Y.V.N.L.I}$PEPTIDE2,PEPTIDE1,5:R2-2:R3$$$";
;
for (int i = 0; i < test.length(); ++i) {
parser.doAction(test.charAt(i));
}
test += "V2.0";
ContainerHELM2 containerhelm2 = new ContainerHELM2(parser.notationContainer,
new InterConnections());
Float f = (float) 1.55;
Assert.assertEquals(BigDecimal.valueOf(ExtinctionCoefficient.getInstance().calculate(containerhelm2)).setScale(2, BigDecimal.ROUND_DOWN).floatValue(), f);
}
@Test
public void testCalculationOneRNA() throws ExceptionState, IOException, JDOMException, ExtinctionCoefficientException, CalculationException {
parser = new StateMachineParser();
String test = "RNA1{P.R(A)P.R([5meC])P.R(G)P.[mR](A)}$$$$";
;
for (int i = 0; i < test.length(); ++i) {
parser.doAction(test.charAt(i));
}
test += "V2.0";
ContainerHELM2 containerhelm2 = new ContainerHELM2(parser.notationContainer,
new InterConnections());
Float f = (float) 46.20;
Assert.assertEquals(BigDecimal.valueOf(ExtinctionCoefficient.getInstance().calculate(containerhelm2)).setScale(2, BigDecimal.ROUND_DOWN).floatValue(), f);
}
@Test
public void testCalculationRepeatingRNA() throws ExceptionState, IOException, JDOMException, ExtinctionCoefficientException, CalculationException {
parser = new StateMachineParser();
String test = "RNA1{P.(R(A)P.R(G)P)'2'.R([5meC])P.R(G)P.[mR](A)}$$$$";
;
for (int i = 0; i < test.length(); ++i) {
parser.doAction(test.charAt(i));
}
test += "V2.0";
ContainerHELM2 containerhelm2 = new ContainerHELM2(parser.notationContainer,
new InterConnections());
Float f = (float) 80.58;
Assert.assertEquals(BigDecimal.valueOf(ExtinctionCoefficient.getInstance().calculate(containerhelm2)).setScale(2, BigDecimal.ROUND_DOWN).floatValue(), f);
}
@Test
public void testCalculationRepeatingMonomer() throws ExceptionState, IOException, JDOMException, ExtinctionCoefficientException, CalculationException {
parser = new StateMachineParser();
String test = "PEPTIDE1{C'2'}$$$$";
;
for (int i = 0; i < test.length(); ++i) {
parser.doAction(test.charAt(i));
}
test += "V2.0";
ContainerHELM2 containerhelm2 = new ContainerHELM2(parser.notationContainer,
new InterConnections());
Float f = (float) 0.12;
Assert.assertEquals(BigDecimal.valueOf(ExtinctionCoefficient.getInstance().calculate(containerhelm2)).setScale(2, BigDecimal.ROUND_DOWN).floatValue(), f);
}
@Test
public void testCalculationRepeatingList() throws ExceptionState, IOException, JDOMException, ExtinctionCoefficientException, CalculationException {
parser = new StateMachineParser();
String test = "PEPTIDE1{(F.C.F)'3'}$$$$";
;
for (int i = 0; i < test.length(); ++i) {
parser.doAction(test.charAt(i));
}
test += "V2.0";
ContainerHELM2 containerhelm2 = new ContainerHELM2(parser.notationContainer,
new InterConnections());
Float f = (float) 0.19;
Assert.assertEquals(BigDecimal.valueOf(ExtinctionCoefficient.getInstance().calculate(containerhelm2)).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue(), f);
}
@Test
public void testCalculationWithCHEMAndBlob() throws ExceptionState, IOException, JDOMException, ExtinctionCoefficientException, CalculationException {
parser = new StateMachineParser();
String test = "CHEM1{[MCC]}|RNA1{R(U)}|BLOB1{?}$$$$";
;
for (int i = 0; i < test.length(); ++i) {
parser.doAction(test.charAt(i));
}
test += "V2.0";
ContainerHELM2 containerhelm2 = new ContainerHELM2(parser.notationContainer,
new InterConnections());
Float f = (float) 10.21;
Assert.assertEquals(BigDecimal.valueOf(ExtinctionCoefficient.getInstance().calculate(containerhelm2)).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue(), f);
}
@Test(expectedExceptions = ExtinctionCoefficientException.class)
public void testCalculationWithException() throws ExtinctionCoefficientException, CalculationException, ExceptionState, IOException, JDOMException {
parser = new StateMachineParser();
String test = "CHEM1{[MCC]}|RNA1{(R(U)+R(A))}|BLOB1{?}$$$$";
;
for (int i = 0; i < test.length(); ++i) {
parser.doAction(test.charAt(i));
}
test += "V2.0";
ContainerHELM2 containerhelm2 = new ContainerHELM2(parser.notationContainer,
new InterConnections());
Float f = (float) 10.21;
Assert.assertEquals(BigDecimal.valueOf(ExtinctionCoefficient.getInstance().calculate(containerhelm2)).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue(), f);
}
@Test(expectedExceptions = ExtinctionCoefficientException.class)
public void testCalculationWithException2() throws ExceptionState, IOException, JDOMException, ExtinctionCoefficientException, CalculationException {
parser = new StateMachineParser();
String test = "PEPTIDE1{?}$$$$";
;
for (int i = 0; i < test.length(); ++i) {
parser.doAction(test.charAt(i));
}
test += "V2.0";
ContainerHELM2 containerhelm2 = new ContainerHELM2(parser.notationContainer,
new InterConnections());
ExtinctionCoefficient.getInstance().calculate(containerhelm2);
}
@Test(expectedExceptions = ExtinctionCoefficientException.class)
public void testCalculationWithException3() throws ExceptionState, IOException, JDOMException, ExtinctionCoefficientException, CalculationException {
parser = new StateMachineParser();
String test = "PEPTIDE1{A.C._}$$$$";
;
for (int i = 0; i < test.length(); ++i) {
parser.doAction(test.charAt(i));
}
test += "V2.0";
ContainerHELM2 containerhelm2 = new ContainerHELM2(parser.notationContainer,
new InterConnections());
ExtinctionCoefficient.getInstance().calculate(containerhelm2);
}
@Test(expectedExceptions = ExtinctionCoefficientException.class)
public void testCalculationWithException4() throws ExceptionState, IOException, JDOMException, ExtinctionCoefficientException, CalculationException {
parser = new StateMachineParser();
String test = "PEPTIDE1{A.C.(_.K)}$$$$";
;
for (int i = 0; i < test.length(); ++i) {
parser.doAction(test.charAt(i));
}
test += "V2.0";
ContainerHELM2 containerhelm2 = new ContainerHELM2(parser.notationContainer,
new InterConnections());
ExtinctionCoefficient.getInstance().calculate(containerhelm2);
}
@Test(expectedExceptions = ExtinctionCoefficientException.class)
public void testCalculationWithException5() throws ExceptionState, IOException, JDOMException, ExtinctionCoefficientException, CalculationException {
parser = new StateMachineParser();
String test = "PEPTIDE1{X}$$$$";
;
for (int i = 0; i < test.length(); ++i) {
parser.doAction(test.charAt(i));
}
test += "V2.0";
ContainerHELM2 containerhelm2 = new ContainerHELM2(parser.notationContainer,
new InterConnections());
ExtinctionCoefficient.getInstance().calculate(containerhelm2);
}
@Test(expectedExceptions = ExtinctionCoefficientException.class)
public void testCalculationWithException6() throws ExceptionState, IOException, JDOMException, ExtinctionCoefficientException, CalculationException {
parser = new StateMachineParser();
String test = "PEPTIDE1{?}$$$$";
;
for (int i = 0; i < test.length(); ++i) {
parser.doAction(test.charAt(i));
}
test += "V2.0";
ContainerHELM2 containerhelm2 = new ContainerHELM2(parser.notationContainer,
new InterConnections());
System.out.println(ExtinctionCoefficient.getInstance().calculate(containerhelm2));
}
@Test(expectedExceptions = ExtinctionCoefficientException.class)
public void testCalculationWithException7() throws ExceptionState, IOException, JDOMException, ExtinctionCoefficientException, CalculationException {
parser = new StateMachineParser();
String test = "RNA1{R(N)P}$$$$";
;
for (int i = 0; i < test.length(); ++i) {
parser.doAction(test.charAt(i));
}
test += "V2.0";
ContainerHELM2 containerhelm2 = new ContainerHELM2(parser.notationContainer,
new InterConnections());
ExtinctionCoefficient.getInstance().calculate(containerhelm2);
}
@Test(expectedExceptions = ExtinctionCoefficientException.class)
public void testCalculationWithException8() throws ExceptionState, IOException, JDOMException, ExtinctionCoefficientException, CalculationException {
parser = new StateMachineParser();
String test = "RNA1{[[H]OC[C@H]1O[C@@H]([C@H](O)[C@@H]1OP(O)(=O)OC[C@H]1O[C@@H]([C@H](O)[C@@H]1OP(O)(=O)OC[C@H]1O[C@@H]([C@H](O)[C@@H]1O[H])N1C=CC(=O)NC1=O)N1C=CC(=O)NC1=O)N1C=CC(=O)NC1=O]}$$$$";
;
for (int i = 0; i < test.length(); ++i) {
parser.doAction(test.charAt(i));
}
test += "V2.0";
ContainerHELM2 containerhelm2 = new ContainerHELM2(parser.notationContainer,
new InterConnections());
ExtinctionCoefficient.getInstance().calculate(containerhelm2);
}
} |
package org.opendaylight.yangtools.yang.data.impl.schema.tree;
import com.google.common.base.Optional;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
final class OperationWithModification {
private final ModifiedNode modification;
private final ModificationApplyOperation applyOperation;
private OperationWithModification(final ModificationApplyOperation op, final ModifiedNode mod) {
this.modification = mod;
this.applyOperation = op;
}
public OperationWithModification write(final NormalizedNode<?, ?> value) {
modification.write(value);
applyOperation.verifyStructure(modification);
return this;
}
public OperationWithModification delete() {
modification.delete();
return this;
}
public ModifiedNode getModification() {
return modification;
}
public ModificationApplyOperation getApplyOperation() {
return applyOperation;
}
public Optional<TreeNode> apply(final Optional<TreeNode> data, final Version version) {
return applyOperation.apply(modification, data, version);
}
public static OperationWithModification from(final ModificationApplyOperation operation,
final ModifiedNode modification) {
return new OperationWithModification(operation, modification);
}
public void merge(final NormalizedNode<?, ?> data) {
modification.merge(data);
applyOperation.verifyStructure(modification);
}
public OperationWithModification forChild(final PathArgument childId) {
ModificationApplyOperation childOp = applyOperation.getChild(childId).get();
final boolean isOrdered;
if (childOp instanceof SchemaAwareApplyOperation) {
isOrdered = ((SchemaAwareApplyOperation) childOp).isOrdered();
} else {
isOrdered = true;
}
ModifiedNode childMod = modification.modifyChild(childId, isOrdered);
return from(childOp,childMod);
}
} |
package org.openremote.security;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.openremote.security.provider.BouncyCastleKeySigner;
import org.testng.Assert;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.Test;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.net.URI;
import java.security.KeyStore;
import java.security.Provider;
import java.security.Security;
import java.security.cert.Certificate;
import java.util.Arrays;
import java.util.UUID;
/**
* Unit tests for {@link org.openremote.security.PasswordManager}
*
* @author <a href="mailto:juha@openremote.org">Juha Lindfors</a>
*/
public class PasswordManagerTest
{
@AfterSuite public void clearSecurityProvider()
{
Provider p = Security.getProvider("BC");
if (p != null)
{
Assert.fail("Tests did not properly remove BouncyCastle provider.");
}
}
/**
* No arg constructor test (just code execution completeness)
*
* @throws Exception if test fails
*/
@Test public void testNoArgCtor() throws Exception
{
new PasswordManager();
}
/**
* Test file-persisted password manager with an existing, empty password store.
*
* @throws Exception if test fails
*/
@Test public void testFileConstructor() throws Exception
{
try
{
Security.addProvider(SecurityProvider.BC.getProviderInstance());
// Create an existing, empty keystore...
TestUBERStore store = new TestUBERStore();
File dir = new File(System.getProperty("user.dir"));
File file = new File(dir, "test.store-" + UUID.randomUUID());
file.deleteOnExit();
store.save(file.toURI(), new char[] { '0' });
char[] pw = new char[] { '0' };
PasswordManager mgr = new PasswordManager(file.toURI(), pw);
// check that password was erased....
for (Character c : pw)
{
Assert.assertTrue(c == 0);
}
}
finally
{
Security.removeProvider(SecurityProvider.BC.getProviderInstance().getName());
}
}
/**
* Test file-persisted password manager with an existing password store that contains
* passwords.
*
* @throws Exception if test fails
*/
@Test public void testFileConstructorWithExistingKeys() throws Exception
{
try
{
// BouncyCastle must be installed as a system security provider...
Security.addProvider(new BouncyCastleProvider());
// Create an existing keystore...
TestUBERStore store = new TestUBERStore();
File dir = new File(System.getProperty("user.dir"));
File file = new File(dir, "test.store-" + UUID.randomUUID());
file.deleteOnExit();
store.add(
"foo",
new KeyStore.SecretKeyEntry(new SecretKeySpec(new byte[] { '1' }, "test")),
new KeyStore.PasswordProtection(new char[] { '0' })
);
store.save(file.toURI(), new char[] { '0' });
char[] pw = new char[] { '0' };
PasswordManager mgr = new PasswordManager(file.toURI(), pw);
// check that password was erased....
for (Character c : pw)
{
Assert.assertTrue(c == 0);
}
// check that password is found...
Assert.assertTrue(Arrays.equals(mgr.getPassword("foo", new char[] {'0'}), new byte[] {'1'}));
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Test file-persisted password manager constructor loading a keystore that contains
* non-password entries.
*
* @throws Exception if test fails
*/
@Test public void testFileConstructorWithWrongEntryType() throws Exception
{
try
{
// BouncyCastle must be installed as a system security provider...
Security.addProvider(new BouncyCastleProvider());
// Create an existing keystore...
PrivateKeyManager keys = PrivateKeyManager.create();
Certificate cert = keys.addKey("bar", new char[] {'0'}, "test");
File dir = new File(System.getProperty("user.dir"));
File file = new File(dir, "test.store-" + UUID.randomUUID());
file.deleteOnExit();
TestUBERStore store = new TestUBERStore();
store.add(
"foo",
new KeyStore.TrustedCertificateEntry(cert),
null
);
store.save(file.toURI(), new char[] { '0' });
PasswordManager mgr = new PasswordManager(file.toURI(), new char[] { '0' });
try
{
mgr.getPassword("bar", new char[] {'0'});
Assert.fail("should not get here...");
}
catch (PasswordManager.PasswordNotFoundException e)
{
// expected...
}
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Test file-persisted password manager constructor against an empty file.
*
* @throws Exception if test fails
*/
@Test public void testFileConstructorWithEmptyFile() throws Exception
{
// Create an existing keystore...
File file = File.createTempFile("openremote", null);
try
{
new PasswordManager(file.toURI(), new char[] { '0' });
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Test file-persisted password manager constructor against a non-existent file.
*
* @throws Exception if test fails
*/
@Test public void testFileConstructorWithNewFile() throws Exception
{
try
{
// BouncyCastle must be installed as a system security provider...
Security.addProvider(new BouncyCastleProvider());
File dir = new File(System.getProperty("user.dir"));
File file = new File(dir, "test.store-" + UUID.randomUUID());
file.deleteOnExit();
PasswordManager mgr = new PasswordManager(file.toURI(), new char[] { '0' });
byte[] password = new byte[] { 'a' };
char[] masterpassword = new char[] { '0' };
mgr.addPassword("foo", password, masterpassword);
// Check that passwords are cleared...
for (Byte b : password)
{
Assert.assertTrue(b == 0);
}
for (Character c : masterpassword)
{
Assert.assertTrue(c == 0);
}
// try to retrieve the password...
byte[] pw = mgr.getPassword("foo", new char[] { '0' });
Assert.assertTrue(Arrays.equals(pw, new byte[] { 'a' }));
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Test error handling behavior when constructor has a null file descriptor.
*
* @throws Exception if test fails
*/
@Test public void testFileConstructorWithNullURI() throws Exception
{
try
{
new PasswordManager(null, new char[] { '0' });
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Test error handling behavior when constructor has a null password.
*
* @throws Exception if test fails
*/
@Test public void testFileConstructorWithNullPassword() throws Exception
{
try
{
new PasswordManager(File.createTempFile("openremote", null).toURI(), null);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Test error handling behavior when constructor has empty password.
*
* @throws Exception if test fails
*/
@Test public void testFileConstructorWithEmptyPassword() throws Exception
{
try
{
new PasswordManager(File.createTempFile("openremote", null).toURI(), new char[] {});
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Tests basic password add.
*
* @throws Exception if test fails
*/
@Test public void testAddPassword() throws Exception
{
try
{
// BouncyCastle must be installed as a system security provider...
Security.addProvider(new BouncyCastleProvider());
File dir = new File(System.getProperty("user.dir"));
File file = new File(dir, "test-" + UUID.randomUUID());
file.deleteOnExit();
char[] masterPW = new char[] { 'b' };
PasswordManager mgr = new PasswordManager(file.toURI(), masterPW);
// Check that the password is cleared...
for (Character c : masterPW)
{
Assert.assertTrue(c == 0);
}
masterPW = new char[] { 'b' };
mgr.addPassword("test", new byte[] { '1' }, masterPW);
// Check that the password is cleared...
for (Character c : masterPW)
{
Assert.assertTrue(c == 0);
}
byte[] pw = mgr.getPassword("test", new char[] { 'b' });
Assert.assertTrue(Arrays.equals(pw, new byte[] { '1' }));
TestUBERStore store = new TestUBERStore();
store.load(file.toURI(), new char[] { 'b' });
KeyStore.SecretKeyEntry entry = (KeyStore.SecretKeyEntry)store.retrieveKey(
"test", new KeyStore.PasswordProtection(new char[] {'b'})
);
Assert.assertTrue(Arrays.equals(entry.getSecretKey().getEncoded(), new byte[] { '1' }));
mgr = new PasswordManager(file.toURI(), new char[] { 'b' });
pw = mgr.getPassword("test", new char[] { 'b' });
Assert.assertTrue(Arrays.equals(pw, new byte[] { '1' }));
mgr.addPassword("tz", new byte[] { 'z' }, new char[] { 'b' });
mgr.addPassword("tx", new byte[] { 'x' }, new char[] { 'b' });
store.load(file.toURI(), new char[] {'b'});
Assert.assertTrue(store.contains("tz"));
Assert.assertTrue(store.contains("tx"));
Assert.assertTrue(store.contains("test"));
Assert.assertTrue(store.size() == 3);
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Test basic password add without persistence.
*
* @throws Exception if test fails
*/
@Test public void testAddPasswordInMemory() throws Exception
{
try
{
// BouncyCastle must be installed as a system security provider...
Security.addProvider(new BouncyCastleProvider());
PasswordManager mgr = new PasswordManager();
mgr.addPassword("test", new byte[] { '1' }, new char[] { 'b' });
byte[] pw = mgr.getPassword("test", new char[] { 'b' });
Assert.assertTrue(Arrays.equals(pw, new byte[] { '1' }));
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Test error handling when adding password with incorrect storage credentials.
*
* @throws Exception if test fails
*/
@Test public void testAddPasswordWrongPassword() throws Exception
{
try
{
Security.addProvider(SecurityProvider.BC.getProviderInstance());
File dir = new File(System.getProperty("user.dir"));
File file = new File(dir, "test-" + UUID.randomUUID());
file.deleteOnExit();
PasswordManager mgr = new PasswordManager(file.toURI(), new char[] { 'b' });
// TODO : currently this sets a NEW password to the store...
mgr.addPassword("test", new byte[] { '1' }, new char[] { 'c' });
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
finally
{
Security.removeProvider(SecurityProvider.BC.getProviderInstance().getName());
}
}
/**
* Tests error handling when adding password with a null alias.
*
* @throws Exception if test fails
*/
@Test public void testAddPasswordNullAlias() throws Exception
{
try
{
// BouncyCastle must be installed as a system security provider...
Security.addProvider(new BouncyCastleProvider());
File dir = new File(System.getProperty("user.dir"));
File file = new File(dir, "test-" + UUID.randomUUID());
file.deleteOnExit();
PasswordManager mgr = new PasswordManager(file.toURI(), new char[] { 'b' });
mgr.addPassword(null, new byte[] { '1' }, new char[] { 'c' });
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Tests error handling when adding password with empty alias.
*
* @throws Exception if test fails
*/
@Test public void testAddPasswordEmptyAlias() throws Exception
{
try
{
Security.addProvider(SecurityProvider.BC.getProviderInstance());
File dir = new File(System.getProperty("user.dir"));
File file = new File(dir, "test-" + UUID.randomUUID());
file.deleteOnExit();
PasswordManager mgr = new PasswordManager(file.toURI(), new char[] { 'b' });
mgr.addPassword("", new byte[] { '1' }, new char[] { 'c' });
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
finally
{
Security.removeProvider(SecurityProvider.BC.getProviderInstance().getName());
}
}
/**
* Tests addPassword() error handling when the given password is a null reference.
*
* @throws Exception if test fails
*/
@Test public void testAddPasswordNullPassword() throws Exception
{
try
{
Security.addProvider(SecurityProvider.BC.getProviderInstance());
File dir = new File(System.getProperty("user.dir"));
File file = new File(dir, "test-" + UUID.randomUUID());
file.deleteOnExit();
PasswordManager mgr = new PasswordManager(file.toURI(), new char[] { 'b' });
mgr.addPassword("test", null, new char[] { 'c' });
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
finally
{
Security.removeProvider(SecurityProvider.BC.getProviderInstance().getName());
}
}
/**
* Tests addPassword() error handling when the given password is an empty byte array.
*
* @throws Exception if test fails
*/
@Test public void testAddPasswordEmptyPassword() throws Exception
{
PasswordManager mgr = new PasswordManager();
try
{
mgr.addPassword("test", new byte[] { }, new char[] { 'c' });
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Tests addPassword() error handling when the store master password is a null.
*
* @throws Exception if test fails
*/
@Test public void testAddPasswordNullMasterPassword() throws Exception
{
try
{
Security.addProvider(SecurityProvider.BC.getProviderInstance());
File dir = new File(System.getProperty("user.dir"));
File file = new File(dir, "test-" + UUID.randomUUID());
file.deleteOnExit();
PasswordManager mgr = new PasswordManager(file.toURI(), new char[] { 'b' });
mgr.addPassword("test", new byte[] { '0' }, null);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
finally
{
Security.removeProvider(SecurityProvider.BC.getProviderInstance().getName());
}
}
/**
* Tests addPassword() error handling when the store master password is an empty character
* array.
*
* @throws Exception if test fails
*/
@Test public void testAddPasswordEmptyMasterPassword() throws Exception
{
PasswordManager mgr = new PasswordManager();
try
{
mgr.addPassword("test", new byte[] { '0' }, new char[] { });
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
/**
* Tests removePassword() with persistence.
*
* @throws Exception if test fails
*/
@Test public void testRemovePassword() throws Exception
{
try
{
// BouncyCastle must be installed as a system security provider...
Security.addProvider(new BouncyCastleProvider());
File dir = new File(System.getProperty("user.dir"));
File file = new File(dir, "test-" + UUID.randomUUID());
file.deleteOnExit();
PasswordManager mgr = new PasswordManager(file.toURI(), new char[] { 'b' });
mgr.addPassword("test", new byte[] { '1' }, new char[] { 'b' });
byte[] pw = mgr.getPassword("test", new char[] { 'b' });
Assert.assertTrue(Arrays.equals(pw, new byte[] { '1' }));
// Remove...
char[] masterPW = new char[] { 'b' };
mgr.removePassword("test", masterPW);
// Check that the password is cleared...
for (Character c : masterPW)
{
Assert.assertTrue(c == 0);
}
try
{
mgr.getPassword("test", new char[] { 'b' });
Assert.fail("should not get here...");
}
catch (PasswordManager.PasswordNotFoundException e)
{
// expected...
}
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Tests removePassword() consequent calls.
*
* @throws Exception if test fails
*/
@Test public void testRemovePasswordTwice() throws Exception
{
try
{
// BouncyCastle must be installed as a system security provider...
Security.addProvider(new BouncyCastleProvider());
PasswordManager mgr = new PasswordManager();
mgr.addPassword("test", new byte[] { '1' }, new char[] { 'b' });
byte[] pw = mgr.getPassword("test", new char[] { 'b' });
Assert.assertTrue(Arrays.equals(pw, new byte[] { '1' }));
// Remove...
char[] masterPW = new char[] { 'b' };
mgr.removePassword("test", masterPW);
// Check that the password is cleared...
for (Character c : masterPW)
{
Assert.assertTrue(c == 0);
}
mgr.removePassword("test", new char[] {'b'});
try
{
mgr.getPassword("test", new char[] {'b'});
Assert.fail("should not get here...");
}
catch (PasswordManager.PasswordNotFoundException e)
{
// expected...
}
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Tests removePassword().
*
* @throws Exception if test fails
*/
@Test public void testAddAndRemove() throws Exception
{
try
{
// BouncyCastle must be installed as a system security provider...
Security.addProvider(new BouncyCastleProvider());
URI uri = new URI("file", System.getProperty("user.dir") + "/test-" + UUID.randomUUID(), null);
File file = new File(uri);
file.deleteOnExit();
PasswordManager mgr = new PasswordManager(uri, new char[] { 'b' });
mgr.addPassword("test1", new byte[] { '1' }, new char[] { 'b' });
mgr.addPassword("test2", new byte[] { '2' }, new char[] { 'b' });
TestUBERStore store = new TestUBERStore();
store.load(uri, new char[] {'b'});
Assert.assertTrue(store.size() == 2);
Assert.assertTrue(store.contains("test1"));
Assert.assertTrue(store.contains("test2"));
// Remove...
mgr.removePassword("test1", new char[] { 'b' });
Assert.assertTrue(Arrays.equals(mgr.getPassword("test2", new char[] { 'b' }), new byte[] { '2' }));
try
{
mgr.getPassword("test1", new char[] {'b'});
Assert.fail("should not get here...");
}
catch (PasswordManager.PasswordNotFoundException e)
{
// expected...
}
store.load(uri, new char[] { 'b' });
Assert.assertTrue(store.size() == 1);
Assert.assertTrue(store.contains("test2"));
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Tests remove password behavior with a null alias.
*
* @throws Exception if test fails
*/
@Test public void testRemoveNullAlias() throws Exception
{
try
{
// BouncyCastle must be installed as a system security provider...
Security.addProvider(new BouncyCastleProvider());
PasswordManager mgr = new PasswordManager();
// Remove...
char[] pw = new char[] { 'f', 'o', 'o' };
mgr.removePassword(null, pw);
// Check that password is erased...
for (Character c : pw)
{
Assert.assertTrue(c == 0);
}
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Tests remove password behavior with empty password alias.
*
* @throws Exception if test fails
*/
@Test public void testRemoveEmptyAlias() throws Exception
{
try
{
// BouncyCastle must be installed as a system security provider...
Security.addProvider(new BouncyCastleProvider());
PasswordManager mgr = new PasswordManager();
// Remove...
char[] pw = new char[] { 'b', '
mgr.removePassword("", pw);
// Check that password is erased...
for (Character c : pw)
{
Assert.assertTrue(c == 0);
}
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Tests remove password behavior when store password is set to null.
*
* @throws Exception if test fails
*/
@Test public void testRemoveNullPassword() throws Exception
{
try
{
// BouncyCastle must be installed as a system security provider...
Security.addProvider(new BouncyCastleProvider());
URI uri = new URI("file", System.getProperty("user.dir") + "/test-" + UUID.randomUUID(), null);
File file = new File(uri);
file.deleteOnExit();
PasswordManager mgr = new PasswordManager(uri, new char[] { 'b' });
mgr.addPassword("test", new byte[] { '2' }, new char[] { 'b' });
// Remove...
try
{
mgr.removePassword("test", null);
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Tests remove password behavior when the store password is set to empty.
*
* @throws Exception if test fails
*/
@Test public void testRemoveEmptyPassword() throws Exception
{
try
{
// BouncyCastle must be installed as a system security provider...
Security.addProvider(new BouncyCastleProvider());
URI uri = new URI("file", System.getProperty("user.dir") + "/test-" + UUID.randomUUID(), null);
File file = new File(uri);
file.deleteOnExit();
PasswordManager mgr = new PasswordManager(uri, new char[] { 'b' });
mgr.addPassword("test", new byte[] { '2' }, new char[] { 'b' });
// Remove...
try
{
mgr.removePassword("test", new char[] { });
Assert.fail("should not get here...");
}
catch (KeyManager.KeyManagerException e)
{
// expected...
}
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Basic run through test.
*
* @throws Exception if test fails
*/
@Test public void testGetPassword() throws Exception
{
try
{
Security.addProvider(new BouncyCastleProvider());
PasswordManager mgr = new PasswordManager();
mgr.addPassword("testing", new byte[] { 'a', 'b' }, new char[] { '1' });
byte[] password = mgr.getPassword("testing", new char[] { '1' });
Assert.assertTrue(Arrays.equals(password, new byte[] { 'a', 'b'}));
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Test passwords above the ANSI range.
*
* @throws Exception if test fails
*/
@Test public void testGetPasswordSpecialCharacters() throws Exception
{
try
{
Security.addProvider(new BouncyCastleProvider());
PasswordManager mgr = new PasswordManager();
mgr.addPassword("testing1", "ä".getBytes(), new char[] { '1' });
byte[] password = mgr.getPassword("testing1", new char[] { '1' });
Assert.assertTrue(Arrays.equals(password, "ä".getBytes()));
mgr.addPassword("testing2", "∫".getBytes(), new char[] { '1' });
password = mgr.getPassword("testing2", new char[] { '1' });
Assert.assertTrue(Arrays.equals(password, "∫".getBytes()));
mgr.addPassword("testing3", "ç".getBytes(), new char[] { '1' });
password = mgr.getPassword("testing3", new char[] { '1' });
Assert.assertTrue(Arrays.equals(password, "ç".getBytes()));
mgr.addPassword("testing4", "".getBytes(), new char[] { '1' });
password = mgr.getPassword("testing4", new char[] { '1' });
Assert.assertTrue(Arrays.equals(password, "".getBytes()));
mgr.addPassword("testing5", "ä∫ç".getBytes(), new char[] { '1' });
password = mgr.getPassword("testing5", new char[] { '1' });
Assert.assertTrue(Arrays.equals(password, "ä∫ç".getBytes()));
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Test getPassword() with null alias.
*
* @throws Exception if test fails
*/
@Test public void testGetPasswordNullAlias() throws Exception
{
try
{
Security.addProvider(new BouncyCastleProvider());
URI uri = new URI("file", System.getProperty("user.dir") + "/test-" + UUID.randomUUID(), null);
File file = new File(uri);
file.deleteOnExit();
PasswordManager mgr = new PasswordManager(uri, new char[] { '0' });
try
{
mgr.getPassword(null, new char[] { '1' });
Assert.fail("should not get here...");
}
catch (PasswordManager.PasswordNotFoundException e)
{
// expected...
}
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Test getPassword() with empty alias.
*
* @throws Exception if test fails
*/
@Test public void testGetPasswordEmptyAlias() throws Exception
{
try
{
Security.addProvider(new BouncyCastleProvider());
URI uri = new URI("file", System.getProperty("user.dir") + "/test-" + UUID.randomUUID(), null);
File file = new File(uri);
file.deleteOnExit();
PasswordManager mgr = new PasswordManager(uri, new char[] { '1' });
try
{
mgr.getPassword("", new char[] { '1' });
Assert.fail("should not get here...");
}
catch (PasswordManager.PasswordNotFoundException e)
{
// expected...
}
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Test getPassword() with empty store master password.
*
* @throws Exception if test fails
*/
@Test public void testGetPasswordEmptyMasterPassword() throws Exception
{
try
{
Security.addProvider(new BouncyCastleProvider());
PasswordManager mgr = new PasswordManager();
try
{
mgr.getPassword("foo", new char[] { });
Assert.fail("should not get here...");
}
catch (PasswordManager.PasswordNotFoundException e)
{
// expected...
}
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Test getPassword() with null master password.
*
* @throws Exception if test fails
*/
@Test public void testGetPasswordNullMasterPassword() throws Exception
{
try
{
Security.addProvider(new BouncyCastleProvider());
PasswordManager mgr = new PasswordManager();
try
{
mgr.getPassword("foo", null);
Assert.fail("should not get here...");
}
catch (PasswordManager.PasswordNotFoundException e)
{
// expected...
}
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Test error handling behavior when the required keystore algorithm are not present.
*
* @throws Exception if test fails
*/
@Test public void testGetPasswordUnrecoverableError() throws Exception
{
try
{
Security.addProvider(new BouncyCastleProvider());
PasswordManager mgr = new PasswordManager();
mgr.addPassword("testing1", new byte[] { 'a' }, new char[] { '1' });
Security.removeProvider("BC");
try
{
mgr.getPassword("testing1", new char[] {'1'});
Assert.fail("could not get here...");
}
catch (PasswordManager.PasswordNotFoundException e)
{
// expected...
}
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Test error behavior when password manager is used to load a non-secret key keystore entry.
*
* @throws Exception if test fails
*/
@Test public void testGetPasswordNotASecretKey() throws Exception
{
try
{
Security.addProvider(new BouncyCastleProvider());
URI uri = new URI("file", System.getProperty("user.dir") + "/test-" + UUID.randomUUID(), null);
File file = new File(uri);
file.deleteOnExit();
PrivateKeyManager mgr = PrivateKeyManager.create();
mgr.createSelfSignedKey(
"test", new char[] { 'a' }, new BouncyCastleKeySigner(), "test"
);
mgr.save(new char[] { 'a' });
PasswordManager pwmgr = new PasswordManager(uri, new char[] { 'a' });
try
{
pwmgr.getPassword("test", new char[] { 'a' });
Assert.fail("could not get here...");
}
catch (PasswordManager.PasswordNotFoundException e)
{
// expected...
}
}
finally
{
Security.removeProvider("BC");
}
}
/**
* Basic run through of the defined exception constructors.
*/
@Test public void testCtor()
{
PasswordManager.PasswordNotFoundException e = new PasswordManager.PasswordNotFoundException("test");
Assert.assertTrue(e.getMessage().equals("test"));
Assert.assertTrue(e.getCause() == null);
e = new PasswordManager.PasswordNotFoundException("test {0}", "test");
Assert.assertTrue(e.getMessage().equals("test test"));
Assert.assertTrue(e.getCause() == null);
e = new PasswordManager.PasswordNotFoundException("test {0}", new Error("foo"));
Assert.assertTrue(e.getMessage().equals("test {0}"));
Assert.assertTrue(e.getCause() instanceof Error);
Assert.assertTrue(e.getCause().getMessage().equals("foo"));
e = new PasswordManager.PasswordNotFoundException("test {0}", new Error("foo"), "test");
Assert.assertTrue(e.getMessage().equals("test test"));
Assert.assertTrue(e.getCause() instanceof Error);
Assert.assertTrue(e.getCause().getMessage().equals("foo"));
}
private static class TestUBERStore extends KeyManager
{
private TestUBERStore() throws Exception
{
super(Storage.UBER, new BouncyCastleProvider());
}
}
} |
package devopsdistilled.operp.client.items.panes.controllers.impl;
import javax.inject.Inject;
import devopsdistilled.operp.client.items.exceptions.EntityNameExistsException;
import devopsdistilled.operp.client.items.exceptions.NullFieldException;
import devopsdistilled.operp.client.items.panes.CreateManufacturerPane;
import devopsdistilled.operp.client.items.panes.controllers.CreateManufacturerPaneController;
import devopsdistilled.operp.client.items.panes.models.CreateManufacturerPaneModel;
import devopsdistilled.operp.server.data.entity.items.Manufacturer;
public class CreateManufacturerPaneControllerImpl implements
CreateManufacturerPaneController {
@Inject
private CreateManufacturerPane view;
@Inject
private CreateManufacturerPaneModel model;
@Override
public void validate(Manufacturer entity) throws NullFieldException,
EntityNameExistsException {
// TODO Auto-generated method stub
}
@Override
public Manufacturer save(Manufacturer entity) {
// TODO Auto-generated method stub
return null;
}
@Override
public void init() {
view.init();
model.registerObserver(view);
}
} |
package org.psjava.example.algo;
import junit.framework.Assert;
import org.junit.Test;
import org.psjava.algo.graph.KonigTheorem;
import org.psjava.algo.graph.MinimumVertexCoverAlgorithmInBipartiteGraph;
import org.psjava.algo.graph.matching.HopcroftKarpAlgorithm;
import org.psjava.algo.graph.matching.MaximumBipartiteMatchingResult;
import org.psjava.ds.graph.MutableBipartiteGraph;
/**
* @implementation {@link org.psjava.algo.graph.KonigTheorem}
*
* @see {@link org.psjava.example.algo.MaximumBipartiteMatchingExample}
* @see {@link org.psjava.example.algo.MinimumVertexCoverInBipartiteGraphExample}
*/
public class KonigTheoremExample {
@Test
public void example() {
MutableBipartiteGraph<String> g = MutableBipartiteGraph.create();
g.insertLeftVertex("A");
g.insertLeftVertex("B");
g.insertLeftVertex("C");
g.insertRightVertex("X");
g.insertRightVertex("Y");
g.insertRightVertex("Z");
g.addEdge("A", "X");
g.addEdge("A", "Y");
g.addEdge("A", "Z");
g.addEdge("B", "Z");
g.addEdge("C", "Z");
// By Konig's Theorem, In any bipartite graph, the number of edges in a maximum matching equals the number of vertices in a minimum vertex cover.
// So matching algorithm is used in it's implementation. In this example, Hopcroft-Karp algorithm is used.
MinimumVertexCoverAlgorithmInBipartiteGraph algorithm = KonigTheorem.getInstance(HopcroftKarpAlgorithm.getInstance());
int number = algorithm.calcMinimumVertexCover(g); // result is 2, ("A", "C")
Assert.assertEquals(2, number);
}
} |
package gov.hhs.fha.nhinc.callback.openSAML;
import com.sun.org.apache.xml.internal.security.keys.KeyInfo;
import com.sun.xml.wss.XWSSecurityException;
import java.io.*;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableEntryException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.*;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;
import java.security.cert.Certificate;
import java.security.interfaces.RSAPublicKey;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.UnsupportedCallbackException;
import com.sun.xml.wss.impl.callback.*;
import com.sun.xml.wss.saml.*;
import gov.hhs.fha.nhinc.callback.SamlConstants;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import gov.hhs.fha.nhinc.properties.PropertyAccessException;
import gov.hhs.fha.nhinc.properties.PropertyAccessor;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import org.opensaml.Configuration;
import org.opensaml.common.SAMLObjectBuilder;
import org.opensaml.saml2.core.Issuer;
import org.opensaml.saml2.core.Statement;
/*import org.opensaml.saml2.core.impl.AssertionBuilder;
import org.opensaml.saml2.core.impl.IssuerBuilder;
import org.opensaml.saml2.core.impl.NameIDBuilder;
import org.opensaml.saml2.core.impl.SubjectBuilder;
import org.opensaml.saml2.core.impl.SubjectConfirmationBuilder;
import org.opensaml.saml2.core.impl.SubjectConfirmationDataBuilder;*/
import org.opensaml.xml.XMLObject;
import org.opensaml.xml.XMLObjectBuilderFactory;
import org.opensaml.xml.signature.Exponent;
import org.opensaml.xml.signature.Modulus;
import org.opensaml.xml.signature.RSAKeyValue;
/*import org.opensaml.xml.signature.impl.ExponentBuilder;
import org.opensaml.xml.signature.impl.KeyInfoBuilder;
import org.opensaml.xml.signature.impl.KeyValueBuilder;
import org.opensaml.xml.signature.impl.ModulusBuilder;
import org.opensaml.xml.signature.impl.RSAKeyValueBuilder;*/
import org.opensaml.saml2.core.AuthnStatement;
import org.opensaml.saml2.core.AuthnContext;
import org.opensaml.saml2.core.AuthnContextClassRef;
import org.opensaml.saml2.core.AttributeStatement;
import org.opensaml.saml2.core.Attribute;
import org.opensaml.saml2.core.SubjectLocality;
import org.w3c.dom.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.security.auth.x500.X500Principal;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* This class implements the CallbackHandler which is invoked upon sending a message requiring the SAML Assertion Token.
* It accesses the information stored in NMProperties in order to build up the required token elements.
*/
public class OpenSAMLCallbackHandler implements CallbackHandler {
private static Log log = LogFactory.getLog(OpenSAMLCallbackHandler.class);
// Valid Evidence Assertion versions
private static final String ASSERTION_VERSION_2_0 = "2.0";
private static final String[] VALID_ASSERTION_VERSION_ARRAY = { ASSERTION_VERSION_2_0 };
private static final List<String> VALID_ASSERTION_VERSION_LIST = Collections.unmodifiableList(Arrays
.asList(VALID_ASSERTION_VERSION_ARRAY));
// Valid Authorization Decision values
private static final String AUTHZ_DECISION_PERMIT = "Permit";
private static final String AUTHZ_DECISION_DENY = "Deny";
private static final String AUTHZ_DECISION_INDETERMINATE = "Indeterminate";
private static final String[] VALID_AUTHZ_DECISION_ARRAY = { AUTHZ_DECISION_PERMIT, AUTHZ_DECISION_DENY,
AUTHZ_DECISION_INDETERMINATE };
private static final List<String> VALID_AUTHZ_DECISION_LIST = Collections.unmodifiableList(Arrays
.asList(VALID_AUTHZ_DECISION_ARRAY));
// Authorization Decision Action is always set to Execute
private static final String AUTHZ_DECISION_ACTION_EXECUTE = "Execute";
private static final String AUTHZ_DECISION_ACTION_NS = "urn:oasis:names:tc:SAML:1.0:action:rwedc";
// Valid Name Identification values
private static final String UNSPECIFIED_NAME_ID = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified";
private static final String EMAIL_NAME_ID = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress";
private static final String X509_NAME_ID = "urn:oasis:names:tc:SAML:1.1:nameid-format:X509SubjectName";
private static final String WINDOWS_NAME_ID = "urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName";
private static final String KERBEROS_NAME_ID = "urn:oasis:names:tc:SAML:1.1:nameid-format:kerberos";
private static final String ENTITY_NAME_ID = "urn:oasis:names:tc:SAML:1.1:nameid-format:entity";
private static final String PERSISTENT_NAME_ID = "urn:oasis:names:tc:SAML:1.1:nameid-format:persistent";
private static final String TRANSIENT_NAME_ID = "urn:oasis:names:tc:SAML:1.1:nameid-format:transient";
private static final String[] VALID_NAME_ID_ARRAY = { UNSPECIFIED_NAME_ID, EMAIL_NAME_ID, X509_NAME_ID,
WINDOWS_NAME_ID, KERBEROS_NAME_ID, ENTITY_NAME_ID, PERSISTENT_NAME_ID, TRANSIENT_NAME_ID };
private static final List<String> VALID_NAME_LIST = Collections
.unmodifiableList(Arrays.asList(VALID_NAME_ID_ARRAY));
// Valid Context Class references
private static final String INTERNET_AUTHN_CNTX_CLS = "urn:oasis:names:tc:SAML:2.0:ac:classes:InternetProtocol";
private static final String INTERNET_PASSWORD_AUTHN_CNTX_CLS = "urn:oasis:names:tc:SAML:2.0:ac:classes:InternetProtocolPassword";
private static final String PASSWORD_AUTHN_CNTX_CLS = "urn:oasis:names:tc:SAML:2.0:ac:classes:Password";
private static final String PASSWORD_TRANS_AUTHN_CNTX_CLS = "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport";
private static final String KERBEROS_AUTHN_CNTX_CLS = "urn:oasis:names:tc:SAML:2.0:ac:classes:Kerberos";
private static final String PREVIOUS_AUTHN_CNTX_CLS = "urn:oasis:names:tc:SAML:2.0:ac:classes:PreviousSession";
private static final String REMOTE_AUTHN_CNTX_CLS = "urn:oasis:names:tc:SAML:2.0:ac:classes:SecureRemotePassword";
private static final String TLS_AUTHN_CNTX_CLS = "urn:oasis:names:tc:SAML:2.0:ac:classes:TLSClient";
private static final String X509_AUTHN_CNTX_CLS = "urn:oasis:names:tc:SAML:2.0:ac:classes:X509";
private static final String PGP_AUTHN_CNTX_CLS = "urn:oasis:names:tc:SAML:2.0:ac:classes:PGP";
private static final String SPKI_AUTHN_CNTX_CLS = "urn:oasis:names:tc:SAML:2.0:ac:classes:SPKI";
private static final String DIG_SIGN_AUTHN_CNTX_CLS = "urn:oasis:names:tc:SAML:2.0:ac:classes:XMLDSig";
private static final String UNSPECIFIED_AUTHN_CNTX_CLS = "urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified";
private static final String[] VALID_AUTHN_CNTX_CLS_ARRAY = { INTERNET_AUTHN_CNTX_CLS,
INTERNET_PASSWORD_AUTHN_CNTX_CLS, PASSWORD_AUTHN_CNTX_CLS, PASSWORD_TRANS_AUTHN_CNTX_CLS,
KERBEROS_AUTHN_CNTX_CLS, PREVIOUS_AUTHN_CNTX_CLS, REMOTE_AUTHN_CNTX_CLS, TLS_AUTHN_CNTX_CLS,
X509_AUTHN_CNTX_CLS, PGP_AUTHN_CNTX_CLS, SPKI_AUTHN_CNTX_CLS, DIG_SIGN_AUTHN_CNTX_CLS,
UNSPECIFIED_AUTHN_CNTX_CLS };
private static final List<String> VALID_AUTHN_CNTX_CLS_LIST = Collections.unmodifiableList(Arrays
.asList(VALID_AUTHN_CNTX_CLS_ARRAY));
private static final String AUTHN_SESSION_INDEX = "123456";
public static final String HOK_CONFIRM = "urn:oasis:names:tc:SAML:2.0:cm:holder-of-key";
public static final String SV_CONFIRM = "urn:oasis:names:tc:SAML:2.0:cm:authorization-over-ssl";
private static final String NHIN_NS = "http:
private static final String HL7_NS = "urn:hl7-org:v3";
private static final int DEFAULT_NAME = 0;
private static final int PRIMARY_NAME = 1;
private HashMap<Object, Object> tokenVals = new HashMap<Object, Object>();
private KeyStore keyStore;
private KeyStore trustStore;
private static Element svAssertion;
private static Element hokAssertion20;
private static HashMap<String, String> factoryVersionMap = new HashMap<String, String>();
private static final String ID_PREFIX = "_";
private static final String PURPOSE_FOR_USE_DEPRECATED_ENABLED = "purposeForUseEnabled";
private static final String DEFAULT_ISSUER_VALUE = "CN=SAML User,OU=SU,O=SAML User,L=Los Angeles,ST=CA,C=US";
private static SAMLObjectBuilder<AuthnStatement> authnStatementBuilder;
private static SAMLObjectBuilder<AuthnContext> authnContextBuilder;
private static SAMLObjectBuilder<AuthnContextClassRef> authnContextClassRefBuilder;
private static SAMLObjectBuilder<AttributeStatement> attributeStatementBuilder;
private static SAMLObjectBuilder<Attribute> attributeBuilder;
private static SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
private static XMLObjectBuilderFactory builderFactory = Configuration.getBuilderFactory();
private static final DateTimeFormatter XML_DATE_TIME_FORMAT = ISODateTimeFormat.dateTimeNoMillis();
static {
// WORKAROUND NEEDED IN METRO1.4. TO BE REMOVED LATER.
javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
public boolean verify(String hostname, javax.net.ssl.SSLSession sslSession) {
return true;
}
});
// Set up versioning mapping - currently only support 2.0
factoryVersionMap.put(ASSERTION_VERSION_2_0, SAMLAssertionFactory.SAML2_0);
}
/**
* Constructs the callback handler and initializes the keystore and truststore references to the security
* certificates
*/
public OpenSAMLCallbackHandler() {
log.debug("SamlCallbackHandler Constructor -- Begin");
try {
initKeyStore();
initTrustStore();
} catch (IOException e) {
log.error("SamlCallbackHandler Exception: " + e.getMessage());
e.printStackTrace();
throw new RuntimeException(e);
}
log.debug("SamlCallbackHandler Constructor -- Begin");
}
private XMLObject createOpenSAMLObject(QName qname) {
return Configuration.getBuilderFactory().getBuilder(qname).buildObject(qname);
}
/**
* This is the invoked implementation to handle the SAML Token creation upon notification of an outgoing message
* needing SAML. Based on the type of confirmation method detected on the Callbace it creates either a
* "Sender Vouches: or a "Holder-ok_Key" variant of the SAML Assertion.
*
* @param callbacks The SAML Callback
* @throws java.io.IOException
* @throws javax.security.auth.callback.UnsupportedCallbackException
*/
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
log.debug(" ********************************** Handle SAML Callback Begin **************************");
for (int i = 0; i < callbacks.length; i++) {
if (callbacks[i] instanceof SAMLCallback) {
SAMLCallback samlCallback = (SAMLCallback) callbacks[i];
log.debug("=============== Print Runtime properties =============");
tokenVals.putAll(samlCallback.getRuntimeProperties());
log.debug(tokenVals);
log.debug("=============== Completed Print properties =============");
if (samlCallback.getConfirmationMethod().equals(SAMLCallback.HOK_ASSERTION_TYPE)) {
samlCallback.setAssertionElement(createHOKSAMLAssertion20());
hokAssertion20 = samlCallback.getAssertionElement();
} else if (samlCallback.getConfirmationMethod().equals(SAMLCallback.SV_ASSERTION_TYPE)) {
samlCallback.setAssertionElement(createSVSAMLAssertion20());
svAssertion = samlCallback.getAssertionElement();
} else {
log.error("Unknown SAML Assertion Type: " + samlCallback.getConfirmationMethod());
throw new UnsupportedCallbackException(null, "SAML Assertion Type is not matched:"
+ samlCallback.getConfirmationMethod());
}
} else {
log.error("Unknown Callback encountered: " + callbacks[i]);
throw new UnsupportedCallbackException(null, "Unsupported Callback Type Encountered");
}
}
log.debug("********************************** Handle SAML Callback End **************************");
}
/**
* Currently not Used. Creates the "Sender Vouches" variant of the SAML Assertion token.
*
* @return The Assertion element
*/
private Element createSVSAMLAssertion20() {
log.debug("SamlCallbackHandler.createSVSAMLAssertion20() -- Begin");
Assertion assertion = null;
try {
SAMLAssertionFactory factory = SAMLAssertionFactory.newInstance(SAMLAssertionFactory.SAML2_0);
// create the assertion id
// Per GATEWAY-847 the id attribute should not be allowed to start
// with a number (UUIDs can). Direction
// given from 2011 specification set was to prepend with and
// underscore.
String aID = ID_PREFIX.concat(String.valueOf(UUID.randomUUID()));
log.debug("Assertion ID: " + aID);
// name id of the issuer - For now just use default
NameID issueId = create509NameID(factory, DEFAULT_NAME);
// issue instant
GregorianCalendar issueInstant = calendarFactory();
// name id of the subject - user name
String uname = "defUser";
if (tokenVals.containsKey(SamlConstants.USER_NAME_PROP)
&& tokenVals.get(SamlConstants.USER_NAME_PROP) != null) {
uname = tokenVals.get(SamlConstants.USER_NAME_PROP).toString();
}
NameID nmId = factory.createNameID(uname, null, X509_NAME_ID);
Subject subj = factory.createSubject(nmId, null);
// authentication statement
List statements = createAuthnStatements(factory);
assertion = factory.createAssertion(aID, issueId, issueInstant, null, null, subj, statements);
assertion.setVersion("2.0");
log.debug("createSVSAMLAssertion20 end ()");
return assertion.toElement(null);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* Creates the "Holder-of-Key" variant of the SAML Assertion token.
*
* @return The Assertion element
*/
private Element createHOKSAMLAssertion20() {
log.debug("SamlCallbackHandler.createHOKSAMLAssertion20() -- Begin");
org.opensaml.saml2.core.Assertion ass = null;
try {
ass = (org.opensaml.saml2.core.Assertion) createOpenSAMLObject(org.opensaml.saml2.core.Assertion.DEFAULT_ELEMENT_NAME);
// create the assertion id
// Per GATEWAY-847 the id attribute should not be allowed to start
// with a number (UUIDs can). Direction
// given from 2011 specification set was to prepend with and
// underscore.
String aID = ID_PREFIX.concat(String.valueOf(UUID.randomUUID()));
log.debug("Assertion ID: " + aID);
// set assertion Id
ass.setID(aID);
// issue instant set to now.
DateTime issueInstant = new DateTime();
ass.setIssueInstant(issueInstant);
// set issuer
ass.setIssuer(createIssuer());
// set subject
ass.setSubject(createSubject());
// add attribute statements
ass.getStatements().addAll(createAttributeStatements());
// TODO: need to sign the message
} catch (Exception ex) {
log.error("Unable to create HOK Assertion: " + ex.getMessage());
ex.printStackTrace();
}
log.debug("SamlCallbackHandler.createHOKSAMLAssertion20() -- End");
return null;
}
/**
* @return
*/
@SuppressWarnings("unchecked")
private List<Statement> createAttributeStatements() {
List<Statement> statements = new ArrayList<Statement>();
statements.addAll(createAuthenicationStatements());
return statements;
}
/**
* @return
*/
private List<AuthnStatement> createAuthenicationStatements() {
List<AuthnStatement> authnStatements = new ArrayList<AuthnStatement>();
if (authnStatementBuilder == null) {
authnStatementBuilder = (SAMLObjectBuilder<AuthnStatement>) builderFactory
.getBuilder(AuthnStatement.DEFAULT_ELEMENT_NAME);
}
if (authnContextBuilder == null) {
authnContextBuilder = (SAMLObjectBuilder<AuthnContext>) builderFactory
.getBuilder(AuthnContext.DEFAULT_ELEMENT_NAME);
}
if (authnContextClassRefBuilder == null) {
authnContextClassRefBuilder = (SAMLObjectBuilder<AuthnContextClassRef>) builderFactory
.getBuilder(AuthnContextClassRef.DEFAULT_ELEMENT_NAME);
}
if (subjectLocalityBuilder == null) {
subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) builderFactory
.getBuilder(SubjectLocality.DEFAULT_ELEMENT_NAME);
}
AuthnStatement authnStatement = authnStatementBuilder.buildObject();
AuthnContextClassRef authnContextClassRef = authnContextClassRefBuilder.buildObject();
String cntxCls = getNullSafeString(tokenVals, SamlConstants.AUTHN_CONTEXT_CLASS_PROP);
if (cntxCls != null) {
if (VALID_AUTHN_CNTX_CLS_LIST.contains(cntxCls.trim())) {
log.debug("Create Authentication Context Class as: " + cntxCls);
authnContextClassRef.setAuthnContextClassRef(cntxCls);
} else {
log.debug(cntxCls + " is not recognized as valid, "
+ "create default Authentication Context Class as: " + UNSPECIFIED_AUTHN_CNTX_CLS);
log.debug("Should be one of: " + VALID_AUTHN_CNTX_CLS_LIST);
authnContextClassRef.setAuthnContextClassRef(UNSPECIFIED_AUTHN_CNTX_CLS);
}
} else {
log.debug("Create default Authentication Context Class as: " + X509_AUTHN_CNTX_CLS);
authnContextClassRef.setAuthnContextClassRef(X509_AUTHN_CNTX_CLS);
}
AuthnContext authnContext = authnContextBuilder.buildObject();
authnContext.setAuthnContextClassRef(authnContextClassRef);
authnStatement.setAuthnContext(authnContext);
String sessionIndex = getNullSafeString(tokenVals, SamlConstants.AUTHN_SESSION_INDEX_PROP, AUTHN_SESSION_INDEX);
log.debug("Setting Authentication session index to: " + sessionIndex);
authnStatement.setSessionIndex(sessionIndex);
String instantText = getNullSafeString(tokenVals, SamlConstants.AUTHN_INSTANT_PROP);
DateTime authInstant = new DateTime();
if (instantText != null) {
authInstant = XML_DATE_TIME_FORMAT.parseDateTime(instantText);
} else {
log.debug("Defaulting Authentication instant to current time");
}
authnStatement.setAuthnInstant(authInstant);
String inetAddr = getNullSafeString(tokenVals, SamlConstants.SUBJECT_LOCALITY_ADDR_PROP);
String dnsName = getNullSafeString(tokenVals, SamlConstants.SUBJECT_LOCALITY_DNS_PROP);
if (inetAddr != null && dnsName != null) {
log.debug("Create Subject Locality as " + inetAddr + " in domain: " + dnsName);
SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
subjectLocality.setDNSName(dnsName);
subjectLocality.setAddress(inetAddr);
authnStatement.setSubjectLocality(subjectLocality);
}
authnStatements.add(authnStatement);
return authnStatements;
}
private String getNullSafeString(Map map, final String property) {
return getNullSafeString(map, property, null);
}
private String getNullSafeString(Map map, final String property, String defaultValue) {
String value = defaultValue;
if (map.containsKey(property) && map.get(property) != null) {
value = map.get(property).toString();
}
return value;
}
/**
* @return
*/
private org.opensaml.saml2.core.Subject createSubject() {
org.opensaml.saml2.core.Subject subject = (org.opensaml.saml2.core.Subject) createOpenSAMLObject(org.opensaml.saml2.core.Subject.DEFAULT_ELEMENT_NAME);
String x509Name = "UID=" + tokenVals.get(SamlConstants.USER_NAME_PROP).toString();
subject.setNameID(createNameID(X509_NAME_ID, x509Name));
subject.getSubjectConfirmations().add(createHoKConfirmation());
return subject;
}
private org.opensaml.saml2.core.SubjectConfirmation createHoKConfirmation() {
org.opensaml.saml2.core.SubjectConfirmation subjectConfirmation = (org.opensaml.saml2.core.SubjectConfirmation) createOpenSAMLObject(org.opensaml.saml2.core.SubjectConfirmation.DEFAULT_ELEMENT_NAME);
subjectConfirmation.setMethod(org.opensaml.saml2.core.SubjectConfirmation.METHOD_HOLDER_OF_KEY);
subjectConfirmation.setSubjectConfirmationData(createSubjectConfirmationData());
return subjectConfirmation;
}
private org.opensaml.saml2.core.SubjectConfirmationData createSubjectConfirmationData() {
org.opensaml.saml2.core.SubjectConfirmationData subjectConfirmationData = (org.opensaml.saml2.core.SubjectConfirmationData) createOpenSAMLObject(org.opensaml.saml2.core.SubjectConfirmationData.DEFAULT_ELEMENT_NAME);
subjectConfirmationData.getUnknownAttributes().put(
new QName("http:
"saml:KeyInfoConfirmationDataType");
org.opensaml.xml.signature.KeyInfo ki = (org.opensaml.xml.signature.KeyInfo) createOpenSAMLObject(org.opensaml.xml.signature.KeyInfo.DEFAULT_ELEMENT_NAME);
org.opensaml.xml.signature.KeyValue kv = (org.opensaml.xml.signature.KeyValue) createOpenSAMLObject(org.opensaml.xml.signature.KeyValue.DEFAULT_ELEMENT_NAME);
RSAKeyValue _RSAKeyValue = (RSAKeyValue) createOpenSAMLObject(RSAKeyValue.DEFAULT_ELEMENT_NAME);
Exponent arg0 = (Exponent) createOpenSAMLObject(Exponent.DEFAULT_ELEMENT_NAME);
Modulus arg1 = (Modulus) createOpenSAMLObject(Modulus.DEFAULT_ELEMENT_NAME);
RSAPublicKey RSAPk = (RSAPublicKey)getPublicKey();
arg0.setValue(RSAPk.getPublicExponent().toString());
_RSAKeyValue.setExponent(arg0);
arg1.setValue(RSAPk.getModulus().toString());
_RSAKeyValue.setModulus(arg1);
kv.setRSAKeyValue(_RSAKeyValue);
ki.getKeyValues().add(kv);
subjectConfirmationData.getUnknownXMLObjects().add(ki);
return subjectConfirmationData;
}
public PublicKey getPublicKey()
{
KeyStore ks;
KeyStore.PrivateKeyEntry pkEntry = null;
try {
ks = KeyStore.getInstance(KeyStore.getDefaultType());
char[] password = "cspass".toCharArray();
FileInputStream fis = new FileInputStream("c:/opt/keystores/clientKeystore.jks");
ks.load(fis, password);
fis.close();
pkEntry = (KeyStore.PrivateKeyEntry) ks.getEntry("myclientkey",
new KeyStore.PasswordProtection("ckpass".toCharArray()));
} catch (KeyStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (CertificateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnrecoverableEntryException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
X509Certificate certificate = (X509Certificate) pkEntry.getCertificate();
return certificate.getPublicKey();
}
/**
* @return
*/
private org.opensaml.saml2.core.NameID createNameID(String format, String value) {
org.opensaml.saml2.core.NameID nameId = (org.opensaml.saml2.core.NameID) createOpenSAMLObject(org.opensaml.saml2.core.NameID.DEFAULT_ELEMENT_NAME);
nameId.setFormat(format);
nameId.setValue(value);
return nameId;
}
public org.opensaml.saml2.core.Issuer createIssuer() {
Issuer issuer = null;
if (tokenVals.containsKey(SamlConstants.ASSERTION_ISSUER_FORMAT_PROP)
&& tokenVals.containsKey(SamlConstants.ASSERTION_ISSUER_PROP)) {
String format = tokenVals.get(SamlConstants.ASSERTION_ISSUER_FORMAT_PROP).toString();
log.debug("Setting Assertion Issuer format to: " + format);
String sIssuer = tokenVals.get(SamlConstants.ASSERTION_ISSUER_PROP).toString();
log.debug("Setting Assertion Issuer to: " + sIssuer);
if (VALID_NAME_LIST.contains(format.trim())) {
issuer = (Issuer) createOpenSAMLObject(Issuer.DEFAULT_ELEMENT_NAME);
issuer.setFormat(format);
issuer.setValue(sIssuer);
} else {
log.debug("Not in valid listing of formats: Using default issuer");
issuer = createDefaultIssuer();
}
} else {
log.debug("Assertion issuer not defined: Using default issuer");
issuer = createDefaultIssuer();
}
return issuer;
}
protected org.opensaml.saml2.core.Issuer createDefaultIssuer() {
Issuer issuer = (Issuer) createOpenSAMLObject(Issuer.DEFAULT_ELEMENT_NAME);
issuer.setFormat(X509_NAME_ID);
issuer.setValue(DEFAULT_ISSUER_VALUE);
return issuer;
}
private NameID create509NameID(SAMLAssertionFactory factory, int assId) throws SAMLException {
log.debug("SamlCallbackHandler.create509NameID() -- Begin: " + assId);
NameID nmId = null;
String defCN = "SAML User";
String defOU = "SU";
String defO = "SAML User";
String defL = "Los Angeles";
String defST = "CA";
String defC = "US";
String identifier;
if (assId != PRIMARY_NAME || !tokenVals.containsKey(SamlConstants.USER_NAME_PROP)
|| tokenVals.get(SamlConstants.USER_NAME_PROP) == null) {
identifier = "CN=" + defCN + "," + "OU=" + defOU + "," + "O=" + defO + "," + "L=" + defL + "," + "ST="
+ defST + "," + "C=" + defC;
nmId = factory.createNameID(identifier, null, X509_NAME_ID);
log.debug("Create default X509 name: " + identifier);
} else {
String x509Name = "UID=" + tokenVals.get(SamlConstants.USER_NAME_PROP).toString();
try {
X500Principal prin = new X500Principal(x509Name);
nmId = factory.createNameID(x509Name, null, X509_NAME_ID);
log.debug("Create X509 name: " + x509Name);
} catch (IllegalArgumentException iae) {
/* Could also test if email form if we wanted to support that */
log.warn("Set format as Unspecified. Invalid X509 format: "
+ tokenVals.get(SamlConstants.USER_NAME_PROP) + " " + iae.getMessage());
nmId = factory.createNameID(tokenVals.get(SamlConstants.USER_NAME_PROP).toString(), null,
UNSPECIFIED_NAME_ID);
}
}
log.debug("SamlCallbackHandler.create509NameID() -- End: " + nmId.getValue());
return nmId;
}
/*
* public boolean isValidEmailAddress(String address) { log.debug("SamlCallbackHandler.isValidEmailAddress() " +
* address + " -- Begin"); boolean retBool = false; if (address != null && address.length() > 0) { try {
* InternetAddress emailAddr = new InternetAddress(address, true); String[] tokens = address.split("@"); if
* (tokens.length == 2 && tokens[0].trim().length() > 0 && tokens[1].trim().length() > 0) { retBool = true; } else {
* log.debug("Address does not follow the form 'local-part@domain'"); } } catch (AddressException ex) { // address
* does not comply with RFC822 log.debug("Address is not of the RFC822 format"); } }
* log.debug("SamlCallbackHandler.isValidEmailAddress() " + retBool + " -- End"); return retBool; }
*/
/**
* Creates the authentication statement, the attribute statements, and the authorization decision statements for
* placement in the SAML Assertion.
*
* @param factory The factory object used to assist in the construction of the SAML Assertion token
* @param issueInstant The calendar representing the time of Assertion issuance
* @return A listing of all statements
* @throws com.sun.xml.wss.saml.SAMLException
*/
private List createAuthnStatements(SAMLAssertionFactory factory) throws SAMLException, XWSSecurityException {
log.debug("SamlCallbackHandler.createAuthnStatements() -- Begin");
List statements = new ArrayList();
statements.addAll(addAssertStatements(factory));
// The authorization Decision Statement is optional
if (tokenVals.containsKey(SamlConstants.AUTHZ_STATEMENT_EXISTS_PROP)
&& tokenVals.get(SamlConstants.AUTHZ_STATEMENT_EXISTS_PROP) != null
&& "true".equalsIgnoreCase(tokenVals.get(SamlConstants.AUTHZ_STATEMENT_EXISTS_PROP).toString())) {
// Create resource for Authentication Decision Statement
String resource = null;
if (tokenVals.containsKey(SamlConstants.RESOURCE_PROP)
&& tokenVals.get(SamlConstants.RESOURCE_PROP) != null) {
resource = tokenVals.get(SamlConstants.RESOURCE_PROP).toString();
log.debug("Setting Authentication Decision Resource to: " + resource);
} else {
log.debug("Default Authentication Decision Resource is: " + resource);
}
// Options are Permit, Deny and Indeterminate
String decision = AUTHZ_DECISION_PERMIT;
if (tokenVals.containsKey(SamlConstants.AUTHZ_DECISION_PROP)
&& tokenVals.get(SamlConstants.AUTHZ_DECISION_PROP) != null) {
String requestedDecision = tokenVals.get(SamlConstants.AUTHZ_DECISION_PROP).toString().trim();
if (VALID_AUTHZ_DECISION_LIST.contains(requestedDecision)) {
log.debug("Setting Authentication Decision to: " + requestedDecision);
decision = requestedDecision;
} else {
log.debug(requestedDecision + " is not recognized as valid, "
+ "create default Authentication Decision as: " + AUTHZ_DECISION_PERMIT);
log.debug("Should be one of: " + VALID_AUTHZ_DECISION_LIST);
}
} else {
log.debug("Create default Authentication Decision as: " + AUTHZ_DECISION_PERMIT);
}
// As of Authorization Framework Spec 2.2 Action is a hard-coded
// value
// Therefore the value of the ACTION_PROP is no longer used
List actions = new ArrayList();
String actionAttr = AUTHZ_DECISION_ACTION_EXECUTE;
log.debug("Setting Authentication Decision Action to: " + actionAttr);
try {
final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
final Element elemURAttr = document.createElementNS("urn:oasis:names:tc:SAML:2.0:assertion", "Action");
elemURAttr.setAttribute("Namespace", AUTHZ_DECISION_ACTION_NS);
elemURAttr.setTextContent(actionAttr);
actions.add(elemURAttr);
} catch (ParserConfigurationException ex) {
actions.add(actionAttr);
}
// Evidence Assertion generation
Evidence evidence = createEvidence();
AuthnDecisionStatement authDecState = factory.createAuthnDecisionStatement(resource, decision, actions,
evidence);
if (authDecState != null) {
statements.add(authDecState);
}
} else {
log.info("Authorization Decision statement is not specified");
}
log.debug("SamlCallbackHandler.createAuthnStatements() -- End");
return statements;
}
/**
* Creates the Attribute statements for UserName, UserOrganization, UserRole, and PurposeOfUse
*
* @param factory The factory object used to assist in the construction of the SAML Assertion token
* @return The listing of all Attribute statements
* @throws com.sun.xml.wss.saml.SAMLException
*/
private List addAssertStatements(SAMLAssertionFactory factory) throws SAMLException {
log.debug("SamlCallbackHandler.addAssertStatements() -- Begin");
List statements = new ArrayList();
List attributes = new ArrayList();
// Set the User Name Attribute
List attributeValues1 = new ArrayList();
StringBuffer nameConstruct = new StringBuffer();
if (tokenVals.containsKey(SamlConstants.USER_FIRST_PROP)
&& tokenVals.get(SamlConstants.USER_FIRST_PROP) != null) {
nameConstruct.append(tokenVals.get(SamlConstants.USER_FIRST_PROP).toString() + " ");
}
if (tokenVals.containsKey(SamlConstants.USER_MIDDLE_PROP)
&& tokenVals.get(SamlConstants.USER_MIDDLE_PROP) != null) {
nameConstruct.append(tokenVals.get(SamlConstants.USER_MIDDLE_PROP).toString() + " ");
}
if (tokenVals.containsKey(SamlConstants.USER_LAST_PROP) && tokenVals.get(SamlConstants.USER_LAST_PROP) != null) {
nameConstruct.append(tokenVals.get(SamlConstants.USER_LAST_PROP).toString() + " ");
}
if (nameConstruct.length() > 0) {
if (nameConstruct.charAt(nameConstruct.length() - 1) == ' ') {
nameConstruct.setLength(nameConstruct.length() - 1);
}
log.debug("UserName: " + nameConstruct.toString());
attributeValues1.add(nameConstruct.toString());
attributes.add(factory.createAttribute(SamlConstants.USERNAME_ATTR, attributeValues1));
} else {
log.warn("No information provided to fill in user name attribute");
}
// Set the User Organization Attribute
List attributeValues2 = new ArrayList();
if (tokenVals.containsKey(SamlConstants.USER_ORG_PROP) && tokenVals.get(SamlConstants.USER_ORG_PROP) != null) {
log.debug("UserOrg: " + tokenVals.get(SamlConstants.USER_ORG_PROP).toString());
attributeValues2.add(tokenVals.get(SamlConstants.USER_ORG_PROP).toString());
attributes.add(factory.createAttribute(SamlConstants.USER_ORG_ATTR, attributeValues2));
} else {
log.warn("No information provided to fill in user organization attribute");
}
// Set the User Organization ID Attribute
List attributeValues5 = new ArrayList();
if (tokenVals.containsKey(SamlConstants.USER_ORG_ID_PROP)
&& tokenVals.get(SamlConstants.USER_ORG_ID_PROP) != null) {
log.debug("UserOrgID: " + tokenVals.get(SamlConstants.USER_ORG_ID_PROP).toString());
attributeValues5.add(tokenVals.get(SamlConstants.USER_ORG_ID_PROP).toString());
attributes.add(factory.createAttribute(SamlConstants.USER_ORG_ID_ATTR, attributeValues5));
} else {
log.warn("No information provided to fill in user organization ID attribute");
}
// Set the Home Community ID Attribute
List attributeValues6 = new ArrayList();
if (tokenVals.containsKey(SamlConstants.HOME_COM_PROP) && tokenVals.get(SamlConstants.HOME_COM_PROP) != null) {
log.debug("HomeCommunityID: " + tokenVals.get(SamlConstants.HOME_COM_PROP).toString());
attributeValues6.add(tokenVals.get(SamlConstants.HOME_COM_PROP).toString());
attributes.add(factory.createAttribute(SamlConstants.HOME_COM_ID_ATTR, attributeValues6));
} else {
log.warn("No information provided to fill in home community ID attribute");
}
try {
// Set the User Role Attribute
List attributeValues3 = new ArrayList();
final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
final Element elemURAttr = document.createElementNS("urn:oasis:names:tc:SAML:2.0:assertion",
"AttibuteValue");
final Element userRole = document.createElementNS(HL7_NS, "hl7:Role");
elemURAttr.appendChild(userRole);
userRole.setAttributeNS("http:
if (tokenVals.containsKey(SamlConstants.USER_CODE_PROP)
&& tokenVals.get(SamlConstants.USER_CODE_PROP) != null) {
log.debug("User Role Code: " + tokenVals.get(SamlConstants.USER_CODE_PROP));
userRole.setAttribute(SamlConstants.CE_CODE_ID, tokenVals.get(SamlConstants.USER_CODE_PROP).toString());
} else {
log.warn("No information provided to fill in user role code attribute");
}
if (tokenVals.containsKey(SamlConstants.USER_SYST_PROP)
&& tokenVals.get(SamlConstants.USER_SYST_PROP) != null) {
log.debug("User Role Code System: " + tokenVals.get(SamlConstants.USER_SYST_PROP).toString());
userRole.setAttribute(SamlConstants.CE_CODESYS_ID, tokenVals.get(SamlConstants.USER_SYST_PROP)
.toString());
} else {
log.warn("No information provided to fill in user role code system attribute");
}
if (tokenVals.containsKey(SamlConstants.USER_SYST_NAME_PROP)
&& tokenVals.get(SamlConstants.USER_SYST_NAME_PROP) != null) {
log.debug("User Role Code System Name: " + tokenVals.get(SamlConstants.USER_SYST_NAME_PROP).toString());
userRole.setAttribute(SamlConstants.CE_CODESYSNAME_ID, tokenVals.get(SamlConstants.USER_SYST_NAME_PROP)
.toString());
} else {
log.warn("No information provided to fill in user role code system name attribute");
}
if (tokenVals.containsKey(SamlConstants.USER_DISPLAY_PROP)
&& tokenVals.get(SamlConstants.USER_DISPLAY_PROP) != null) {
log.debug("User Role Display: " + tokenVals.get(SamlConstants.USER_DISPLAY_PROP).toString());
userRole.setAttribute(SamlConstants.CE_DISPLAYNAME_ID, tokenVals.get(SamlConstants.USER_DISPLAY_PROP)
.toString());
} else {
log.warn("No information provided to fill in user role display attribute");
}
attributeValues3.add(elemURAttr);
attributes.add(factory.createAttribute(SamlConstants.USER_ROLE_ATTR, attributeValues3));
} catch (ParserConfigurationException ex) {
log.debug("Unable to create an XML Document to set Attributes" + ex.getMessage());
}
try {
/*
* Gateway-347 - Support for both values will remain until NHIN Specs updated Determine whether to use
* PurposeOfUse or PuposeForUse
*/
String purposeAttributeValueName = "hl7:PurposeOfUse";
if (isPurposeForUseEnabled()) {
purposeAttributeValueName = "hl7:PurposeForUse";
}
// Add the Purpose Of/For Use Attribute Value
List attributeValues4 = new ArrayList();
final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
final Element elemPFUAttr = document.createElementNS("urn:oasis:names:tc:SAML:2.0:assertion",
"AttibuteValue");
final Element purpose = document.createElementNS(HL7_NS, purposeAttributeValueName);
elemPFUAttr.appendChild(purpose);
purpose.setAttributeNS("http:
if (tokenVals.containsKey(SamlConstants.PURPOSE_CODE_PROP)
&& tokenVals.get(SamlConstants.PURPOSE_CODE_PROP) != null) {
log.debug("Purpose Code: " + tokenVals.get(SamlConstants.PURPOSE_CODE_PROP).toString());
purpose.setAttribute(SamlConstants.CE_CODE_ID, tokenVals.get(SamlConstants.PURPOSE_CODE_PROP)
.toString());
}
if (tokenVals.containsKey(SamlConstants.PURPOSE_SYST_PROP)
&& tokenVals.get(SamlConstants.PURPOSE_SYST_PROP) != null) {
log.debug("Purpose Code System: " + tokenVals.get(SamlConstants.PURPOSE_SYST_PROP).toString());
purpose.setAttribute(SamlConstants.CE_CODESYS_ID, tokenVals.get(SamlConstants.PURPOSE_SYST_PROP)
.toString());
}
if (tokenVals.containsKey(SamlConstants.PURPOSE_SYST_NAME_PROP)
&& tokenVals.get(SamlConstants.PURPOSE_SYST_NAME_PROP) != null) {
log.debug("Purpose Code System Name: " + tokenVals.get(SamlConstants.PURPOSE_SYST_NAME_PROP).toString());
purpose.setAttribute(SamlConstants.CE_CODESYSNAME_ID,
tokenVals.get(SamlConstants.PURPOSE_SYST_NAME_PROP).toString());
}
if (tokenVals.containsKey(SamlConstants.PURPOSE_DISPLAY_PROP)
&& tokenVals.get(SamlConstants.PURPOSE_DISPLAY_PROP) != null) {
log.debug("Purpose Display: " + tokenVals.get(SamlConstants.PURPOSE_DISPLAY_PROP).toString());
purpose.setAttribute(SamlConstants.CE_DISPLAYNAME_ID, tokenVals.get(SamlConstants.PURPOSE_DISPLAY_PROP)
.toString());
}
attributeValues4.add(elemPFUAttr);
attributes.add(factory.createAttribute(SamlConstants.PURPOSE_ROLE_ATTR, attributeValues4));
if (!attributes.isEmpty()) {
statements.add(factory.createAttributeStatement(attributes));
}
} catch (ParserConfigurationException ex) {
log.debug("Unable to create an XML Document to set Attributes" + ex.getMessage());
}
// Set the Patient ID Attribute
List attributeValues7 = new ArrayList();
if (tokenVals.containsKey(SamlConstants.PATIENT_ID_PROP)
&& tokenVals.get(SamlConstants.PATIENT_ID_PROP) != null) {
log.debug("PatientID: " + tokenVals.get(SamlConstants.PATIENT_ID_PROP).toString());
attributeValues7.add(tokenVals.get(SamlConstants.PATIENT_ID_PROP).toString());
attributes.add(factory.createAttribute(SamlConstants.PATIENT_ID_ATTR, attributeValues7));
} else {
log.warn("No information provided to fill in patient ID attribute");
}
log.debug("SamlCallbackHandler.addAssertStatements() -- End");
return statements;
}
/**
* Returns boolean condition on whether PurposeForUse is enabled
*
* @return The PurposeForUse enabled setting
*/
private boolean isPurposeForUseEnabled() {
boolean match = false;
try {
// Use CONNECT utility class to access gateway.properties
String purposeForUseEnabled = PropertyAccessor.getProperty(NhincConstants.GATEWAY_PROPERTY_FILE,
PURPOSE_FOR_USE_DEPRECATED_ENABLED);
if (purposeForUseEnabled != null && purposeForUseEnabled.equalsIgnoreCase("true")) {
match = true;
}
} catch (PropertyAccessException ex) {
log.error("Error: Failed to retrieve " + PURPOSE_FOR_USE_DEPRECATED_ENABLED + " from property file: "
+ NhincConstants.GATEWAY_PROPERTY_FILE);
log.error(ex.getMessage());
}
return match;
}
/**
* Creates the Evidence element that encompasses the Assertion defining the authorization form needed in cases where
* evidence of authorization to access the medical records must be provided along with the message request
*
* @param factory The factory object used to assist in the construction of the SAML Assertion token
* @param issueInstant The calendar representing the time of Assertion issuance
* @return The Evidence element
* @throws com.sun.xml.wss.saml.SAMLException
*/
private Evidence createEvidence() throws SAMLException, XWSSecurityException {
log.debug("SamlCallbackHandler.createEvidence() -- Begin");
Boolean defaultInstant = false;
Boolean defaultBefore = false;
Boolean defaultAfter = false;
String evAssertVersion = ASSERTION_VERSION_2_0;
if ((tokenVals.containsKey(SamlConstants.EVIDENCE_VERSION_PROP) && tokenVals
.get(SamlConstants.EVIDENCE_VERSION_PROP) != null)) {
String requestedVersion = tokenVals.get(SamlConstants.EVIDENCE_VERSION_PROP).toString();
if (VALID_ASSERTION_VERSION_LIST.contains(requestedVersion.trim())) {
log.debug("Setting Evidence Assertion Version to: " + requestedVersion);
evAssertVersion = requestedVersion;
} else {
log.debug(requestedVersion + " is not recognized as valid, " + "create evidence assertion version as: "
+ ASSERTION_VERSION_2_0);
log.debug("Should be one of: " + VALID_ASSERTION_VERSION_LIST);
}
} else {
log.debug("Defaulting Evidence version to: " + ASSERTION_VERSION_2_0);
}
String evAssertFactoryVersion = factoryVersionMap.get(evAssertVersion);
SAMLAssertionFactory factory = SAMLAssertionFactory.newInstance(evAssertFactoryVersion);
List evAsserts = new ArrayList();
try {
String evAssertionID = String.valueOf(UUID.randomUUID());
if (tokenVals.containsKey(SamlConstants.EVIDENCE_ID_PROP)
&& tokenVals.get(SamlConstants.EVIDENCE_ID_PROP) != null) {
evAssertionID = tokenVals.get(SamlConstants.EVIDENCE_ID_PROP).toString();
log.debug("Setting Evidence assertion id to: " + evAssertionID);
} else {
log.debug("Defaulting Evidence assertion id to: " + evAssertionID);
}
GregorianCalendar issueInstant = calendarFactory();
if (tokenVals.containsKey(SamlConstants.EVIDENCE_INSTANT_PROP)
&& tokenVals.get(SamlConstants.EVIDENCE_INSTANT_PROP) != null) {
String authnInstant = tokenVals.get(SamlConstants.EVIDENCE_INSTANT_PROP).toString();
try {
// times must be in UTC format as specified by the XML
// Schema type (dateTime)
DatatypeFactory xmlDateFactory = DatatypeFactory.newInstance();
XMLGregorianCalendar xmlDate = xmlDateFactory.newXMLGregorianCalendar(authnInstant.trim());
issueInstant = xmlDate.toGregorianCalendar();
log.debug("Setting Evidence assertion instant to: " + xmlDate.toXMLFormat());
} catch (IllegalArgumentException iaex) {
log.debug("Evidence assertion instant: " + authnInstant
+ " is not in a valid dateTime format, defaulting to current time");
} catch (DatatypeConfigurationException ex) {
log.debug("Evidence assertion instant: " + authnInstant
+ " is not in a valid dateTime format, defaulting to current time");
}
} else {
log.debug("Defaulting Authentication instant to current time");
defaultInstant = true;
}
NameID evIssuerId = null;
if (tokenVals.containsKey(SamlConstants.EVIDENCE_ISSUER_FORMAT_PROP)
&& tokenVals.get(SamlConstants.EVIDENCE_ISSUER_FORMAT_PROP) != null
&& tokenVals.containsKey(SamlConstants.EVIDENCE_ISSUER_PROP)
&& tokenVals.get(SamlConstants.EVIDENCE_ISSUER_PROP) != null) {
String format = tokenVals.get(SamlConstants.EVIDENCE_ISSUER_FORMAT_PROP).toString();
if (VALID_NAME_LIST.contains(format.trim())) {
log.debug("Setting Evidence Issuer format to: " + format);
String issuer = tokenVals.get(SamlConstants.EVIDENCE_ISSUER_PROP).toString();
log.debug("Setting Evidence Issuer to: " + issuer);
evIssuerId = factory.createNameID(issuer, null, format);
} else {
log.debug(format + " is not recognized as valid, " + "create default evidence issuer");
log.debug("Should be one of: " + VALID_NAME_LIST);
evIssuerId = create509NameID(factory, DEFAULT_NAME);
}
} else {
log.debug("Defaulting Evidence issuer format to: " + X509_NAME_ID + " Default issuer identity");
evIssuerId = create509NameID(factory, DEFAULT_NAME);
}
GregorianCalendar beginValidTime = calendarFactory();
if ((tokenVals.containsKey(SamlConstants.EVIDENCE_CONDITION_NOT_BEFORE_PROP) && tokenVals
.get(SamlConstants.EVIDENCE_CONDITION_NOT_BEFORE_PROP) != null)) {
beginValidTime = createCal(tokenVals.get(SamlConstants.EVIDENCE_CONDITION_NOT_BEFORE_PROP).toString());
} else {
log.debug("Defaulting Evidence NotBefore condition to: current time");
defaultBefore = true;
}
GregorianCalendar endValidTime = calendarFactory();
if ((tokenVals.containsKey(SamlConstants.EVIDENCE_CONDITION_NOT_AFTER_PROP) && tokenVals
.get(SamlConstants.EVIDENCE_CONDITION_NOT_AFTER_PROP) != null)) {
endValidTime = createCal(tokenVals.get(SamlConstants.EVIDENCE_CONDITION_NOT_AFTER_PROP).toString());
} else {
log.debug("Defaulting Evidence NotAfter condition to: current time");
defaultAfter = true;
}
if (defaultInstant && defaultBefore && defaultAfter) {
log.warn("Begin, End, and Instant time all defaulted to current time. Set end time to future.");
endValidTime.set(Calendar.MINUTE, endValidTime.get(Calendar.MINUTE) + 5);
}
if (beginValidTime.after(endValidTime)) {
// set beginning time to now
beginValidTime = calendarFactory();
log.warn("The beginning time for the valid evidence should be before the ending time. "
+ "Setting the beginning time to the current system time.");
}
Conditions conditions = factory.createConditions(beginValidTime, endValidTime, null, null, null, null);
List statements = createEvidenceStatements(factory);
Assertion evAssert = factory.createAssertion(evAssertionID, evIssuerId, issueInstant, conditions, null,
null, statements);
evAssert.setVersion(evAssertVersion);
evAsserts.add(evAssert);
} catch (SAMLException ex) {
log.debug("Unable to create Evidence Assertion: " + ex.getMessage());
}
Evidence evidence = factory.createEvidence(null, evAsserts);
log.debug("SamlCallbackHandler.createEvidence() -- End");
return evidence;
}
/**
* Creates a calendar object representing the time given.
*
* @param time following the UTC format as specified by the XML Schema type (dateTime) or for backward compatibility
* following the simple date form MM/dd/yyyy HH:mm:ss
* @return The calendar object representing the given time
*/
private GregorianCalendar createCal(String time) {
GregorianCalendar cal = calendarFactory();
try {
// times must be in UTC format as specified by the XML Schema type
// (dateTime)
DatatypeFactory xmlDateFactory = DatatypeFactory.newInstance();
XMLGregorianCalendar xmlDate = xmlDateFactory.newXMLGregorianCalendar(time.trim());
cal = xmlDate.toGregorianCalendar();
} catch (IllegalArgumentException iaex) {
try {
// try simple date format - backward compatibility
SimpleDateFormat dateForm = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
cal.setTime(dateForm.parse(time));
} catch (ParseException ex) {
log.error("Date form is expected to be in dateTime format yyyy-MM-ddTHH:mm:ss.SSSZ Setting default date");
}
} catch (DatatypeConfigurationException dtex) {
log.error("Problem in creating XML Date Factory. Setting default date");
}
log.info("Created calendar instance: " + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.DAY_OF_MONTH)
+ "/" + cal.get(Calendar.YEAR) + " " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE)
+ ":" + cal.get(Calendar.SECOND));
return cal;
}
/**
* Creates the Attribute Statements needed for the Evidence element. These include the Attributes for the Access
* Consent Policy and the Instance Access Consent Policy
*
* @param factory The factory object used to assist in the construction of the SAML Assertion token
* @return The listing of the attribute statements for the Evidence element
* @throws com.sun.xml.wss.saml.SAMLException
*/
private List createEvidenceStatements(SAMLAssertionFactory factory) throws SAMLException {
log.debug("SamlCallbackHandler.createEvidenceStatements() -- Begin");
List statements = new ArrayList();
List attributes = new ArrayList();
// Set the Access Consent
List attributeValues1 = new ArrayList();
if (tokenVals.containsKey(SamlConstants.EVIDENCE_ACCESS_CONSENT_PROP)
&& tokenVals.get(SamlConstants.EVIDENCE_ACCESS_CONSENT_PROP) != null) {
log.debug("Setting Evidence Access Consent to: "
+ tokenVals.get(SamlConstants.EVIDENCE_ACCESS_CONSENT_PROP).toString());
attributeValues1.addAll((List<String>) tokenVals.get(SamlConstants.EVIDENCE_ACCESS_CONSENT_PROP));
} else {
log.debug("No Access Consent found for Evidence");
}
if (!attributeValues1.isEmpty())
attributes.add(factory.createAttribute("AccessConsentPolicy", NHIN_NS, attributeValues1));
// Set the Instance Access Consent
List attributeValues2 = new ArrayList();
if (tokenVals.containsKey(SamlConstants.EVIDENCE_INST_ACCESS_CONSENT_PROP)
&& tokenVals.get(SamlConstants.EVIDENCE_INST_ACCESS_CONSENT_PROP) != null) {
log.debug("Setting Evidence Instance Access Consent to: "
+ tokenVals.get(SamlConstants.EVIDENCE_INST_ACCESS_CONSENT_PROP).toString());
attributeValues2.addAll((List<String>) tokenVals.get(SamlConstants.EVIDENCE_INST_ACCESS_CONSENT_PROP));
} else {
log.debug("No Instance Access Consent found for Evidence");
}
if (!attributeValues2.isEmpty())
attributes.add(factory.createAttribute("InstanceAccessConsentPolicy", NHIN_NS, attributeValues2));
if (!attributes.isEmpty()) {
statements.add(factory.createAttributeStatement(attributes));
} else
throw new SAMLException(
"At least one AccessConsentPolicy or InstanceAccessConsentPolicy must be provided in the AuthorizationDecisionStatement:Evidence:AttributeStatement");
log.debug("SamlCallbackHandler.createEvidenceStatements() -- End");
return statements;
}
/**
* Initializes the keystore access using the system properties defined in the domain.xml javax.net.ssl.keyStore and
* javax.net.ssl.keyStorePassword
*
* @throws java.io.IOException
*/
private void initKeyStore() throws IOException {
log.debug("SamlCallbackHandler.initKeyStore() -- Begin");
InputStream is = null;
String storeType = System.getProperty("javax.net.ssl.keyStoreType");
String password = System.getProperty("javax.net.ssl.keyStorePassword");
String storeLoc = System.getProperty("javax.net.ssl.keyStore");
if (storeType == null) {
log.error("javax.net.ssl.keyStoreType is not defined in domain.xml");
log.warn("Default to JKS keyStoreType");
storeType = "JKS";
}
if (password != null) {
if ("JKS".equals(storeType) && storeLoc == null) {
log.error("javax.net.ssl.keyStore is not defined in domain.xml");
} else {
try {
keyStore = KeyStore.getInstance(storeType);
if ("JKS".equals(storeType)) {
is = new FileInputStream(storeLoc);
}
keyStore.load(is, password.toCharArray());
} catch (NoSuchAlgorithmException ex) {
log.error("Error initializing KeyStore: " + ex);
throw new IOException(ex.getMessage());
} catch (CertificateException ex) {
log.error("Error initializing KeyStore: " + ex);
throw new IOException(ex.getMessage());
} catch (KeyStoreException ex) {
log.error("Error initializing KeyStore: " + ex);
throw new IOException(ex.getMessage());
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException ex) {
log.debug("KeyStoreCallbackHandler " + ex);
}
}
}
} else {
log.error("javax.net.ssl.keyStorePassword is not defined in domain.xml");
}
log.debug("SamlCallbackHandler.initKeyStore() -- End");
}
/**
* Initializes the truststore access using the system properties defined in the domain.xml javax.net.ssl.trustStore
* and javax.net.ssl.trustStorePassword
*
* @throws java.io.IOException
*/
private void initTrustStore() throws IOException {
log.debug("SamlCallbackHandler.initTrustStore() -- Begin");
InputStream is = null;
String storeType = System.getProperty("javax.net.ssl.trustStoreType");
String password = System.getProperty("javax.net.ssl.trustStorePassword");
String storeLoc = System.getProperty("javax.net.ssl.trustStore");
if (storeType == null) {
log.error("javax.net.ssl.trustStoreType is not defined in domain.xml");
log.warn("Default to JKS trustStoreType");
storeType = "JKS";
}
if (password != null) {
if ("JKS".equals(storeType) && storeLoc == null) {
log.error("javax.net.ssl.trustStore is not defined in domain.xml");
} else {
try {
trustStore = KeyStore.getInstance(storeType);
if ("JKS".equals(storeType)) {
is = new FileInputStream(storeLoc);
}
trustStore.load(is, password.toCharArray());
} catch (NoSuchAlgorithmException ex) {
log.error("Error initializing TrustStore: " + ex);
throw new IOException(ex.getMessage());
} catch (CertificateException ex) {
log.error("Error initializing TrustStore: " + ex);
throw new IOException(ex.getMessage());
} catch (KeyStoreException ex) {
log.error("Error initializing TrustStore: " + ex);
throw new IOException(ex.getMessage());
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException ex) {
log.debug("KeyStoreCallbackHandler " + ex);
}
}
}
} else {
log.error("javax.net.ssl.trustStorePassword is not defined in domain.xml");
}
log.debug("SamlCallbackHandler.initTrustStore() -- End");
}
/**
* Finds the X509 certificate in the keystore with the client alias as defined in the domain.xml system property
* CLIENT_KEY_ALIAS and establishes the private key on the SignatureKeyCallback request using this certificate.
*
* @param request The SignatureKeyCallback request object
* @throws java.io.IOException
*/
private void getDefaultPrivKeyCert(SignatureKeyCallback.DefaultPrivKeyCertRequest request) throws IOException {
log.debug("SamlCallbackHandler.getDefaultPrivKeyCert() -- Begin");
String uniqueAlias = null;
String client_key_alias = System.getProperty("CLIENT_KEY_ALIAS");
if (client_key_alias != null) {
String password = System.getProperty("javax.net.ssl.keyStorePassword");
if (password != null) {
try {
Enumeration aliases = keyStore.aliases();
while (aliases.hasMoreElements()) {
String currentAlias = (String) aliases.nextElement();
if (currentAlias.equals(client_key_alias)) {
if (keyStore.isKeyEntry(currentAlias)) {
Certificate thisCertificate = keyStore.getCertificate(currentAlias);
if (thisCertificate != null) {
if (thisCertificate instanceof X509Certificate) {
if (uniqueAlias == null) {
uniqueAlias = currentAlias;
break;
}
}
}
}
}
}
if (uniqueAlias != null) {
request.setX509Certificate((X509Certificate) keyStore.getCertificate(uniqueAlias));
request.setPrivateKey((PrivateKey) keyStore.getKey(uniqueAlias, password.toCharArray()));
} else {
log.error("Client key alais can not be determined");
}
} catch (UnrecoverableKeyException ex) {
log.error("Error initializing Private Key: " + ex);
throw new IOException(ex.getMessage());
} catch (NoSuchAlgorithmException ex) {
log.error("Error initializing Private Key: " + ex);
throw new IOException(ex.getMessage());
} catch (KeyStoreException ex) {
log.error("Error initializing Private Key: " + ex);
throw new IOException(ex.getMessage());
}
} else {
log.error("javax.net.ssl.keyStorePassword is not defined in domain.xml");
}
} else {
log.error("CLIENT_KEY_ALIAS is not defined in domain.xml");
}
log.debug("SamlCallbackHandler.getDefaultPrivKeyCert() -- End");
}
/**
* Creates a calendar instance set to the current system time in GMT
*
* @return The calendar instance
*/
private GregorianCalendar calendarFactory() {
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
return calendar;
}
} |
package org.csstudio.utility.adlparser;
import org.eclipse.jface.action.IContributionItem;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.actions.ContributionItemFactory;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.eclipse.ui.application.ActionBarAdvisor;
import org.eclipse.ui.application.IActionBarConfigurer;
/**
* An action bar advisor is responsible for creating, adding, and disposing of
* the actions added to a workbench window. Each window will be populated with
* new actions.
*/
public class ApplicationActionBarAdvisor extends ActionBarAdvisor {
// Actions - important to allocate these only in makeActions, and then use
// them
// in the fill methods. This ensures that the actions aren't recreated
// when fillActionBars is called with FILL_PROXY.
private IWorkbenchAction exitAction;
private IWorkbenchAction perspectiveAction;
private IWorkbenchAction saveAction;
private IWorkbenchAction saveAsAction;
private IWorkbenchAction preferencesAction;
private IContributionItem showViewAction;
public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) {
super(configurer);
}
protected void makeActions(final IWorkbenchWindow window) {
// Creates the actions and registers them.
// Registering is needed to ensure that key bindings work.
// The corresponding commands keybindings are defined in the plugin.xml
// file.
// Registering also provides automatic disposal of the actions when
// the window is closed.
exitAction = ActionFactory.QUIT.create(window);
perspectiveAction = ActionFactory.OPEN_PERSPECTIVE_DIALOG.create(window);
showViewAction = ContributionItemFactory.VIEWS_SHORTLIST.create(window);
saveAction = ActionFactory.SAVE.create(window);
saveAsAction = ActionFactory.SAVE_AS.create(window);
preferencesAction = ActionFactory.PREFERENCES.create(window);
register(exitAction);
register(perspectiveAction);
register(saveAction);
register(saveAsAction);
register(preferencesAction);
}
protected void fillMenuBar(IMenuManager menuBar) {
MenuManager fileMenu = new MenuManager("&File",
IWorkbenchActionConstants.M_FILE);
MenuManager windowMenu = new MenuManager("&Window",
IWorkbenchActionConstants.M_WINDOW);
menuBar.add(fileMenu);
menuBar.add(windowMenu);
windowMenu.add(perspectiveAction);
windowMenu.add(showViewAction);
fileMenu.add(saveAction);
System.out.println ("hello from fill menubar");
fileMenu.add(saveAsAction);
fileMenu.add(preferencesAction);
fileMenu.add(exitAction);
}
} |
package uk.gov.register.functional.app;
import io.dropwizard.client.JerseyClientBuilder;
import io.dropwizard.testing.ConfigOverride;
import io.dropwizard.testing.ResourceHelpers;
import io.dropwizard.testing.junit.DropwizardAppRule;
import org.apache.http.impl.conn.InMemoryDnsResolver;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.Handle;
import uk.gov.register.RegisterApplication;
import uk.gov.register.RegisterConfiguration;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static javax.ws.rs.client.Entity.entity;
import static uk.gov.register.views.representations.ExtraMediaType.APPLICATION_RSF_TYPE;
public class RegisterRule implements TestRule {
public enum TestRegister {
address, postcode, register;
private static final String REGISTER_DOMAIN = "test.register.gov.uk";
private final String hostname = name() + "." + REGISTER_DOMAIN;
public String getHostname() {
return hostname;
}
}
private final WipeDatabaseRule wipeRule;
private DropwizardAppRule<RegisterConfiguration> appRule;
private TestRule wholeRule;
private Client client;
private List<Handle> handles = new ArrayList<>();
public RegisterRule(ConfigOverride... overrides) {
this.appRule = new DropwizardAppRule<>(RegisterApplication.class,
ResourceHelpers.resourceFilePath("test-app-config.yaml"),
overrides);
String[] registers = Arrays.stream(TestRegister.values())
.map(TestRegister::name)
.toArray(String[]::new);
wipeRule = new WipeDatabaseRule(registers);
wholeRule = RuleChain
.outerRule(appRule)
.around(wipeRule);
}
@Override
public Statement apply(Statement base, Description description) {
Statement me = new Statement() {
@Override
public void evaluate() throws Throwable {
client = clientBuilder().build("test client");
base.evaluate();
handles.forEach(Handle::close);
}
};
return wholeRule.apply(me, description);
}
private WebTarget authenticatedTarget(String registerName) {
WebTarget authenticatedTarget = targetRegister(registerName);
authenticatedTarget.register(HttpAuthenticationFeature.basicBuilder().credentials("foo", "bar").build());
return authenticatedTarget;
}
private WebTarget target(String targetHost) {
return client.target("http://" + targetHost + ":" + appRule.getLocalPort());
}
/**
* get a WebTarget pointing at a particular register.
* if the registerName is recognized, the Host: will be set appropriately for that register
* if not, it will default to a Host: of localhost (which will hit the default register)
*/
public WebTarget targetRegister(String registerName) {
TestRegister register = TestRegister.valueOf(registerName);
return target(register.getHostname());
}
public Response loadRsf(String registerName, String rsf) {
return authenticatedTarget(registerName).path("/load-rsf")
.request()
.post(entity(rsf, APPLICATION_RSF_TYPE));
}
public Response mintLines(String registerName, String... payload) {
return authenticatedTarget(registerName).path("/load")
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.json(String.join("\n", payload)));
}
public Response getRequest(String registerName, String path) {
return targetRegister(registerName).path(path).request().get();
}
public Response getRequest(String registerName, String path, String acceptedResponseType) {
return targetRegister(registerName).path(path).request(acceptedResponseType).get();
}
public Response deleteRegisterData(String registerName) {
return authenticatedTarget(registerName).path("/delete-register-data").request().delete();
}
public void wipe() {
wipeRule.before();
}
private JerseyClientBuilder clientBuilder() {
InMemoryDnsResolver customDnsResolver = new InMemoryDnsResolver();
for (TestRegister register : TestRegister.values()) {
customDnsResolver.add(register.getHostname(), InetAddress.getLoopbackAddress());
}
customDnsResolver.add("localhost", InetAddress.getLoopbackAddress());
return new JerseyClientBuilder(appRule.getEnvironment())
.using(appRule.getConfiguration().getJerseyClientConfiguration())
.using(customDnsResolver);
}
/**
* provides a DBI Handle for the given register
* the handle will automatically be closed by the RegisterRule
*/
public Handle handleFor(String register) {
Handle handle = new DBI(postgresConnectionString(register)).open();
handles.add(handle);
return handle;
}
private String postgresConnectionString(String register) {
return String.format("jdbc:postgresql://localhost:5432/ft_openregister_java_%s?user=postgres&ApplicationName=RegisterRule", register);
}
} |
package org.eclipse.birt.chart.ui.swt.wizard.format.popup;
import org.eclipse.birt.chart.model.attribute.ScaleUnitType;
import org.eclipse.birt.chart.model.component.ComponentPackage;
import org.eclipse.birt.chart.model.component.Scale;
import org.eclipse.birt.chart.model.data.DataElement;
import org.eclipse.birt.chart.model.data.DateTimeDataElement;
import org.eclipse.birt.chart.ui.extension.i18n.Messages;
import org.eclipse.birt.chart.ui.swt.ChartCheckbox;
import org.eclipse.birt.chart.ui.swt.ChartCombo;
import org.eclipse.birt.chart.ui.swt.composites.TextEditorComposite;
import org.eclipse.birt.chart.ui.swt.interfaces.IDataElementComposite;
import org.eclipse.birt.chart.ui.swt.wizard.ChartWizardContext;
import org.eclipse.birt.chart.ui.util.ChartHelpContextIds;
import org.eclipse.birt.chart.ui.util.ChartUIUtil;
import org.eclipse.birt.chart.util.LiteralHelper;
import org.eclipse.birt.chart.util.NameSet;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Spinner;
public abstract class AbstractScaleSheet extends AbstractPopupSheet
implements
Listener, SelectionListener
{
protected Label lblMin = null;
protected IDataElementComposite txtScaleMin = null;
protected Label lblMax = null;
protected IDataElementComposite txtScaleMax = null;
protected Button btnStepSize = null;
protected Button btnStepNumber = null;
protected Button btnStepAuto = null;
protected Button btnFactor = null;
protected TextEditorComposite txtFactor = null;
protected TextEditorComposite txtStepSize = null;
protected Label lblUnit = null;
protected ChartCombo cmbScaleUnit = null;
protected Label lblStepNumber = null;
protected Spinner spnStepNumber = null;
protected ChartCheckbox btnAutoExpand;
protected ChartCheckbox btnShowOutside;
public AbstractScaleSheet( String title, ChartWizardContext context )
{
super( title, context, true );
}
protected Composite getComponent( Composite parent )
{
ChartUIUtil.bindHelp( parent, ChartHelpContextIds.POPUP_AXIS_SCALE );
Composite cmpContent = new Composite( parent, SWT.NONE );
{
GridLayout glContent = new GridLayout( 4, false );
glContent.marginHeight = 10;
glContent.marginWidth = 10;
glContent.horizontalSpacing = 5;
glContent.verticalSpacing = 10;
cmpContent.setLayout( glContent );
}
Group grpScale = new Group( cmpContent, SWT.NONE );
{
GridData gdGRPScale = new GridData( GridData.FILL_BOTH );
gdGRPScale.horizontalSpan = 4;
grpScale.setLayoutData( gdGRPScale );
GridLayout glScale = new GridLayout( );
glScale.numColumns = 4;
glScale.horizontalSpacing = 5;
glScale.verticalSpacing = 5;
glScale.marginHeight = 2;
glScale.marginWidth = 7;
grpScale.setLayout( glScale );
grpScale.setText( Messages.getString( "AbstractScaleSheet.Label.Step" ) ); //$NON-NLS-1$
}
btnStepAuto = new Button( grpScale, SWT.RADIO );
{
GridData gd = new GridData( );
gd.horizontalSpan = 4;
btnStepAuto.setLayoutData( gd );
btnStepAuto.setText( Messages.getString( "AbstractScaleSheet.Label.Auto" ) ); //$NON-NLS-1$
btnStepAuto.addListener( SWT.Selection, this );
}
btnStepSize = new Button( grpScale, SWT.RADIO );
{
btnStepSize.setText( Messages.getString( "AbstractScaleSheet.Label.StepSize" ) ); //$NON-NLS-1$
btnStepSize.addListener( SWT.Selection, this );
}
txtStepSize = new TextEditorComposite( grpScale, SWT.BORDER
| SWT.SINGLE, TextEditorComposite.TYPE_NUMBERIC );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
gd.widthHint = 100;
txtStepSize.setLayoutData( gd );
String str = ""; //$NON-NLS-1$
if ( getScale( ).isSetStep( ) )
{
str = String.valueOf( getScale( ).getStep( ) );
}
txtStepSize.setText( str );
txtStepSize.addListener( this );
txtStepSize.addListener( SWT.Modify, this );
txtStepSize.setDefaultValue( "" ); //$NON-NLS-1$
}
lblUnit = new Label( grpScale, SWT.NONE );
{
lblUnit.setText( Messages.getString( "BaseAxisDataSheetImpl.Lbl.Unit" ) ); //$NON-NLS-1$
}
cmbScaleUnit = getContext( ).getUIFactory( )
.createChartCombo( grpScale,
SWT.DROP_DOWN | SWT.READ_ONLY,
getScale( ),
"unit", //$NON-NLS-1$
getDefaultVauleScale( ).getUnit( ).getName( ) );
{
GridData gdCMBScaleUnit = new GridData( GridData.FILL_HORIZONTAL );
cmbScaleUnit.setLayoutData( gdCMBScaleUnit );
cmbScaleUnit.addListener( SWT.Selection, this );
// Populate origin types combo
NameSet ns = LiteralHelper.scaleUnitTypeSet;
cmbScaleUnit.setItems( ns.getDisplayNames( ) );
cmbScaleUnit.setItemData( ns.getNames( ) );
cmbScaleUnit.setSelection( getScale( ).getUnit( ).getName( ) );
}
btnStepNumber = new Button( grpScale, SWT.RADIO );
{
btnStepNumber.setText( Messages.getString( "AbstractScaleSheet.Label.StepNumber" ) ); //$NON-NLS-1$
btnStepNumber.addListener( SWT.Selection, this );
}
spnStepNumber = new Spinner( grpScale, SWT.BORDER );
{
spnStepNumber.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
spnStepNumber.setMinimum( 1 );
spnStepNumber.setMaximum( 100 );
spnStepNumber.setSelection( getScale( ).getStepNumber( ) );
spnStepNumber.addListener( SWT.Selection, this );
ChartUIUtil.addScreenReaderAccessbility( spnStepNumber, btnStepNumber.getText( ) );
}
new Label( grpScale, SWT.NONE );
new Label( grpScale, SWT.NONE );
btnFactor = new Button( cmpContent, SWT.CHECK );
{
btnFactor.setText( Messages.getString("AbstractScaleSheet.Label.Factor") ); //$NON-NLS-1$
GridData gd = new GridData( );
gd.horizontalSpan = 2;
btnFactor.setLayoutData( gd );
btnFactor.addListener( SWT.Selection, this );
if ( getScale( ).isSetFactor( ) )
{
btnFactor.setSelection( true );
}
else
{
btnFactor.setSelection( false );
}
}
txtFactor = new TextEditorComposite( cmpContent, SWT.BORDER
| SWT.SINGLE, TextEditorComposite.TYPE_NUMBERIC );
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
// gd.widthHint = 100;
gd.horizontalSpan = 2;
txtFactor.setLayoutData( gd );
String str = ""; //$NON-NLS-1$
if ( getScale( ).isSetFactor( ) )
{
str = String.valueOf( getScale( ).getFactor( ) );
}
txtFactor.setText( str );
txtFactor.addListener( this );
txtFactor.addListener( SWT.Modify, this );
txtFactor.setDefaultValue( "" ); //$NON-NLS-1$
}
lblMin = new Label( cmpContent, SWT.NONE );
lblMin.setText( Messages.getString( "BaseAxisDataSheetImpl.Lbl.Minimum" ) ); //$NON-NLS-1$
txtScaleMin = createValuePicker( cmpContent,
getScale( ).getMin( ),
getScale( ),
"min" ); //$NON-NLS-1$
lblMax = new Label( cmpContent, SWT.NONE );
lblMax.setText( Messages.getString( "BaseAxisDataSheetImpl.Lbl.Maximum" ) ); //$NON-NLS-1$
txtScaleMax = createValuePicker( cmpContent,
getScale( ).getMax( ),
getScale( ),
"max" );//$NON-NLS-1$
btnAutoExpand = getContext( ).getUIFactory( )
.createChartCheckbox( cmpContent,
SWT.NONE,
getDefaultVauleScale( ).isAutoExpand( ) );
btnAutoExpand.setText( Messages.getString( "AbstractScaleSheet.AutoExpand" ) );//$NON-NLS-1$
{
GridData gd = new GridData( );
gd.horizontalSpan = 4;
btnAutoExpand.setLayoutData( gd );
btnAutoExpand.setSelectionState( getScale( ).isSetAutoExpand( ) ? ( getScale( ).isAutoExpand( ) ? ChartCheckbox.STATE_SELECTED
: ChartCheckbox.STATE_UNSELECTED )
: ChartCheckbox.STATE_GRAYED );
btnAutoExpand.addSelectionListener( this );
}
btnShowOutside = getContext( ).getUIFactory( )
.createChartCheckbox( cmpContent,
SWT.NONE,
getDefaultVauleScale( ).isShowOutside( ) );
btnShowOutside.setText( Messages.getString( "AbstractScaleSheet.Label.ShowValuesOutside" ) ); //$NON-NLS-1$
{
GridData gd = new GridData( );
gd.horizontalSpan = 4;
btnShowOutside.setLayoutData( gd );
btnShowOutside.setSelectionState( getScale( ).isSetShowOutside( ) ? ( getScale( ).isShowOutside( ) ? ChartCheckbox.STATE_SELECTED
: ChartCheckbox.STATE_UNSELECTED )
: ChartCheckbox.STATE_GRAYED );
btnShowOutside.addSelectionListener( this );
// Only visible in number type
btnShowOutside.setVisible( getValueType( ) == TextEditorComposite.TYPE_NUMBERIC );
}
// Set checkbox selection.
btnStepSize.setSelection( getScale( ).isSetStep( ) );
if ( !btnStepSize.getSelection( ) )
{
if ( getValueType( ) != TextEditorComposite.TYPE_NUMBERIC )
{
btnStepAuto.setSelection( true );
}
else
{
// Only numeric value support step number
btnStepNumber.setSelection( getScale( ).isSetStepNumber( ) );
btnStepAuto.setSelection( !getScale( ).isSetStep( )
&& !getScale( ).isSetStepNumber( ) );
}
}
setState( );
if ( getValueType( ) == TextEditorComposite.TYPE_DATETIME )
{
parent.getShell( ).addListener( SWT.Close, new Listener( ) {
public void handleEvent( Event event )
{
if ( event.type == SWT.Close )
{
DataElement data = txtScaleMin.getDataElement( );
if ( data == null )
{
getScale( ).eUnset( ComponentPackage.eINSTANCE.getScale_Min( ) );
}
else
{
getScale( ).setMin( data );
}
data = txtScaleMax.getDataElement( );
if ( data == null )
{
getScale( ).eUnset( ComponentPackage.eINSTANCE.getScale_Max( ) );
}
else
{
getScale( ).setMax( data );
}
setState( );
}
}
} );
}
return cmpContent;
}
protected void setState( boolean bEnabled )
{
btnStepSize.setEnabled( bEnabled );
txtStepSize.setEnabled( bEnabled && btnStepSize.getSelection( ) );
btnStepNumber.setEnabled( bEnabled
&& getValueType( ) == TextEditorComposite.TYPE_NUMBERIC );
spnStepNumber.setEnabled( bEnabled
&& btnStepNumber.getSelection( )
&& getValueType( ) == TextEditorComposite.TYPE_NUMBERIC );
btnFactor.setEnabled( false );
txtFactor.setEnabled( false );
lblMin.setEnabled( bEnabled );
lblMax.setEnabled( bEnabled );
txtScaleMin.setEnabled( bEnabled );
txtScaleMax.setEnabled( bEnabled );
btnShowOutside.setEnabled( bEnabled );
lblUnit.setEnabled( bEnabled
&& btnStepSize.getSelection( )
&& getValueType( ) == TextEditorComposite.TYPE_DATETIME );
cmbScaleUnit.setEnabled( bEnabled
&& btnStepSize.getSelection( )
&& getValueType( ) == TextEditorComposite.TYPE_DATETIME );
}
protected void setState( )
{
// Could be override if needed
setState( true );
}
protected IDataElementComposite createValuePicker( Composite parent,
DataElement data, EObject eParent, String sProperty )
{
IDataElementComposite picker = null;
if ( getValueType( ) == TextEditorComposite.TYPE_NUMBERIC
|| getValueType( ) == TextEditorComposite.TYPE_NONE )
{
try
{
picker = getContext( ).getUIFactory( )
.createNumberDataElementComposite( parent,
data,
eParent,
sProperty );
}
catch ( Exception e )
{
picker = getContext( ).getUIFactory( )
.createNumberDataElementComposite( parent,
null,
eParent,
sProperty );
}
}
else if ( getValueType( ) == TextEditorComposite.TYPE_DATETIME )
{
try
{
picker = getContext( ).getUIFactory( )
.createDateTimeDataElementComposite( parent,
SWT.BORDER,
(DateTimeDataElement) data,
true,
eParent,
sProperty );
}
catch ( Exception e )
{
picker = getContext( ).getUIFactory( )
.createDateTimeDataElementComposite( parent,
SWT.BORDER,
null,
true,
eParent,
sProperty );
}
}
if ( picker != null )
{
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
gd.horizontalSpan = 3;
picker.setLayoutData( gd );
picker.addListener( this );
}
return picker;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
*/
public void handleEvent( Event event )
{
if ( event.widget.equals( txtScaleMin ) )
{
DataElement data = txtScaleMin.getDataElement( );
if ( data == null )
{
getScale( ).eUnset( ComponentPackage.eINSTANCE.getScale_Min( ) );
}
else
{
getScale( ).setMin( data );
}
setState( );
}
else if ( event.widget.equals( txtScaleMax ) )
{
DataElement data = txtScaleMax.getDataElement( );
if ( data == null )
{
getScale( ).eUnset( ComponentPackage.eINSTANCE.getScale_Max( ) );
}
else
{
getScale( ).setMax( data );
}
setState( );
}
else if ( event.widget.equals( txtStepSize ) )
{
try
{
if ( txtStepSize.getText( ).length( ) == 0 )
{
getScale( ).eUnset( ComponentPackage.eINSTANCE.getScale_Step( ) );
}
else
{
double dbl = Double.valueOf( txtStepSize.getText( ) )
.doubleValue( );
if ( dbl == 0 )
{
getScale( ).eUnset( ComponentPackage.eINSTANCE.getScale_Step( ) );
}
else
{
getScale( ).setStep( dbl );
}
}
}
catch ( NumberFormatException e1 )
{
txtStepSize.setText( String.valueOf( getScale( ).getStep( ) ) );
}
}
else if ( event.widget.equals( cmbScaleUnit ) )
{
String selectedScale = cmbScaleUnit.getSelectedItemData( );
if ( selectedScale != null )
{
getScale( ).setUnit( ScaleUnitType.getByName( selectedScale ) );
}
}
else if ( event.widget.equals( btnStepAuto ) )
{
getScale( ).unsetStepNumber( );
getScale( ).unsetStep( );
setState( );
}
else if ( event.widget.equals( btnStepSize ) )
{
getScale( ).unsetStepNumber( );
// Set step size by notification
txtStepSize.notifyListeners( SWT.Modify, null );
setState( );
}
else if ( event.widget.equals( btnStepNumber ) )
{
getScale( ).unsetStep( );
getScale( ).setStepNumber( spnStepNumber.getSelection( ) );
setState( );
}
else if ( event.widget.equals( spnStepNumber ) )
{
getScale( ).setStepNumber( spnStepNumber.getSelection( ) );
}
else if ( event.widget == btnFactor )
{
if ( btnFactor.getSelection( ) )
{
getScale( ).unsetStepNumber( );
txtFactor.notifyListeners( SWT.Modify, null );
}
else
{
getScale( ).unsetFactor( );
}
setState( );
}
else if ( event.widget == txtFactor )
{
try
{
if ( txtFactor.getText( ).length( ) == 0 )
{
getScale( ).eUnset( ComponentPackage.eINSTANCE.getScale_Factor( ) );
}
else
{
double dbl = Double.valueOf( txtFactor.getText( ) )
.doubleValue( );
if ( dbl == 0 )
{
getScale( ).eUnset( ComponentPackage.eINSTANCE.getScale_Factor( ) );
}
else
{
getScale( ).setFactor( dbl );
}
}
}
catch ( NumberFormatException e1 )
{
txtFactor.setText( String.valueOf( getScale( ).getFactor( ) ) );
}
}
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse
* .swt.events.SelectionEvent)
*/
public void widgetDefaultSelected( SelectionEvent arg0 )
{
// Nothing.
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt
* .events.SelectionEvent)
*/
public void widgetSelected( SelectionEvent event )
{
if ( event.widget == btnShowOutside )
{
if ( btnShowOutside.getSelectionState( ) == ChartCheckbox.STATE_GRAYED )
{
getScale( ).unsetShowOutside( );
}
else
{
getScale( ).setShowOutside( btnShowOutside.getSelectionState( ) == ChartCheckbox.STATE_SELECTED );
}
}
else if ( event.widget == btnAutoExpand )
{
if ( btnAutoExpand.getSelectionState( ) == ChartCheckbox.STATE_GRAYED )
{
getScale( ).unsetAutoExpand( );
}
else
{
getScale( ).setAutoExpand( btnAutoExpand.getSelectionState( ) == ChartCheckbox.STATE_SELECTED );
}
}
}
protected abstract Scale getScale( );
protected abstract Scale getDefaultVauleScale( );
/**
* Returns the type of scale value
*
* @return Constant value defined in <code>TextEditorComposite</code>
*/
protected abstract int getValueType( );
} |
package org.jdesktop.swingx;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import org.jdesktop.swingx.JXCollapsiblePane.Direction;
import org.jdesktop.swingx.action.AbstractActionExt;
/**
* @author Karl George Schaefer
*
*/
public class JXCollapsiblePaneVisualCheck extends InteractiveTestCase {
/**
* @param args
*/
public static void main(String[] args) {
JXCollapsiblePaneVisualCheck test = new JXCollapsiblePaneVisualCheck();
try {
// test.runInteractiveTests();
test.runInteractiveTests("interactive.*Zero.*");
} catch (Exception e) {
System.err.println("exception when executing interactive tests:");
e.printStackTrace();
}
}
/**
* Issue #1185-swingx: inconsistent change notification of "animatedState"
*
* Depends on value of animated: fired only if true, nothing happens on false
*
*
* Trying to resize a top-level window on collapsed state changes of a taskpane.
* Need to listen to "animationState" which is fired when animation is complete.
*/
public void interactiveDialogWithCollapsibleFalse() {
JXTaskPane pane = new JXTaskPane();
pane.setAnimated(false);
pane.setTitle("Just a TaskPane with animated property false");
final JXDialog dialog = new JXDialog(pane);
PropertyChangeListener l = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if ("animationState".equals(evt.getPropertyName())) {
dialog.pack();
}
}
};
pane.addPropertyChangeListener(l);
pane.add(new JLabel("to have some content"));
dialog.setTitle("pack on expand/collapse");
dialog.pack();
dialog.setVisible(true);
}
/**
* Trying to resize a top-level window on collapsed state changes of a taskpane.
* Need to listen to "animationState" which is fired when animation is complete.
*
* Note: works only if animated is true (see Issue #1185-swingx)
*/
public void interactiveDialogWithCollapsibleTrue() {
JXTaskPane pane = new JXTaskPane();
pane.setTitle("Just a TaskPane with animated property true");
final JXDialog dialog = new JXDialog(pane);
PropertyChangeListener l = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if ("animationState".equals(evt.getPropertyName())) {
dialog.pack();
}
}
};
pane.addPropertyChangeListener(l);
pane.add(new JLabel("to have some content"));
dialog.setTitle("pack on expand/collapse");
dialog.pack();
dialog.setVisible(true);
}
/**
* SwingX 578: Ensure that the directions work correctly.
*/
public void interactiveDirectionTest() {
JXCollapsiblePane north = new JXCollapsiblePane(Direction.UP);
JLabel label = new JLabel("<html>north1<br>north2<br>north3<br>north4<br>north5<br>north6</html>");
label.setHorizontalAlignment(SwingConstants.CENTER);
north.add(label);
JXCollapsiblePane south = new JXCollapsiblePane(Direction.DOWN);
label = new JLabel("<html>south1<br>south2<br>south3<br>south4<br>south5<br>south6</html>");
label.setHorizontalAlignment(SwingConstants.CENTER);
south.add(label);
JXCollapsiblePane west = new JXCollapsiblePane(Direction.LEFT);
west.add(new JLabel("west1west2west3west4west5west6"));
JXCollapsiblePane east = new JXCollapsiblePane(Direction.RIGHT);
east.add(new JLabel("east1east2east3east4east5east6"));
JPanel panel = new JPanel(new GridLayout(2, 2));
JButton button = new JButton(north.getActionMap().get(JXCollapsiblePane.TOGGLE_ACTION));
button.setText("UP");
panel.add(button);
button = new JButton(south.getActionMap().get(JXCollapsiblePane.TOGGLE_ACTION));
button.setText("DOWN");
panel.add(button);
button = new JButton(west.getActionMap().get(JXCollapsiblePane.TOGGLE_ACTION));
button.setText("LEFT");
panel.add(button);
button = new JButton(east.getActionMap().get(JXCollapsiblePane.TOGGLE_ACTION));
button.setText("RIGHT");
panel.add(button);
JFrame frame = wrapInFrame(panel, "Direction Animation Test");
frame.add(north, BorderLayout.NORTH);
frame.add(south, BorderLayout.SOUTH);
frame.add(west, BorderLayout.WEST);
frame.add(east, BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
}
/**
* Test case for bug 1076.
*/
public void interactiveAnimationSizingTest() {
JPanel panel = new JPanel(new BorderLayout());
final JXCollapsiblePane collPane = new JXCollapsiblePane();
collPane.setCollapsed(true);
collPane.add(new JLabel("hello!"));
collPane.setAnimated(false); // critical statement
panel.add(collPane, BorderLayout.NORTH);
JButton button = new JButton("Toggle");
button.addActionListener(collPane.getActionMap().get(
JXCollapsiblePane.TOGGLE_ACTION));
panel.add(button, BorderLayout.CENTER);
showInFrame(panel, "Animation Sizing Test");
}
/**
* Test case for bug 1087. Hidden components should not have focus.
*/
public void interactiveFocusTest() {
JPanel panel = new JPanel(new BorderLayout());
final JXCollapsiblePane instance = new JXCollapsiblePane();
panel.add(instance, BorderLayout.SOUTH);
JButton paneButton = new JButton("I do nothing");
paneButton.addFocusListener(new FocusAdapter() {
@Override
public void focusGained(FocusEvent e) {
if (instance.isCollapsed()) {
fail("Why am i getting focus?!");
}
}
});
instance.add(paneButton);
JButton button = new JButton("Toggle");
button.addActionListener(instance.getActionMap().get(
JXCollapsiblePane.TOGGLE_ACTION));
panel.add(button, BorderLayout.CENTER);
showInFrame(panel, "Focus Test");
}
/**
* Test case for bug 1181. scrollXXXToVisible does not work.
*/
public void interactiveScrollToVisibleTest() {
JPanel panel = new JPanel(new BorderLayout());
JXCollapsiblePane pane = new JXCollapsiblePane();
pane.setScrollableTracksViewportHeight(false);
panel.add(new JScrollPane(pane), BorderLayout.SOUTH);
final JXTree tree = new JXTree();
pane.add(tree);
JXFindBar find = new JXFindBar(tree.getSearchable());
panel.add(find, BorderLayout.CENTER);
showInFrame(panel, "Scroll Rect To Visible Test");
SwingUtilities.invokeLater(new Runnable() {
public void run() {
tree.expandAll();
}
});
}
public void interactiveScrollRectToVisible() {
final JXTree tree = new JXTree();
tree.expandAll();
JXTaskPane pane = new JXTaskPane();
pane.add(tree);
JComponent component = new JPanel(new BorderLayout());
component.add(pane);
JXFrame frame = wrapWithScrollingInFrame(component, "scroll to last row must work");
Action action = new AbstractActionExt("scrollToLastRow") {
@Override
public void actionPerformed(ActionEvent e) {
tree.scrollRowToVisible(tree.getRowCount()- 1);
}
};
addAction(frame, action);
// small dimension, make sure there is something to scroll
show(frame, 300, 200);
}
/**
* Test case for bug 433. When the initial size is 0 expansion fails.
*/
public void interactiveZeroInitialHeightTest() {
JPanel panel = new JPanel(new BorderLayout());
final JXCollapsiblePane collPane = new JXCollapsiblePane();
// collPane.setAnimated(false);
collPane.setCollapsed(true);
collPane.setCollapsed(false);
collPane.add(new JLabel("hello!"));
panel.add(collPane, BorderLayout.NORTH);
JButton button = new JButton("Toggle");
button.addActionListener(collPane.getActionMap().get(
JXCollapsiblePane.TOGGLE_ACTION));
panel.add(button, BorderLayout.CENTER);
showInFrame(panel, "Initial Sizing Test");
}
/**
* do nothing test - keep the testrunner happy.
*/
public void testDummy() {
}
} |
/**
* Owned by DESY.
*/
package org.csstudio.platform.internal.model;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.csstudio.platform.model.AbstractControlSystemItemFactory;
import org.csstudio.platform.model.IProcessVariable;
import org.junit.Test;
/**
* Test class for {@link ControlSystemItemFactoriesRegistry}.
*
* @author Sven Wende
*
*/
public final class ControlSystemItemFactoriesRegistryTest {
/**
* Test method for {@link org.csstudio.platform.internal.model.ControlSystemItemFactoriesRegistry#getInstance()}.
*/
@Test
public void testGetInstance() {
ControlSystemItemFactoriesRegistry registry = ControlSystemItemFactoriesRegistry.getInstance();
assertNotNull(registry);
ControlSystemItemFactoriesRegistry registry2 = ControlSystemItemFactoriesRegistry.getInstance();
assertEquals(registry, registry2);
}
/**
* Test method for {@link org.csstudio.platform.internal.model.ControlSystemItemFactoriesRegistry#getControlSystemItemFactory(java.lang.String)}.
*/
@Test
public void testGetControlSystemItemFactory() {
// get an existing factory
AbstractControlSystemItemFactory factory = ControlSystemItemFactoriesRegistry.getInstance().getControlSystemItemFactory(IProcessVariable.TYPE_ID);
assertNotNull(factory);
}
} |
package org.eclipse.birt.report.engine.script.internal.instance;
import org.eclipse.birt.report.engine.api.script.instance.IAutoTextInstance;
import org.eclipse.birt.report.engine.content.IAutoTextContent;
import org.eclipse.birt.report.engine.executor.ExecutionContext;
public class AutoTextInstance extends ReportElementInstance
implements
IAutoTextInstance
{
IAutoTextContent autoText;
public AutoTextInstance( IAutoTextContent autoText,
ExecutionContext context, RunningState runningState )
{
super( autoText, context, runningState );
this.autoText = autoText;
}
public void setText( String text )
{
if ( runningState != RunningState.RENDER )
{
throw new UnsupportedOperationException(
"setText can only be invoked in onRender" );
}
autoText.setText( text );
}
public String getText( )
{
return autoText.getText( );
}
} |
package org.innovateuk.ifs.application.populator;
import com.google.common.collect.Iterables;
import org.innovateuk.ifs.application.resource.ApplicationResource;
import org.innovateuk.ifs.application.resource.QuestionResource;
import org.innovateuk.ifs.application.resource.SectionResource;
import org.innovateuk.ifs.application.resource.SectionType;
import org.innovateuk.ifs.application.service.ApplicationService;
import org.innovateuk.ifs.application.service.QuestionService;
import org.innovateuk.ifs.application.service.SectionService;
import org.innovateuk.ifs.application.viewmodel.NavigationViewModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import java.util.List;
import java.util.Optional;
import static org.innovateuk.ifs.competition.resource.CompetitionStatus.OPEN;
@Component
public class ApplicationNavigationPopulator {
private static final String SECTION_URL = "/section/";
private static final String QUESTION_URL = "/question/";
private static final String APPLICATION_BASE_URL = "/application/";
@Autowired
private QuestionService questionService;
@Autowired
private SectionService sectionService;
@Autowired
private ApplicationService applicationService;
public NavigationViewModel addNavigation(SectionResource section, Long applicationId) {
return addNavigation(section, applicationId, null);
}
public NavigationViewModel addNavigation(SectionResource section, Long applicationId, List<SectionType> sectionTypesToSkip) {
NavigationViewModel navigationViewModel = new NavigationViewModel();
if (section == null) {
return navigationViewModel;
}
Optional<QuestionResource> previousQuestion = questionService.getPreviousQuestionBySection(section.getId());
addPreviousQuestionToModel(previousQuestion, applicationId, navigationViewModel, sectionTypesToSkip);
Optional<QuestionResource> nextQuestion = questionService.getNextQuestionBySection(section.getId());
addNextQuestionToModel(nextQuestion, applicationId, navigationViewModel, sectionTypesToSkip);
return navigationViewModel;
}
public NavigationViewModel addNavigation(QuestionResource question, Long applicationId) {
NavigationViewModel navigationViewModel = new NavigationViewModel();
if (question == null) {
return navigationViewModel;
}
Optional<QuestionResource> previousQuestion = questionService.getPreviousQuestion(question.getId());
addPreviousQuestionToModel(previousQuestion, applicationId, navigationViewModel, null);
Optional<QuestionResource> nextQuestion = questionService.getNextQuestion(question.getId());
addNextQuestionToModel(nextQuestion, applicationId, navigationViewModel, null);
return navigationViewModel;
}
private void addPreviousQuestionToModel(Optional<QuestionResource> previousQuestionOptional, Long applicationId,
NavigationViewModel navigationViewModel, List<SectionType> sectionTypesToSkip) {
while (previousQuestionOptional.isPresent()) {
String previousUrl;
String previousText;
QuestionResource previousQuestion = previousQuestionOptional.get();
SectionResource previousSection = sectionService.getSectionByQuestionId(previousQuestion.getId());
if (sectionTypesToSkip != null && sectionTypesToSkip.contains(previousSection.getType())) {
previousQuestionOptional = questionService.getPreviousQuestion(previousSection.getQuestions().get(0));
} else {
if (previousSection.isQuestionGroup()) {
previousUrl = APPLICATION_BASE_URL + applicationId + "/form" + SECTION_URL + previousSection.getId();
previousText = previousSection.getName();
} else {
previousUrl = APPLICATION_BASE_URL + applicationId + "/form" + QUESTION_URL + previousQuestion.getId();
previousText = previousQuestion.getShortName();
}
navigationViewModel.setPreviousUrl(previousUrl);
navigationViewModel.setPreviousText(previousText);
break;
}
}
}
private void addNextQuestionToModel(Optional<QuestionResource> nextQuestionOptional, Long applicationId,
NavigationViewModel navigationViewModel, List<SectionType> sectionTypesToSkip) {
while (nextQuestionOptional.isPresent()) {
String nextUrl;
String nextText;
QuestionResource nextQuestion = nextQuestionOptional.get();
SectionResource nextSection = sectionService.getSectionByQuestionId(nextQuestion.getId());
if (sectionTypesToSkip != null && sectionTypesToSkip.contains(nextSection.getType())) {
Long lastQuestion = Iterables.getLast(nextSection.getQuestions());
nextQuestionOptional = questionService.getNextQuestion(lastQuestion);
} else {
if (nextSection.isQuestionGroup()) {
nextUrl = APPLICATION_BASE_URL + applicationId + "/form" + SECTION_URL + nextSection.getId();
nextText = nextSection.getName();
} else {
nextUrl = APPLICATION_BASE_URL + applicationId + "/form" + QUESTION_URL + nextQuestion.getId();
nextText = nextQuestion.getShortName();
}
navigationViewModel.setNextUrl(nextUrl);
navigationViewModel.setNextText(nextText);
break;
}
}
}
/**
* This method creates a URL looking at referer in request. Because 'back' will be different depending on
* whether the user arrived at this page via PS pages and summary vs App pages input form/overview. (INFUND-6892)
*/
public void addAppropriateBackURLToModel(Long applicationId, Model model, SectionResource section) {
if (section != null && SectionType.FINANCE.equals(section.getType().getParent().orElse(null))) {
model.addAttribute("backTitle", "Your finances");
model.addAttribute("backURL", "/application/" + applicationId + "/form/" + SectionType.FINANCE.name());
} else {
ApplicationResource application = applicationService.getById(applicationId);
String backURL = "/application/" + applicationId;
if (eitherApplicationOrCompetitionAreNotOpen(application)) {
model.addAttribute("backTitle", "Application summary");
backURL += "/summary";
} else {
model.addAttribute("backTitle", "Application overview");
}
model.addAttribute("backURL", backURL);
}
}
private boolean eitherApplicationOrCompetitionAreNotOpen(ApplicationResource application) {
return !application.isOpen() || !application.getCompetitionStatus().equals(OPEN);
}
} |
package org.mockserver.integration.server;
import org.junit.Test;
import org.mockserver.client.netty.NettyHttpClient;
import org.mockserver.client.serialization.ExpectationSerializer;
import org.mockserver.echo.http.EchoServer;
import org.mockserver.logging.MockServerLogger;
import org.mockserver.matchers.TimeToLive;
import org.mockserver.mock.Expectation;
import org.mockserver.model.*;
import org.mockserver.verify.VerificationTimes;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import static io.netty.handler.codec.http.HttpHeaderNames.HOST;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.StringStartsWith.startsWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import static org.mockserver.character.Character.NEW_LINE;
import static org.mockserver.matchers.Times.exactly;
import static org.mockserver.matchers.Times.once;
import static org.mockserver.model.Cookie.cookie;
import static org.mockserver.model.Header.header;
import static org.mockserver.model.HttpClassCallback.callback;
import static org.mockserver.model.HttpForward.forward;
import static org.mockserver.model.HttpOverrideForwardedRequest.forwardOverriddenRequest;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.notFoundResponse;
import static org.mockserver.model.HttpResponse.response;
import static org.mockserver.model.HttpStatusCode.OK_200;
import static org.mockserver.model.HttpTemplate.template;
import static org.mockserver.model.Parameter.param;
import static org.mockserver.model.StringBody.exact;
/**
* @author jamesdbloom
*/
public abstract class AbstractBasicMockingIntegrationTest extends AbstractMockingIntegrationTestBase {
@Test
public void shouldForwardRequestInHTTP() {
// when
mockServerClient
.when(
request()
.withPath(calculatePath("echo"))
)
.forward(
forward()
.withHost("127.0.0.1")
.withPort(getEchoServerPort())
);
// then
// - in http
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withHeaders(
header("x-test", "test_headers_and_body")
)
.withBody("an_example_body_http"),
makeRequest(
request()
.withPath(calculatePath("echo"))
.withMethod("POST")
.withHeaders(
header("x-test", "test_headers_and_body")
)
.withBody("an_example_body_http"),
headersToIgnore)
);
// - in https
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withHeaders(
header("x-test", "test_headers_and_body")
)
.withBody("an_example_body_https"),
makeRequest(
request()
.withSecure(true)
.withPath(calculatePath("echo"))
.withMethod("POST")
.withHeaders(
header("x-test", "test_headers_and_body")
)
.withBody("an_example_body_https"),
headersToIgnore)
);
}
@Test
public void shouldForwardRequestInHTTPS() {
EchoServer secureEchoServer = new EchoServer(true);
try {
// when
mockServerClient
.when(
request()
.withPath(calculatePath("echo"))
)
.forward(
forward()
.withHost("127.0.0.1")
.withPort(secureEchoServer.getPort())
.withScheme(HttpForward.Scheme.HTTPS)
);
// then
// - in http
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withHeaders(
header("x-test", "test_headers_and_body")
)
.withBody("an_example_body_http"),
makeRequest(
request()
.withPath(calculatePath("echo"))
.withMethod("POST")
.withHeaders(
header("x-test", "test_headers_and_body")
)
.withBody("an_example_body_http"),
headersToIgnore)
);
// - in https
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withHeaders(
header("x-test", "test_headers_and_body")
)
.withBody("an_example_body_https"),
makeRequest(
request()
.withSecure(true)
.withPath(calculatePath("echo"))
.withMethod("POST")
.withHeaders(
header("x-test", "test_headers_and_body")
)
.withBody("an_example_body_https"),
headersToIgnore)
);
} finally {
secureEchoServer.stop();
}
}
@Test
public void shouldForwardOverriddenRequest() {
// given
EchoServer echoServer = new EchoServer(false);
EchoServer secureEchoServer = new EchoServer(true);
try {
// when
mockServerClient
.when(
request()
.withPath(calculatePath("echo"))
.withSecure(false)
)
.forward(
forwardOverriddenRequest(
request()
.withHeader("Host", "localhost:" + echoServer.getPort())
.withBody("some_overridden_body")
).withDelay(MILLISECONDS, 10)
);
mockServerClient
.when(
request()
.withPath(calculatePath("echo"))
.withSecure(true)
)
.forward(
forwardOverriddenRequest(
request()
.withHeader("Host", "localhost:" + secureEchoServer.getPort())
.withBody("some_overridden_body")
).withDelay(MILLISECONDS, 10)
);
// then
// - in http
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withHeaders(
header("x-test", "test_headers_and_body")
)
.withBody("some_overridden_body"),
makeRequest(
request()
.withPath(calculatePath("echo"))
.withMethod("POST")
.withHeaders(
header("x-test", "test_headers_and_body")
)
.withBody("an_example_body_http"),
headersToIgnore
)
);
// - in https
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withHeaders(
header("x-test", "test_headers_and_body_https")
)
.withBody("some_overridden_body"),
makeRequest(
request()
.withSecure(true)
.withPath(calculatePath("echo"))
.withMethod("POST")
.withHeaders(
header("x-test", "test_headers_and_body_https")
)
.withBody("an_example_body_https"),
headersToIgnore)
);
} finally {
echoServer.stop();
secureEchoServer.stop();
}
}
@Test
public void shouldCallbackForForwardToSpecifiedClassWithPrecannedResponse() {
// given
EchoServer echoServer = new EchoServer(false);
EchoServer secureEchoServer = new EchoServer(true);
// when
mockServerClient
.when(
request()
.withPath(calculatePath("echo"))
)
.forward(
callback()
.withCallbackClass("org.mockserver.integration.callback.PrecannedTestExpectationForwardCallback")
);
// then
// - in http
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withHeaders(
header("x-test", "test_headers_and_body")
)
.withBody("some_overridden_body"),
makeRequest(
request()
.withPath(calculatePath("echo"))
.withMethod("POST")
.withHeaders(
header("x-test", "test_headers_and_body"),
header("x-echo-server-port", echoServer.getPort())
)
.withBody("an_example_body_http"),
headersToIgnore
)
);
// - in https
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withHeaders(
header("x-test", "test_headers_and_body")
)
.withBody("some_overridden_body"),
makeRequest(
request()
.withSecure(true)
.withPath(calculatePath("echo"))
.withMethod("POST")
.withHeaders(
header("x-test", "test_headers_and_body"),
header("x-echo-server-port", secureEchoServer.getPort())
)
.withBody("an_example_body_https"),
headersToIgnore
)
);
}
@Test
public void shouldForwardTemplateInVelocity() {
EchoServer secureEchoServer = new EchoServer(false);
try {
// when
mockServerClient
.when(
request()
.withPath(calculatePath("echo"))
)
.forward(
template(HttpTemplate.TemplateType.VELOCITY,
"{" + NEW_LINE +
" 'path' : \"/somePath\"," + NEW_LINE +
" 'headers' : [ {" + NEW_LINE +
" 'name' : \"Host\"," + NEW_LINE +
" 'values' : [ \"127.0.0.1:" + secureEchoServer.getPort() + "\" ]" + NEW_LINE +
" }, {" + NEW_LINE +
" 'name' : \"x-test\"," + NEW_LINE +
" 'values' : [ \"$!request.headers['x-test'][0]\" ]" + NEW_LINE +
" } ]," + NEW_LINE +
" 'body': \"{'name': 'value'}\"" + NEW_LINE +
"}")
.withDelay(MILLISECONDS, 10)
);
// then
// - in http
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withHeaders(
header("x-test", "test_headers_and_body")
)
.withBody("{'name': 'value'}"),
makeRequest(
request()
.withPath(calculatePath("echo"))
.withMethod("POST")
.withHeaders(
header("x-test", "test_headers_and_body")
)
.withBody("an_example_body_http"),
headersToIgnore
)
);
// - in https
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withHeaders(
header("x-test", "test_headers_and_body_https")
)
.withBody("{'name': 'value'}"),
makeRequest(
request()
.withSecure(true)
.withPath(calculatePath("echo"))
.withMethod("POST")
.withHeaders(
header("x-test", "test_headers_and_body_https")
)
.withBody("an_example_body_https"),
headersToIgnore)
);
} finally {
secureEchoServer.stop();
}
}
@Test
public void shouldAllowSimultaneousForwardAndResponseExpectations() {
// when
mockServerClient
.when(
request()
.withPath(calculatePath("echo")),
once()
)
.forward(
forward()
.withHost("127.0.0.1")
.withPort(getEchoServerPort())
);
mockServerClient
.when(
request()
.withPath(calculatePath("test_headers_and_body")),
once()
)
.respond(
response()
.withBody("some_body")
);
// then
// - forward
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withHeaders(
header("x-test", "test_headers_and_body")
)
.withBody("an_example_body"),
makeRequest(
request()
.withPath(calculatePath("echo"))
.withMethod("POST")
.withHeaders(
header("x-test", "test_headers_and_body")
)
.withBody("an_example_body"),
headersToIgnore)
);
// - respond
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withBody("some_body"),
makeRequest(
request()
.withPath(calculatePath("test_headers_and_body")),
headersToIgnore)
);
// - no response or forward
assertEquals(
response()
.withStatusCode(HttpStatusCode.NOT_FOUND_404.code())
.withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()),
makeRequest(
request()
.withPath(calculatePath("test_headers_and_body")),
headersToIgnore)
);
}
@Test
public void shouldCallbackForResponseToSpecifiedClassWithPrecannedResponse() {
// when
mockServerClient
.when(
request()
.withPath(calculatePath("callback"))
)
.respond(
callback()
.withCallbackClass("org.mockserver.integration.callback.PrecannedTestExpectationResponseCallback")
);
// then
// - in http
assertEquals(
response()
.withStatusCode(HttpStatusCode.ACCEPTED_202.code())
.withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase())
.withHeaders(
header("x-callback", "test_callback_header")
)
.withBody("a_callback_response"),
makeRequest(
request()
.withPath(calculatePath("callback"))
.withMethod("POST")
.withHeaders(
header("x-test", "test_headers_and_body")
)
.withBody("an_example_body_http"),
headersToIgnore
)
);
// - in https
assertEquals(
response()
.withStatusCode(HttpStatusCode.ACCEPTED_202.code())
.withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase())
.withHeaders(
header("x-callback", "test_callback_header")
)
.withBody("a_callback_response"),
makeRequest(
request()
.withSecure(true)
.withPath(calculatePath("callback"))
.withMethod("POST")
.withHeaders(
header("x-test", "test_headers_and_body")
)
.withBody("an_example_body_https"),
headersToIgnore
)
);
}
@Test
public void shouldSupportBatchedExpectations() throws Exception {
// when
new NettyHttpClient().sendRequest(
request()
.withMethod("PUT")
.withHeader(HOST.toString(), "localhost:" + this.getServerPort())
.withPath(addContextToPath("/expectation"))
.withBody("" +
"[" +
new ExpectationSerializer(new MockServerLogger())
.serialize(
new Expectation(request("/path_one"), once(), TimeToLive.unlimited())
.thenRespond(response().withBody("some_body_one"))
) + "," +
new ExpectationSerializer(new MockServerLogger())
.serialize(
new Expectation(request("/path_two"), once(), TimeToLive.unlimited())
.thenRespond(response().withBody("some_body_two"))
) + "," +
new ExpectationSerializer(new MockServerLogger())
.serialize(
new Expectation(request("/path_three"), once(), TimeToLive.unlimited())
.thenRespond(response().withBody("some_body_three"))
) +
"]"
)
).get(10, TimeUnit.SECONDS);
// then
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withBody("some_body_one"),
makeRequest(
request()
.withPath(calculatePath("/path_one")),
headersToIgnore)
);
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withBody("some_body_two"),
makeRequest(
request()
.withPath(calculatePath("/path_two")),
headersToIgnore)
);
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withBody("some_body_three"),
makeRequest(
request()
.withPath(calculatePath("/path_three")),
headersToIgnore)
);
}
@Test
public void shouldReturnResponseWithOnlyBody() {
// when
mockServerClient.when(request()).respond(response().withBody("some_body"));
// then
// - in http
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withBody("some_body"),
makeRequest(
request()
.withPath(calculatePath("")),
headersToIgnore)
);
// - in https
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withBody("some_body"),
makeRequest(
request()
.withSecure(true)
.withPath(calculatePath("")),
headersToIgnore)
);
}
@Test
public void shouldReturnResponseWithOnlyStatusCode() {
// when
mockServerClient
.when(
request()
.withMethod("POST")
.withPath(calculatePath("some_path"))
)
.respond(
response()
.withStatusCode(200)
);
// then
// - in http
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase()),
makeRequest(
request()
.withPath(calculatePath("some_path"))
.withMethod("POST"),
headersToIgnore)
);
// - in https
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase()),
makeRequest(
request()
.withSecure(true)
.withPath(calculatePath("some_path"))
.withMethod("POST"),
headersToIgnore)
);
}
@Test
public void shouldReturnResponseByMatchingStringBody() {
// when
mockServerClient
.when(
request()
.withBody(
exact("some_random_body")
),
exactly(2)
)
.respond(
response()
.withBody("some_string_body_response")
);
// then
// - in http
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withBody("some_string_body_response"),
makeRequest(
request()
.withMethod("POST")
.withPath(calculatePath("some_path"))
.withBody("some_random_body"),
headersToIgnore)
);
// - in https
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withBody("some_string_body_response"),
makeRequest(
request()
.withSecure(true)
.withMethod("POST")
.withPath(calculatePath("some_path"))
.withBody("some_random_body"),
headersToIgnore)
);
}
@Test
public void shouldReturnResponseForExpectationWithDelay() {
// when
mockServerClient
.when(
request()
.withPath(calculatePath("some_path1"))
)
.respond(
response()
.withBody("some_body1")
.withDelay(new Delay(MILLISECONDS, 10))
);
mockServerClient
.when(
request()
.withPath(calculatePath("some_path2"))
)
.respond(
response()
.withBody("some_body2")
.withDelay(new Delay(MILLISECONDS, 20))
);
// then
// - in http
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withBody("some_body2"),
makeRequest(
request()
.withPath(calculatePath("some_path2")),
headersToIgnore)
);
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withBody("some_body1"),
makeRequest(
request()
.withPath(calculatePath("some_path1")),
headersToIgnore)
);
// - in https
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withBody("some_body2"),
makeRequest(
request()
.withSecure(true)
.withPath(calculatePath("some_path2")),
headersToIgnore)
);
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withBody("some_body1"),
makeRequest(
request()
.withSecure(true)
.withPath(calculatePath("some_path1")),
headersToIgnore)
);
}
@Test
public void shouldReturnResponseFromVelocityTemplate() {
// when
mockServerClient
.when(
request()
.withPath(calculatePath("some_path"))
)
.respond(
template(
HttpTemplate.TemplateType.VELOCITY,
"{" + NEW_LINE +
" \"statusCode\": 200," + NEW_LINE +
" \"headers\": [ { \"name\": \"name\", \"values\": [ \"$!request.headers['name'][0]\" ] } ]," + NEW_LINE +
" \"body\": \"$!request.body\"" + NEW_LINE +
"}" + NEW_LINE
)
);
// then
// - in http
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withHeader("name", "value")
.withBody("some_request_body"),
makeRequest(
request()
.withPath(calculatePath("some_path"))
.withHeader("name", "value")
.withBody("some_request_body"),
headersToIgnore)
);
// - in https
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withHeader("name", "value")
.withBody("some_request_body"),
makeRequest(
request()
.withSecure(true)
.withPath(calculatePath("some_path"))
.withHeader("name", "value")
.withBody("some_request_body"),
headersToIgnore)
);
}
@Test
public void shouldReturnResponseByMatchingPathAndMethod() {
// when
mockServerClient
.when(
request()
.withMethod("GET")
.withPath(calculatePath("some_pathRequest"))
)
.respond(
response()
.withStatusCode(HttpStatusCode.ACCEPTED_202.code())
.withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase())
.withBody("some_body_response")
);
// then
// - in http
assertEquals(
response()
.withStatusCode(HttpStatusCode.ACCEPTED_202.code())
.withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase())
.withBody("some_body_response"),
makeRequest(
request()
.withMethod("GET")
.withPath(calculatePath("some_pathRequest"))
.withQueryStringParameters(
param("queryStringParameterOneName", "queryStringParameterOneValue"),
param("queryStringParameterTwoName", "queryStringParameterTwoValue")
)
.withHeaders(header("headerNameRequest", "headerValueRequest"))
.withCookies(cookie("cookieNameRequest", "cookieValueRequest")),
headersToIgnore)
);
// - in https
assertEquals(
response()
.withStatusCode(HttpStatusCode.ACCEPTED_202.code())
.withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase())
.withBody("some_body_response"),
makeRequest(
request()
.withMethod("GET")
.withSecure(true)
.withPath(calculatePath("some_pathRequest"))
.withQueryStringParameters(
param("queryStringParameterOneName", "queryStringParameterOneValue"),
param("queryStringParameterTwoName", "queryStringParameterTwoValue")
)
.withHeaders(header("headerNameRequest", "headerValueRequest"))
.withCookies(cookie("cookieNameRequest", "cookieValueRequest")),
headersToIgnore)
);
}
@Test
public void shouldNotReturnResponseForNonMatchingBody() {
// when
mockServerClient
.when(
request()
.withMethod("GET")
.withPath(calculatePath("some_path"))
.withQueryStringParameters(
param("queryStringParameterOneName", "queryStringParameterOneValue"),
param("queryStringParameterTwoName", "queryStringParameterTwoValue")
)
.withBody(exact("some_body"))
.withHeaders(header("headerName", "headerValue"))
.withCookies(cookie("cookieName", "cookieValue"))
)
.respond(
response()
.withStatusCode(HttpStatusCode.ACCEPTED_202.code())
.withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase())
.withBody("some_body")
.withHeaders(header("headerName", "headerValue"))
.withCookies(cookie("cookieName", "cookieValue"))
);
// then
// - in http
assertEquals(
response()
.withStatusCode(HttpStatusCode.NOT_FOUND_404.code())
.withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()),
makeRequest(
request()
.withMethod("GET")
.withPath(calculatePath("some_path"))
.withQueryStringParameters(
param("queryStringParameterOneName", "queryStringParameterOneValue"),
param("queryStringParameterTwoName", "queryStringParameterTwoValue")
)
.withBody(exact("some_other_body"))
.withHeaders(header("headerName", "headerValue"))
.withCookies(cookie("cookieName", "cookieValue")),
headersToIgnore)
);
// - in https
assertEquals(
response()
.withStatusCode(HttpStatusCode.NOT_FOUND_404.code())
.withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()),
makeRequest(
request()
.withMethod("GET")
.withSecure(true)
.withPath(calculatePath("some_path"))
.withQueryStringParameters(
param("queryStringParameterOneName", "queryStringParameterOneValue"),
param("queryStringParameterTwoName", "queryStringParameterTwoValue")
)
.withBody(exact("some_other_body"))
.withHeaders(header("headerName", "headerValue"))
.withCookies(cookie("cookieName", "cookieValue")),
headersToIgnore)
);
}
@Test
public void shouldNotReturnResponseForNonMatchingPath() {
// when
mockServerClient
.when(
request()
.withMethod("GET")
.withPath(calculatePath("some_path"))
.withQueryStringParameters(
param("queryStringParameterOneName", "queryStringParameterOneValue"),
param("queryStringParameterTwoName", "queryStringParameterTwoValue")
)
.withBody(exact("some_body"))
.withHeaders(header("headerName", "headerValue"))
.withCookies(cookie("cookieName", "cookieValue"))
)
.respond(
response()
.withStatusCode(HttpStatusCode.ACCEPTED_202.code())
.withReasonPhrase(HttpStatusCode.ACCEPTED_202.reasonPhrase())
.withBody("some_body")
.withHeaders(header("headerName", "headerValue"))
.withCookies(cookie("cookieName", "cookieValue"))
);
// then
// - in http
assertEquals(
response()
.withStatusCode(HttpStatusCode.NOT_FOUND_404.code())
.withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()),
makeRequest(
request()
.withMethod("GET")
.withPath(calculatePath("some_other_path"))
.withQueryStringParameters(
param("queryStringParameterOneName", "queryStringParameterOneValue"),
param("queryStringParameterTwoName", "queryStringParameterTwoValue")
)
.withBody(exact("some_body"))
.withHeaders(header("headerName", "headerValue"))
.withCookies(cookie("cookieName", "cookieValue")),
headersToIgnore)
);
// - in https
assertEquals(
response()
.withStatusCode(HttpStatusCode.NOT_FOUND_404.code())
.withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()),
makeRequest(
request()
.withMethod("GET")
.withSecure(true)
.withPath(calculatePath("some_other_path"))
.withQueryStringParameters(
param("queryStringParameterOneName", "queryStringParameterOneValue"),
param("queryStringParameterTwoName", "queryStringParameterTwoValue")
)
.withBody(exact("some_body"))
.withHeaders(header("headerName", "headerValue"))
.withCookies(cookie("cookieName", "cookieValue")),
headersToIgnore)
);
}
@Test
public void shouldVerifyReceivedRequests() {
// when
mockServerClient
.when(
request()
.withPath(calculatePath("some_path")), exactly(2)
)
.respond(
response()
.withBody("some_body")
);
// then
// - in http
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withBody("some_body"),
makeRequest(
request()
.withPath(calculatePath("some_path")),
headersToIgnore)
);
mockServerClient.verify(request()
.withPath(calculatePath("some_path")));
mockServerClient.verify(request()
.withPath(calculatePath("some_path")), VerificationTimes.exactly(1));
// - in https
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withBody("some_body"),
makeRequest(
request()
.withSecure(true)
.withPath(calculatePath("some_path")),
headersToIgnore)
);
mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.atLeast(1));
mockServerClient.verify(request().withPath(calculatePath("some_path")), VerificationTimes.exactly(2));
}
@Test
public void shouldVerifyNotEnoughRequestsReceived() {
// when
mockServerClient.when(request().withPath(calculatePath("some_path")), exactly(2)).respond(response().withBody("some_body"));
// then
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withBody("some_body"),
makeRequest(
request()
.withPath(calculatePath("some_path")),
headersToIgnore)
);
try {
mockServerClient.verify(request()
.withPath(calculatePath("some_path")), VerificationTimes.atLeast(2));
fail();
} catch (AssertionError ae) {
assertThat(ae.getMessage(), startsWith("Request not found at least 2 times, expected:<{" + NEW_LINE +
" \"path\" : \"" + calculatePath("some_path") + "\"" + NEW_LINE +
"}> but was:<{" + NEW_LINE +
" \"method\" : \"GET\"," + NEW_LINE +
" \"path\" : \"" + calculatePath("some_path") + "\"," + NEW_LINE));
}
}
@Test
public void shouldVerifyNoRequestsReceived() {
// when
mockServerClient.reset();
// then
mockServerClient.verifyZeroInteractions();
}
@Test
public void shouldVerifySequenceOfRequestsReceived() {
// when
mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(6)).respond(response().withBody("some_body"));
// then
assertEquals(
response("some_body"),
makeRequest(
request().withPath(calculatePath("some_path_one")),
headersToIgnore)
);
assertEquals(
response("some_body"),
makeRequest(
request().withPath(calculatePath("some_path_two")),
headersToIgnore)
);
assertEquals(
response("some_body"),
makeRequest(
request().withPath(calculatePath("some_path_three")),
headersToIgnore)
);
mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_three")));
mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two")));
mockServerClient.verify(request(calculatePath("some_path_one")), request(calculatePath("some_path_two")), request(calculatePath("some_path_three")));
}
@Test
public void shouldRetrieveRecordedRequests() {
// when
mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body"));
assertEquals(
response("some_body"),
makeRequest(
request().withPath(calculatePath("some_path_one")),
headersToIgnore)
);
assertEquals(
notFoundResponse(),
makeRequest(
request().withPath(calculatePath("not_found")),
headersToIgnore)
);
assertEquals(
response("some_body"),
makeRequest(
request().withPath(calculatePath("some_path_three")),
headersToIgnore)
);
// then
verifyRequestsMatches(
mockServerClient.retrieveRecordedRequests(request().withPath(calculatePath("some_path.*"))),
request(calculatePath("some_path_one")),
request(calculatePath("some_path_three"))
);
verifyRequestsMatches(
mockServerClient.retrieveRecordedRequests(request()),
request(calculatePath("some_path_one")),
request(calculatePath("not_found")),
request(calculatePath("some_path_three"))
);
verifyRequestsMatches(
mockServerClient.retrieveRecordedRequests(null),
request(calculatePath("some_path_one")),
request(calculatePath("not_found")),
request(calculatePath("some_path_three"))
);
}
@Test
public void shouldRetrieveActiveExpectations() {
// when
HttpRequest complexRequest = request()
.withPath(calculatePath("some_path.*"))
.withHeader("some", "header")
.withQueryStringParameter("some", "parameter")
.withCookie("some", "parameter")
.withBody("some_body");
mockServerClient.when(complexRequest, exactly(4))
.respond(response().withBody("some_body"));
mockServerClient.when(request().withPath(calculatePath("some_path.*")))
.respond(response().withBody("some_body"));
mockServerClient.when(request().withPath(calculatePath("some_other_path")))
.respond(response().withBody("some_other_body"));
mockServerClient.when(request().withPath(calculatePath("some_forward_path")))
.forward(forward());
// then
assertThat(
mockServerClient.retrieveActiveExpectations(request().withPath(calculatePath("some_path.*"))),
arrayContaining(
new Expectation(complexRequest, exactly(4), TimeToLive.unlimited())
.thenRespond(response().withBody("some_body")),
new Expectation(request().withPath(calculatePath("some_path.*")))
.thenRespond(response().withBody("some_body"))
)
);
assertThat(
mockServerClient.retrieveActiveExpectations(null),
arrayContaining(
new Expectation(complexRequest, exactly(4), TimeToLive.unlimited())
.thenRespond(response().withBody("some_body")),
new Expectation(request().withPath(calculatePath("some_path.*")))
.thenRespond(response().withBody("some_body")),
new Expectation(request().withPath(calculatePath("some_other_path")))
.thenRespond(response().withBody("some_other_body")),
new Expectation(request().withPath(calculatePath("some_forward_path")))
.thenForward(forward())
)
);
assertThat(
mockServerClient.retrieveActiveExpectations(request()),
arrayContaining(
new Expectation(complexRequest, exactly(4), TimeToLive.unlimited())
.thenRespond(response().withBody("some_body")),
new Expectation(request().withPath(calculatePath("some_path.*")))
.thenRespond(response().withBody("some_body")),
new Expectation(request().withPath(calculatePath("some_other_path")))
.thenRespond(response().withBody("some_other_body")),
new Expectation(request().withPath(calculatePath("some_forward_path")))
.thenForward(forward())
)
);
}
@Test
public void shouldRetrieveRecordedExpectations() {
// when
EchoServer secureEchoServer = new EchoServer(false);
try {
mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).forward(
forward()
.withHost("127.0.0.1")
.withPort(secureEchoServer.getPort())
);
HttpRequest complexRequest = request()
.withPath(calculatePath("some_path_one"))
.withHeader("some", "header")
.withQueryStringParameter("some", "parameter")
.withCookie("some", "parameter")
.withBody("some_body_one");
assertEquals(
response("some_body_one")
.withHeader("some", "header")
.withHeader("cookie", "some=parameter")
.withHeader("set-cookie", "some=parameter")
.withCookie("some", "parameter"),
makeRequest(
complexRequest,
headersToIgnore
)
);
assertEquals(
response("some_body_three"),
makeRequest(
request()
.withPath(calculatePath("some_path_three"))
.withBody("some_body_three"),
headersToIgnore
)
);
// then
Expectation[] recordedExpectations = mockServerClient.retrieveRecordedExpectations(request().withPath(calculatePath("some_path_one")));
assertThat(recordedExpectations.length, is(1));
verifyRequestsMatches(
new HttpRequest[]{
recordedExpectations[0].getHttpRequest()
},
request(calculatePath("some_path_one")).withBody("some_body_one")
);
assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one"));
// and
recordedExpectations = mockServerClient.retrieveRecordedExpectations(request());
assertThat(recordedExpectations.length, is(2));
verifyRequestsMatches(
new HttpRequest[]{
recordedExpectations[0].getHttpRequest(),
recordedExpectations[1].getHttpRequest()
},
request(calculatePath("some_path_one")).withBody("some_body_one"),
request(calculatePath("some_path_three")).withBody("some_body_three")
);
assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one"));
assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three"));
// and
recordedExpectations = mockServerClient.retrieveRecordedExpectations(null);
assertThat(recordedExpectations.length, is(2));
verifyRequestsMatches(
new HttpRequest[]{
recordedExpectations[0].getHttpRequest(),
recordedExpectations[1].getHttpRequest()
},
request(calculatePath("some_path_one")).withBody("some_body_one"),
request(calculatePath("some_path_three")).withBody("some_body_three")
);
assertThat(recordedExpectations[0].getHttpResponse().getBodyAsString(), is("some_body_one"));
assertThat(recordedExpectations[1].getHttpResponse().getBodyAsString(), is("some_body_three"));
} finally {
secureEchoServer.stop();
}
}
@Test
public void shouldRetrieveRecordedLogMessages() {
// when
mockServerClient.reset();
mockServerClient.when(request().withPath(calculatePath("some_path.*")), exactly(4)).respond(response().withBody("some_body"));
assertEquals(
response("some_body"),
makeRequest(
request().withPath(calculatePath("some_path_one")),
headersToIgnore)
);
assertEquals(
notFoundResponse(),
makeRequest(
request().withPath(calculatePath("not_found")),
headersToIgnore)
);
assertEquals(
response("some_body"),
makeRequest(
request().withPath(calculatePath("some_path_three")),
headersToIgnore)
);
// then
String[] actualLogMessages = mockServerClient.retrieveLogMessagesArray(request().withPath(calculatePath(".*")));
Object[] expectedLogMessages = new Object[]{
"resetting all expectations and request logs" + NEW_LINE,
"creating expectation:" + NEW_LINE +
NEW_LINE +
"\t{" + NEW_LINE +
"\t \"httpRequest\" : {" + NEW_LINE +
"\t \"path\" : \"/some_path.*\"" + NEW_LINE +
"\t }," + NEW_LINE +
"\t \"times\" : {" + NEW_LINE +
"\t \"remainingTimes\" : 4" + NEW_LINE +
"\t }," + NEW_LINE +
"\t \"timeToLive\" : {" + NEW_LINE +
"\t \"unlimited\" : true" + NEW_LINE +
"\t }," + NEW_LINE +
"\t \"httpResponse\" : {" + NEW_LINE +
"\t \"body\" : \"some_body\"" + NEW_LINE +
"\t }" + NEW_LINE +
"\t}" + NEW_LINE,
new String[]{
"request:" + NEW_LINE +
NEW_LINE +
"\t{" + NEW_LINE +
"\t \"method\" : \"GET\"," + NEW_LINE +
"\t \"path\" : \"/some_path_one\",",
" matched expectation:" + NEW_LINE +
NEW_LINE +
"\t{" + NEW_LINE +
"\t \"httpRequest\" : {" + NEW_LINE +
"\t \"path\" : \"/some_path.*\"" + NEW_LINE +
"\t }," + NEW_LINE +
"\t \"times\" : {" + NEW_LINE +
"\t \"remainingTimes\" : 4" + NEW_LINE +
"\t }," + NEW_LINE +
"\t \"timeToLive\" : {" + NEW_LINE +
"\t \"unlimited\" : true" + NEW_LINE +
"\t }," + NEW_LINE +
"\t \"httpResponse\" : {" + NEW_LINE +
"\t \"body\" : \"some_body\"" + NEW_LINE +
"\t }" + NEW_LINE +
"\t}"
},
new String[]{
"returning response:" + NEW_LINE +
NEW_LINE +
"\t{" + NEW_LINE +
"\t \"headers\" : {" + NEW_LINE +
"\t \"connection\" : [ \"keep-alive\" ]" + NEW_LINE +
"\t }," + NEW_LINE +
"\t \"body\" : \"some_body\"" + NEW_LINE +
"\t}" + NEW_LINE +
NEW_LINE +
" for request:" + NEW_LINE +
NEW_LINE +
"\t{" + NEW_LINE +
"\t \"method\" : \"GET\"," + NEW_LINE +
"\t \"path\" : \"/some_path_one\",",
" for expectation:" + NEW_LINE +
NEW_LINE +
"\t{" + NEW_LINE +
"\t \"httpRequest\" : {" + NEW_LINE +
"\t \"path\" : \"/some_path.*\"" + NEW_LINE +
"\t }," + NEW_LINE +
"\t \"times\" : {" + NEW_LINE +
"\t \"remainingTimes\" : 3" + NEW_LINE +
"\t }," + NEW_LINE +
"\t \"timeToLive\" : {" + NEW_LINE +
"\t \"unlimited\" : true" + NEW_LINE +
"\t }," + NEW_LINE +
"\t \"httpResponse\" : {" + NEW_LINE +
"\t \"body\" : \"some_body\"" + NEW_LINE +
"\t }" + NEW_LINE +
"\t}" + NEW_LINE
},
new String[]{
"request:" + NEW_LINE +
NEW_LINE +
"\t{" + NEW_LINE +
"\t \"method\" : \"GET\"," + NEW_LINE +
"\t \"path\" : \"/not_found\",",
" did not match expectation:" + NEW_LINE +
NEW_LINE +
"\t{" + NEW_LINE +
"\t \"httpRequest\" : {" + NEW_LINE +
"\t \"path\" : \"/some_path.*\"" + NEW_LINE +
"\t }," + NEW_LINE +
"\t \"times\" : {" + NEW_LINE +
"\t \"remainingTimes\" : 3" + NEW_LINE +
"\t }," + NEW_LINE +
"\t \"timeToLive\" : {" + NEW_LINE +
"\t \"unlimited\" : true" + NEW_LINE +
"\t }," + NEW_LINE +
"\t \"httpResponse\" : {" + NEW_LINE +
"\t \"body\" : \"some_body\"" + NEW_LINE +
"\t }" + NEW_LINE +
"\t}" + NEW_LINE +
NEW_LINE +
" because:" + NEW_LINE +
NEW_LINE +
"\tmethod matches = true" + NEW_LINE +
"\tpath matches = false" + NEW_LINE +
"\tquery string parameters match = true" + NEW_LINE +
"\tbody matches = true" + NEW_LINE +
"\theaders match = true" + NEW_LINE +
"\tcookies match = true" + NEW_LINE +
"\tkeep-alive matches = true" + NEW_LINE +
"\tssl matches = true"
},
new String[]{
"no matching expectation - returning:" + NEW_LINE +
NEW_LINE +
"\t{" + NEW_LINE +
"\t \"statusCode\" : 404," + NEW_LINE +
"\t \"reasonPhrase\" : \"Not Found\"" + NEW_LINE +
"\t}" + NEW_LINE +
NEW_LINE +
" for request:" + NEW_LINE +
NEW_LINE +
"\t{" + NEW_LINE +
"\t \"method\" : \"GET\"," + NEW_LINE +
"\t \"path\" : \"/not_found\","
},
new String[]{
"request:" + NEW_LINE +
NEW_LINE +
"\t{" + NEW_LINE +
"\t \"method\" : \"GET\"," + NEW_LINE +
"\t \"path\" : \"/some_path_three\",",
" matched expectation:" + NEW_LINE +
NEW_LINE +
"\t{" + NEW_LINE +
"\t \"httpRequest\" : {" + NEW_LINE +
"\t \"path\" : \"/some_path.*\"" + NEW_LINE +
"\t }," + NEW_LINE +
"\t \"times\" : {" + NEW_LINE +
"\t \"remainingTimes\" : 3" + NEW_LINE +
"\t }," + NEW_LINE +
"\t \"timeToLive\" : {" + NEW_LINE +
"\t \"unlimited\" : true" + NEW_LINE +
"\t }," + NEW_LINE +
"\t \"httpResponse\" : {" + NEW_LINE +
"\t \"body\" : \"some_body\"" + NEW_LINE +
"\t }" + NEW_LINE +
"\t}"
},
new String[]{
"returning response:" + NEW_LINE +
NEW_LINE +
"\t{" + NEW_LINE +
"\t \"headers\" : {" + NEW_LINE +
"\t \"connection\" : [ \"keep-alive\" ]" + NEW_LINE +
"\t }," + NEW_LINE +
"\t \"body\" : \"some_body\"" + NEW_LINE +
"\t}" + NEW_LINE +
NEW_LINE +
" for request:" + NEW_LINE +
NEW_LINE +
"\t{" + NEW_LINE +
"\t \"method\" : \"GET\"," + NEW_LINE +
"\t \"path\" : \"/some_path_three\",",
" for expectation:" + NEW_LINE +
NEW_LINE +
"\t{" + NEW_LINE +
"\t \"httpRequest\" : {" + NEW_LINE +
"\t \"path\" : \"/some_path.*\"" + NEW_LINE +
"\t }," + NEW_LINE +
"\t \"times\" : {" + NEW_LINE +
"\t \"remainingTimes\" : 2" + NEW_LINE +
"\t }," + NEW_LINE +
"\t \"timeToLive\" : {" + NEW_LINE +
"\t \"unlimited\" : true" + NEW_LINE +
"\t }," + NEW_LINE +
"\t \"httpResponse\" : {" + NEW_LINE +
"\t \"body\" : \"some_body\"" + NEW_LINE +
"\t }" + NEW_LINE +
"\t}" + NEW_LINE
},
"retrieving logs in plain format that match:" + NEW_LINE +
NEW_LINE +
"\t{" + NEW_LINE +
"\t \"path\" : \"/.*\"" + NEW_LINE +
"\t}" + NEW_LINE +
NEW_LINE
};
for (int i = 0; i < expectedLogMessages.length; i++) {
if (expectedLogMessages[i] instanceof String) {
assertThat("matching log message " + i + "\nActual:\n" + Arrays.toString(actualLogMessages), actualLogMessages[i], endsWith((String) expectedLogMessages[i]));
} else if (expectedLogMessages[i] instanceof String[]) {
String[] expectedLogMessage = (String[]) expectedLogMessages[i];
for (int j = 0; j < expectedLogMessage.length; j++) {
assertThat("matching log message " + i + "-" + j + "\nActual:\n" + Arrays.toString(actualLogMessages), actualLogMessages[i], containsString(expectedLogMessage[j]));
}
}
}
}
@Test
public void shouldClearExpectationsAndLogs() {
// given - some expectations
mockServerClient
.when(
request()
.withPath(calculatePath("some_path1"))
)
.respond(
response()
.withBody("some_body1")
);
mockServerClient
.when(
request()
.withPath(calculatePath("some_path2"))
)
.respond(
response()
.withBody("some_body2")
);
// and - some matching requests
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withBody("some_body1"),
makeRequest(
request()
.withPath(calculatePath("some_path1")),
headersToIgnore)
);
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withBody("some_body2"),
makeRequest(
request()
.withPath(calculatePath("some_path2")),
headersToIgnore)
);
// when
mockServerClient
.clear(
request()
.withPath(calculatePath("some_path1"))
);
// then - expectations cleared
assertThat(
mockServerClient.retrieveActiveExpectations(null),
arrayContaining(
new Expectation(request()
.withPath(calculatePath("some_path2")))
.thenRespond(
response()
.withBody("some_body2")
)
)
);
// and then - request log cleared
verifyRequestsMatches(
mockServerClient.retrieveRecordedRequests(null),
request(calculatePath("some_path2"))
);
// and then - remaining expectations not cleared
assertEquals(
response()
.withStatusCode(OK_200.code())
.withReasonPhrase(OK_200.reasonPhrase())
.withBody("some_body2"),
makeRequest(
request()
.withPath(calculatePath("some_path2")),
headersToIgnore)
);
assertEquals(
response()
.withStatusCode(HttpStatusCode.NOT_FOUND_404.code())
.withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()),
makeRequest(
request()
.withPath(calculatePath("some_path1")),
headersToIgnore)
);
}
@Test
public void shouldReset() {
// given
mockServerClient
.when(
request()
.withPath(calculatePath("some_path1"))
)
.respond(
response()
.withBody("some_body1")
);
mockServerClient
.when(
request()
.withPath(calculatePath("some_path2"))
)
.respond(
response()
.withBody("some_body2")
);
// when
mockServerClient.reset();
// then
// - in http
assertEquals(
response()
.withStatusCode(HttpStatusCode.NOT_FOUND_404.code())
.withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()),
makeRequest(
request()
.withPath(calculatePath("some_path1")),
headersToIgnore)
);
assertEquals(
response()
.withStatusCode(HttpStatusCode.NOT_FOUND_404.code())
.withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()),
makeRequest(
request()
.withPath(calculatePath("some_path2")),
headersToIgnore)
);
// - in https
assertEquals(
response()
.withStatusCode(HttpStatusCode.NOT_FOUND_404.code())
.withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()),
makeRequest(
request()
.withSecure(true)
.withPath(calculatePath("some_path1")),
headersToIgnore)
);
assertEquals(
response()
.withStatusCode(HttpStatusCode.NOT_FOUND_404.code())
.withReasonPhrase(HttpStatusCode.NOT_FOUND_404.reasonPhrase()),
makeRequest(
request()
.withSecure(true)
.withPath(calculatePath("some_path2")),
headersToIgnore)
);
}
@Test
public void shouldReturnErrorForInvalidExpectation() throws Exception {
// when
HttpResponse httpResponse = new NettyHttpClient().sendRequest(
request()
.withMethod("PUT")
.withHeader(HOST.toString(), "localhost:" + this.getServerPort())
.withPath(addContextToPath("/expectation"))
.withBody("{" + NEW_LINE +
" \"httpRequest\" : {" + NEW_LINE +
" \"path\" : \"/path_one\"" + NEW_LINE +
" }," + NEW_LINE +
" \"incorrectField\" : {" + NEW_LINE +
" \"body\" : \"some_body_one\"" + NEW_LINE +
" }," + NEW_LINE +
" \"times\" : {" + NEW_LINE +
" \"remainingTimes\" : 1" + NEW_LINE +
" }," + NEW_LINE +
" \"timeToLive\" : {" + NEW_LINE +
" \"unlimited\" : true" + NEW_LINE +
" }" + NEW_LINE +
"}")
).get(10, TimeUnit.SECONDS);
// then
assertThat(httpResponse.getStatusCode(), is(400));
assertThat(httpResponse.getBodyAsString(), is("2 errors:" + NEW_LINE +
" - object instance has properties which are not allowed by the schema: [\"incorrectField\"]" + NEW_LINE +
" - oneOf of the following must be specified [\"httpResponse\", \"httpResponseTemplate\", \"httpResponseObjectCallback\", \"httpResponseClassCallback\", \"httpForward\", \"httpForwardTemplate\", \"httpForwardObjectCallback\", \"httpForwardClassCallback\", \"httpOverrideForwardedRequest\", \"httpError\"] but 0 found"));
}
@Test
public void shouldReturnErrorForInvalidRequest() throws Exception {
// when
HttpResponse httpResponse = new NettyHttpClient().sendRequest(
request()
.withMethod("PUT")
.withHeader(HOST.toString(), "localhost:" + this.getServerPort())
.withPath(addContextToPath("/clear"))
.withBody("{" + NEW_LINE +
" \"path\" : 500," + NEW_LINE +
" \"method\" : true," + NEW_LINE +
" \"keepAlive\" : \"false\"" + NEW_LINE +
" }")
).get(10, TimeUnit.SECONDS);
// then
assertThat(httpResponse.getStatusCode(), is(400));
assertThat(httpResponse.getBodyAsString(), is("3 errors:" + NEW_LINE +
" - instance type (string) does not match any allowed primitive type (allowed: [\"boolean\"]) for field \"/keepAlive\"" + NEW_LINE +
" - instance type (boolean) does not match any allowed primitive type (allowed: [\"string\"]) for field \"/method\"" + NEW_LINE +
" - instance type (integer) does not match any allowed primitive type (allowed: [\"string\"]) for field \"/path\""));
}
} |
package com.opengamma.strata.pricer.provider;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Set;
import org.joda.beans.Bean;
import org.joda.beans.BeanBuilder;
import org.joda.beans.BeanDefinition;
import org.joda.beans.ImmutableBean;
import org.joda.beans.Property;
import org.joda.beans.PropertyDefinition;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.impl.direct.DirectFieldsBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import com.opengamma.analytics.math.interpolation.Interpolator2D;
import com.opengamma.analytics.math.interpolation.data.Interpolator1DDataBundle;
import com.opengamma.analytics.math.surface.InterpolatedDoublesSurface;
import com.opengamma.strata.basics.date.DayCount;
import com.opengamma.strata.collect.tuple.DoublesPair;
import com.opengamma.strata.finance.rate.swap.type.FixedIborSwapConvention;
import com.opengamma.strata.pricer.sensitivity.SwaptionSensitivity;
/**
* Volatility environment for swaptions in the normal or Bachelier model.
* The volatility is represented by a surface on the expiration and swap tenor dimensions.
*/
@BeanDefinition(builderScope = "private")
public class NormalVolatilityExpiryTenorSwaptionProvider
implements NormalVolatilitySwaptionProvider, ImmutableBean, Serializable {
/** The normal volatility surface. The order of the dimensions is expiry/swap tenor */
@PropertyDefinition(validate = "notNull")
private final InterpolatedDoublesSurface surface;
/** The swap convention for which the data is valid. */
@PropertyDefinition(validate = "notNull", overrideGet = true)
private final FixedIborSwapConvention convention;
/** The day count applicable to the model. The time is measured in days, not hours. */
@PropertyDefinition(validate = "notNull")
private final DayCount dayCount;
/** The valuation date. All data items in this environment are calibrated for this date. */
@PropertyDefinition(validate = "notNull", overrideGet = true)
private final LocalDate valuationDate;
/** The valuation time. All data items in this environment are calibrated for this time. */
@PropertyDefinition(validate = "notNull")
private final LocalTime valuationTime;
/** The valuation zone.*/
@PropertyDefinition(validate = "notNull")
private final ZoneId valuationZone;
/**
* Creates a provider from the implied volatility surface and the date, time and zone for which it is valid.
* @param surface the implied volatility surface
* @param convention the swap convention for which the data is valid
* @param dayCount the day count applicable to the model
* @param valuationDate the valuation date
* @param valuationTime the valuation time
* @param valuationZone the valuation time zone
* @return the provider
*/
public static NormalVolatilityExpiryTenorSwaptionProvider of(InterpolatedDoublesSurface surface,
FixedIborSwapConvention convention, DayCount dayCount,
LocalDate valuationDate, LocalTime valuationTime, ZoneId valuationZone) {
return new NormalVolatilityExpiryTenorSwaptionProvider(surface, convention, dayCount, valuationDate,
valuationTime, valuationZone);
}
/**
* Creates a provider from the implied volatility surface and the date.
* The valuation time and zone are defaulted to noon UTC.
* @param surface the implied volatility surface
* @param convention the swap convention for which the data is valid
* @param dayCount the day count applicable to the model
* @param valuationDate the valuation date
* @return the provider
*/
public static NormalVolatilityExpiryTenorSwaptionProvider of(InterpolatedDoublesSurface surface,
FixedIborSwapConvention convention, DayCount dayCount, LocalDate valuationDate) {
return new NormalVolatilityExpiryTenorSwaptionProvider(surface, convention, dayCount, valuationDate, LocalTime.NOON,
ZoneOffset.UTC);
}
// private constructor
private NormalVolatilityExpiryTenorSwaptionProvider(InterpolatedDoublesSurface surface,
FixedIborSwapConvention convention, DayCount dayCount, LocalDate valuationDate, LocalTime valuationTime,
ZoneId valuationZone) {
this.surface = surface;
this.convention = convention;
this.dayCount = dayCount;
this.valuationDate = valuationDate;
this.valuationTime = valuationTime;
this.valuationZone = valuationZone;
}
@Override
public double getVolatility(ZonedDateTime expiryDate, double tenor, double strike, double forwardRate) {
double expiryTime = relativeYearFraction(expiryDate);
double volatility = surface.getZValue(expiryTime, tenor);
return volatility;
}
/**
* Computes the sensitivity of a point swaption sensitivity to the nodes underlying the interpolated surface.
* <p>
* The returned object is in the form of a map between the nodes coordinates (expiry/tenor) to the sensitivity to the
* sensitivity to those nodes.
* @param sensitivity the point sensitivity
* @return the node sensitivity
*/
public Map<DoublesPair, Double> getNormalVolatilitySensitivity(SwaptionSensitivity sensitivity) {
@SuppressWarnings("unchecked")
Map<Double, Interpolator1DDataBundle> volatilityData =
(Map<Double, Interpolator1DDataBundle>) surface.getInterpolatorData();
Interpolator2D interpolator = surface.getInterpolator();
double timeExpiry = relativeYearFraction(sensitivity.getExpiry());
double tenor = sensitivity.getTenor();
Map<DoublesPair, Double> weight = interpolator.getNodeSensitivitiesForValue(volatilityData, DoublesPair.of(timeExpiry, tenor));
Map<DoublesPair, Double> nodeVega = new HashMap<>();
for (Entry<DoublesPair, Double> entry : weight.entrySet()) {
nodeVega.put(entry.getKey(), entry.getValue() * sensitivity.getSensitivity());
}
return nodeVega;
}
@Override
public double relativeYearFraction(ZonedDateTime dateTime) {
LocalDate date = dateTime.toLocalDate();
boolean timeIsNegative = valuationDate.isAfter(date);
if (timeIsNegative) {
return -dayCount.yearFraction(date, valuationDate);
}
return dayCount.yearFraction(valuationDate, date);
}
@Override
public double tenor(LocalDate startDate, LocalDate endDate) {
// rounded number of months. the rounding is to ensure that an integer number of year even with holidays/leap year
return Math.round((endDate.toEpochDay() - startDate.toEpochDay()) / 365.25 * 12) / 12 ;
}
///CLOVER:OFF
/**
* The meta-bean for {@code NormalVolatilityExpiryTenorSwaptionProvider}.
* @return the meta-bean, not null
*/
public static NormalVolatilityExpiryTenorSwaptionProvider.Meta meta() {
return NormalVolatilityExpiryTenorSwaptionProvider.Meta.INSTANCE;
}
static {
JodaBeanUtils.registerMetaBean(NormalVolatilityExpiryTenorSwaptionProvider.Meta.INSTANCE);
}
/**
* The serialization version id.
*/
private static final long serialVersionUID = 1L;
/**
* Restricted constructor.
* @param builder the builder to copy from, not null
*/
protected NormalVolatilityExpiryTenorSwaptionProvider(NormalVolatilityExpiryTenorSwaptionProvider.Builder builder) {
JodaBeanUtils.notNull(builder.surface, "surface");
JodaBeanUtils.notNull(builder.convention, "convention");
JodaBeanUtils.notNull(builder.dayCount, "dayCount");
JodaBeanUtils.notNull(builder.valuationDate, "valuationDate");
JodaBeanUtils.notNull(builder.valuationTime, "valuationTime");
JodaBeanUtils.notNull(builder.valuationZone, "valuationZone");
this.surface = builder.surface;
this.convention = builder.convention;
this.dayCount = builder.dayCount;
this.valuationDate = builder.valuationDate;
this.valuationTime = builder.valuationTime;
this.valuationZone = builder.valuationZone;
}
@Override
public NormalVolatilityExpiryTenorSwaptionProvider.Meta metaBean() {
return NormalVolatilityExpiryTenorSwaptionProvider.Meta.INSTANCE;
}
@Override
public <R> Property<R> property(String propertyName) {
return metaBean().<R>metaProperty(propertyName).createProperty(this);
}
@Override
public Set<String> propertyNames() {
return metaBean().metaPropertyMap().keySet();
}
/**
* Gets the normal volatility surface. The order of the dimensions is expiry/swap tenor
* @return the value of the property, not null
*/
public InterpolatedDoublesSurface getSurface() {
return surface;
}
/**
* Gets the swap convention for which the data is valid.
* @return the value of the property, not null
*/
@Override
public FixedIborSwapConvention getConvention() {
return convention;
}
/**
* Gets the day count applicable to the model. The time is measured in days, not hours.
* @return the value of the property, not null
*/
public DayCount getDayCount() {
return dayCount;
}
/**
* Gets the valuation date. All data items in this environment are calibrated for this date.
* @return the value of the property, not null
*/
@Override
public LocalDate getValuationDate() {
return valuationDate;
}
/**
* Gets the valuation time. All data items in this environment are calibrated for this time.
* @return the value of the property, not null
*/
public LocalTime getValuationTime() {
return valuationTime;
}
/**
* Gets the valuation zone.
* @return the value of the property, not null
*/
public ZoneId getValuationZone() {
return valuationZone;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj != null && obj.getClass() == this.getClass()) {
NormalVolatilityExpiryTenorSwaptionProvider other = (NormalVolatilityExpiryTenorSwaptionProvider) obj;
return JodaBeanUtils.equal(getSurface(), other.getSurface()) &&
JodaBeanUtils.equal(getConvention(), other.getConvention()) &&
JodaBeanUtils.equal(getDayCount(), other.getDayCount()) &&
JodaBeanUtils.equal(getValuationDate(), other.getValuationDate()) &&
JodaBeanUtils.equal(getValuationTime(), other.getValuationTime()) &&
JodaBeanUtils.equal(getValuationZone(), other.getValuationZone());
}
return false;
}
@Override
public int hashCode() {
int hash = getClass().hashCode();
hash = hash * 31 + JodaBeanUtils.hashCode(getSurface());
hash = hash * 31 + JodaBeanUtils.hashCode(getConvention());
hash = hash * 31 + JodaBeanUtils.hashCode(getDayCount());
hash = hash * 31 + JodaBeanUtils.hashCode(getValuationDate());
hash = hash * 31 + JodaBeanUtils.hashCode(getValuationTime());
hash = hash * 31 + JodaBeanUtils.hashCode(getValuationZone());
return hash;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(224);
buf.append("NormalVolatilityExpiryTenorSwaptionProvider{");
int len = buf.length();
toString(buf);
if (buf.length() > len) {
buf.setLength(buf.length() - 2);
}
buf.append('}');
return buf.toString();
}
protected void toString(StringBuilder buf) {
buf.append("surface").append('=').append(JodaBeanUtils.toString(getSurface())).append(',').append(' ');
buf.append("convention").append('=').append(JodaBeanUtils.toString(getConvention())).append(',').append(' ');
buf.append("dayCount").append('=').append(JodaBeanUtils.toString(getDayCount())).append(',').append(' ');
buf.append("valuationDate").append('=').append(JodaBeanUtils.toString(getValuationDate())).append(',').append(' ');
buf.append("valuationTime").append('=').append(JodaBeanUtils.toString(getValuationTime())).append(',').append(' ');
buf.append("valuationZone").append('=').append(JodaBeanUtils.toString(getValuationZone())).append(',').append(' ');
}
/**
* The meta-bean for {@code NormalVolatilityExpiryTenorSwaptionProvider}.
*/
public static class Meta extends DirectMetaBean {
/**
* The singleton instance of the meta-bean.
*/
static final Meta INSTANCE = new Meta();
/**
* The meta-property for the {@code surface} property.
*/
private final MetaProperty<InterpolatedDoublesSurface> surface = DirectMetaProperty.ofImmutable(
this, "surface", NormalVolatilityExpiryTenorSwaptionProvider.class, InterpolatedDoublesSurface.class);
/**
* The meta-property for the {@code convention} property.
*/
private final MetaProperty<FixedIborSwapConvention> convention = DirectMetaProperty.ofImmutable(
this, "convention", NormalVolatilityExpiryTenorSwaptionProvider.class, FixedIborSwapConvention.class);
/**
* The meta-property for the {@code dayCount} property.
*/
private final MetaProperty<DayCount> dayCount = DirectMetaProperty.ofImmutable(
this, "dayCount", NormalVolatilityExpiryTenorSwaptionProvider.class, DayCount.class);
/**
* The meta-property for the {@code valuationDate} property.
*/
private final MetaProperty<LocalDate> valuationDate = DirectMetaProperty.ofImmutable(
this, "valuationDate", NormalVolatilityExpiryTenorSwaptionProvider.class, LocalDate.class);
/**
* The meta-property for the {@code valuationTime} property.
*/
private final MetaProperty<LocalTime> valuationTime = DirectMetaProperty.ofImmutable(
this, "valuationTime", NormalVolatilityExpiryTenorSwaptionProvider.class, LocalTime.class);
/**
* The meta-property for the {@code valuationZone} property.
*/
private final MetaProperty<ZoneId> valuationZone = DirectMetaProperty.ofImmutable(
this, "valuationZone", NormalVolatilityExpiryTenorSwaptionProvider.class, ZoneId.class);
/**
* The meta-properties.
*/
private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap(
this, null,
"surface",
"convention",
"dayCount",
"valuationDate",
"valuationTime",
"valuationZone");
/**
* Restricted constructor.
*/
protected Meta() {
}
@Override
protected MetaProperty<?> metaPropertyGet(String propertyName) {
switch (propertyName.hashCode()) {
case -1853231955: // surface
return surface;
case 2039569265: // convention
return convention;
case 1905311443: // dayCount
return dayCount;
case 113107279: // valuationDate
return valuationDate;
case 113591406: // valuationTime
return valuationTime;
case 113775949: // valuationZone
return valuationZone;
}
return super.metaPropertyGet(propertyName);
}
@Override
public BeanBuilder<? extends NormalVolatilityExpiryTenorSwaptionProvider> builder() {
return new NormalVolatilityExpiryTenorSwaptionProvider.Builder();
}
@Override
public Class<? extends NormalVolatilityExpiryTenorSwaptionProvider> beanType() {
return NormalVolatilityExpiryTenorSwaptionProvider.class;
}
@Override
public Map<String, MetaProperty<?>> metaPropertyMap() {
return metaPropertyMap$;
}
/**
* The meta-property for the {@code surface} property.
* @return the meta-property, not null
*/
public final MetaProperty<InterpolatedDoublesSurface> surface() {
return surface;
}
/**
* The meta-property for the {@code convention} property.
* @return the meta-property, not null
*/
public final MetaProperty<FixedIborSwapConvention> convention() {
return convention;
}
/**
* The meta-property for the {@code dayCount} property.
* @return the meta-property, not null
*/
public final MetaProperty<DayCount> dayCount() {
return dayCount;
}
/**
* The meta-property for the {@code valuationDate} property.
* @return the meta-property, not null
*/
public final MetaProperty<LocalDate> valuationDate() {
return valuationDate;
}
/**
* The meta-property for the {@code valuationTime} property.
* @return the meta-property, not null
*/
public final MetaProperty<LocalTime> valuationTime() {
return valuationTime;
}
/**
* The meta-property for the {@code valuationZone} property.
* @return the meta-property, not null
*/
public final MetaProperty<ZoneId> valuationZone() {
return valuationZone;
}
@Override
protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
switch (propertyName.hashCode()) {
case -1853231955: // surface
return ((NormalVolatilityExpiryTenorSwaptionProvider) bean).getSurface();
case 2039569265: // convention
return ((NormalVolatilityExpiryTenorSwaptionProvider) bean).getConvention();
case 1905311443: // dayCount
return ((NormalVolatilityExpiryTenorSwaptionProvider) bean).getDayCount();
case 113107279: // valuationDate
return ((NormalVolatilityExpiryTenorSwaptionProvider) bean).getValuationDate();
case 113591406: // valuationTime
return ((NormalVolatilityExpiryTenorSwaptionProvider) bean).getValuationTime();
case 113775949: // valuationZone
return ((NormalVolatilityExpiryTenorSwaptionProvider) bean).getValuationZone();
}
return super.propertyGet(bean, propertyName, quiet);
}
@Override
protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
metaProperty(propertyName);
if (quiet) {
return;
}
throw new UnsupportedOperationException("Property cannot be written: " + propertyName);
}
}
/**
* The bean-builder for {@code NormalVolatilityExpiryTenorSwaptionProvider}.
*/
private static class Builder extends DirectFieldsBeanBuilder<NormalVolatilityExpiryTenorSwaptionProvider> {
private InterpolatedDoublesSurface surface;
private FixedIborSwapConvention convention;
private DayCount dayCount;
private LocalDate valuationDate;
private LocalTime valuationTime;
private ZoneId valuationZone;
/**
* Restricted constructor.
*/
protected Builder() {
}
@Override
public Object get(String propertyName) {
switch (propertyName.hashCode()) {
case -1853231955: // surface
return surface;
case 2039569265: // convention
return convention;
case 1905311443: // dayCount
return dayCount;
case 113107279: // valuationDate
return valuationDate;
case 113591406: // valuationTime
return valuationTime;
case 113775949: // valuationZone
return valuationZone;
default:
throw new NoSuchElementException("Unknown property: " + propertyName);
}
}
@Override
public Builder set(String propertyName, Object newValue) {
switch (propertyName.hashCode()) {
case -1853231955: // surface
this.surface = (InterpolatedDoublesSurface) newValue;
break;
case 2039569265: // convention
this.convention = (FixedIborSwapConvention) newValue;
break;
case 1905311443: // dayCount
this.dayCount = (DayCount) newValue;
break;
case 113107279: // valuationDate
this.valuationDate = (LocalDate) newValue;
break;
case 113591406: // valuationTime
this.valuationTime = (LocalTime) newValue;
break;
case 113775949: // valuationZone
this.valuationZone = (ZoneId) newValue;
break;
default:
throw new NoSuchElementException("Unknown property: " + propertyName);
}
return this;
}
@Override
public Builder set(MetaProperty<?> property, Object value) {
super.set(property, value);
return this;
}
@Override
public Builder setString(String propertyName, String value) {
setString(meta().metaProperty(propertyName), value);
return this;
}
@Override
public Builder setString(MetaProperty<?> property, String value) {
super.setString(property, value);
return this;
}
@Override
public Builder setAll(Map<String, ? extends Object> propertyValueMap) {
super.setAll(propertyValueMap);
return this;
}
@Override
public NormalVolatilityExpiryTenorSwaptionProvider build() {
return new NormalVolatilityExpiryTenorSwaptionProvider(this);
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(224);
buf.append("NormalVolatilityExpiryTenorSwaptionProvider.Builder{");
int len = buf.length();
toString(buf);
if (buf.length() > len) {
buf.setLength(buf.length() - 2);
}
buf.append('}');
return buf.toString();
}
protected void toString(StringBuilder buf) {
buf.append("surface").append('=').append(JodaBeanUtils.toString(surface)).append(',').append(' ');
buf.append("convention").append('=').append(JodaBeanUtils.toString(convention)).append(',').append(' ');
buf.append("dayCount").append('=').append(JodaBeanUtils.toString(dayCount)).append(',').append(' ');
buf.append("valuationDate").append('=').append(JodaBeanUtils.toString(valuationDate)).append(',').append(' ');
buf.append("valuationTime").append('=').append(JodaBeanUtils.toString(valuationTime)).append(',').append(' ');
buf.append("valuationZone").append('=').append(JodaBeanUtils.toString(valuationZone)).append(',').append(' ');
}
}
///CLOVER:ON
} |
package org.metaborg.meta.lang.dynsem.interpreter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.concurrent.Callable;
import org.metaborg.meta.lang.dynsem.interpreter.nodes.rules.RuleRegistry;
import org.metaborg.meta.lang.dynsem.interpreter.nodes.rules.RuleResult;
import org.metaborg.meta.lang.dynsem.interpreter.terms.ITerm;
import org.metaborg.meta.lang.dynsem.interpreter.terms.ITermTransformer;
import org.spoofax.interpreter.terms.IStrategoTerm;
import com.oracle.truffle.api.source.MissingNameException;
import com.oracle.truffle.api.source.Source;
import com.oracle.truffle.api.vm.PolyglotEngine;
import com.oracle.truffle.api.vm.PolyglotEngine.Builder;
import com.oracle.truffle.api.vm.PolyglotEngine.Value;
/**
* Abstract class of an entrypoint to a {@link DynSemLanguage}. This class is responsible for instantiating the VM
* properly and provides an interface for evaluating source code in that language.
*/
public abstract class DynSemEntryPoint {
private final IDynSemLanguageParser parser;
private final ITermTransformer transformer;
private final RuleRegistry ruleRegistry;
private final ITermRegistry termRegistry;
public DynSemEntryPoint(IDynSemLanguageParser parser, ITermTransformer transformer, ITermRegistry termRegistry,
RuleRegistry ruleRegistry) {
this.parser = parser;
this.transformer = transformer;
this.termRegistry = termRegistry;
this.ruleRegistry = ruleRegistry;
}
public Callable<RuleResult> getCallable(String file, InputStream input, OutputStream output, OutputStream error) {
try {
IStrategoTerm term = getTransformer().transform(getParser().parse(
Source.newBuilder(new File(file)).name("Evaluate to interpreter").mimeType(getMimeType()).build()));
return getCallable(term, input, output, error);
} catch (IOException ioex) {
throw new RuntimeException("Eval failed", ioex);
}
}
public Callable<RuleResult> getCallable(IStrategoTerm term, InputStream input, OutputStream output,
OutputStream error) {
try {
PolyglotEngine vm = buildPolyglotEngine(input, output, error);
assert vm.getLanguages().containsKey(getMimeType());
Value interpreter = vm.eval(Source.newBuilder(new InputStreamReader(getSpecificationTerm()))
.name("Evaluate to interpreter").mimeType(getMimeType()).build());
ITerm programTerm = getTermRegistry().parseProgramTerm(term);
return new Callable<RuleResult>() {
@Override
public RuleResult call() throws Exception {
return interpreter.execute(programTerm).as(RuleResult.class);
}
};
} catch (IOException e) {
throw new RuntimeException("Eval failed", e);
}
}
/**
* Build and configure the {@link PolyglotEngine}. Uses {@link Builder#config(String, String, Object)} for injecting
* dependencies: the {@link IDynSemLanguageParser parser} to be used, the {@link ITermRegistry term registry} and
* the {@link InputStream} of the DynSem specification term.
*
* @param input
* The {@link InputStream} of the VM.
* @param output
* The {@link OutputStream} of the VM for standard output.
* @param error
* The {@link OutputStream} of the VM for errors.
* @return The configured {@link PolyglotEngine}.
*/
public PolyglotEngine buildPolyglotEngine(InputStream input, OutputStream output, OutputStream error) {
assert DynSemContext.LANGUAGE != null : "DynSemContext.LANGUAGE must be set for creating the RuleRegistry";
return PolyglotEngine.newBuilder().setIn(input).setOut(output).setErr(error)
.config(getMimeType(), DynSemLanguage.PARSER, getParser())
.config(getMimeType(), DynSemLanguage.TERM_REGISTRY, getTermRegistry())
.config(getMimeType(), DynSemLanguage.RULE_REGISTRY, getRuleRegistry()).build();
}
public IDynSemLanguageParser getParser() {
return parser;
}
public ITermTransformer getTransformer() {
return transformer;
}
public ITermRegistry getTermRegistry() {
return termRegistry;
}
public RuleRegistry getRuleRegistry() {
return ruleRegistry;
}
public abstract String getMimeType();
public abstract InputStream getSpecificationTerm();
} |
/* $Id: TestNationalWeatherAssociationArticleIteratorFactory.java,v 1.4 2014-09-15 08:09:24 ldoan Exp $ */
package org.lockss.plugin.nationalweatherassociation;
import java.io.IOException;
import java.util.Iterator;
import java.util.regex.Pattern;
import org.lockss.util.ListUtil;
import org.lockss.util.StringUtil;
import org.lockss.state.NodeManager;
import org.lockss.test.ArticleIteratorTestCase;
import org.lockss.config.ConfigManager;
import org.lockss.config.Configuration;
import org.lockss.daemon.CachedUrlSetSpec;
import org.lockss.daemon.SingleNodeCachedUrlSetSpec;
import org.lockss.extractor.MetadataTarget;
import org.lockss.plugin.ArchivalUnit;
import org.lockss.plugin.ArticleFiles;
import org.lockss.plugin.AuUtil;
import org.lockss.plugin.CachedUrl;
import org.lockss.plugin.CachedUrlSet;
import org.lockss.plugin.PluginTestUtil;
import org.lockss.plugin.SubTreeArticleIterator;
import org.lockss.plugin.simulated.SimulatedArchivalUnit;
import org.lockss.plugin.simulated.SimulatedContentGenerator;
/*
* article content may look like:
* <nwasbase>.org/xjid/abstracts/2013/2013-JID22/abstract.php
* <nwasbase>.org/xjid/articles/2013/2013-JID22/2013-JID22.pdf
*/
public class TestNationalWeatherAssociationArticleIteratorFactory
extends ArticleIteratorTestCase {
private SimulatedArchivalUnit sau; // Simulated AU to generate content
private static final String PLUGIN_NAME = "org.lockss.plugin."
+ "nationalweatherassociation.NationalWeatherAssociationPlugin";
private static final String BASE_URL = "http:
private static final String JID = "xjid";
private static final String YEAR = "2013";
private static final int DEFAULT_FILESIZE = 3000;
private static final int EXP_DELETED_FILE_COUNT = 5;
private static final int EXP_FULL_TEXT_COUNT = 11; // after deleteBlock
private static final int EXP_PDF_COUNT = 11; // after deleteBlock
private static final int EXP_ABS_COUNT = 7; // after deleteBlock
private static final int EXP_AM_COUNT = 7; // after deleteBlock
public void setUp() throws Exception {
super.setUp();
// au is protected archival unit from super class ArticleIteratorTestCase
au = createAu();
sau = PluginTestUtil.createAndStartSimAu(simAuConfig(tempDirPath));
}
public void tearDown() throws Exception {
sau.deleteContentTree();
super.tearDown();
}
protected ArchivalUnit createAu() throws ArchivalUnit.ConfigurationException {
return
PluginTestUtil.createAndStartAu(PLUGIN_NAME, nwaAuConfig());
}
private Configuration simAuConfig(String rootPath) {
Configuration conf = ConfigManager.newConfiguration();
conf.put("root", rootPath);
conf.put("base_url", BASE_URL);
conf.put("depth", "1");
conf.put("branch", "4");
conf.put("numFiles", "3");
conf.put("fileTypes",
"" + ( SimulatedContentGenerator.FILE_TYPE_PDF
| SimulatedContentGenerator.FILE_TYPE_HTML));
conf.put("binFileSize", "" + DEFAULT_FILESIZE);
return conf;
}
private Configuration nwaAuConfig() {
Configuration conf = ConfigManager.newConfiguration();
conf.put("base_url", BASE_URL);
conf.put("journal_id", JID);
conf.put("year", YEAR);
return conf;
}
public void testRoots() throws Exception {
SubTreeArticleIterator artIter = createSubTreeIter();
assertEquals(ListUtil.list(BASE_URL + JID), getRootUrls(artIter));
}
public void testUrlsWithPrefixes() throws Exception {
SubTreeArticleIterator artIter = createSubTreeIter();
Pattern pat = getPattern(artIter);
// Pattern PDF_PATTERN = Pattern.compile(
// "/(articles)/(([^/]+/)+)([^/]+)\\.pdf$", Pattern.CASE_INSENSITIVE);
// <nwabase>.org/xjid/articles/2013/2013-XJID12/2013-XJID12.pdf
assertMatchesRE(pat, BASE_URL + JID + "/articles/" + YEAR + "/"
+ YEAR + "-" + JID + "12/"+ YEAR + "-" + JID + "12.pdf");
// <nwabase>.org/xjid/articles/2013/2013-XJID12/2013-XJID12.pdfbad
assertNotMatchesRE(pat, BASE_URL + JID + "/articles/" + YEAR + "/"
+ YEAR + "-" + JID + "12/"+ YEAR + "-" + JID + "12.pdfbad");
}
// simulated cached urls:
// total number files = 24; // 1 depth, 4 branches, 3 files
// 1003 means branch #1 and file #3
// there are 2 different file formats: .pdf and .php
// .php is actually an html file, so 12 .pdfs and 12 .phps
// full text pdf:
// abstract:
public void testCreateArticleFiles() throws Exception {
PluginTestUtil.crawlSimAu(sau);
String pdfPat = "branch(\\d+)/(\\d+)file\\.pdf";
// <nwabase>.org/xjid/articles/2013/2013-XJID12/2013-XJID12.pdf
String pdfRep = "/" + JID + "/articles/2013/2013-xjid$1$2/2013-xjid$1$2.pdf";
PluginTestUtil.copyAu(sau, au, ".*\\.pdf$", pdfPat, pdfRep);
String htmlPat = "branch(\\d+)/(\\d+)file\\.html";
// <nwabase>.org/xjid/abstracts/2013/2013-XJID22/abstract.php
String absRep = "/" + JID +"/abstracts/2013/2013-xjid$1$2/abstract.php";
PluginTestUtil.copyAu(sau, au, ".*\\.html$", htmlPat, absRep);
// Remove some URLs:
int deletedFileCount = 0;
for (CachedUrl cu : AuUtil.getCuIterable(au)) {
String url = cu.getUrl();
log.info("au cached url: " + url);
if ((url.contains("/articles/") && url.endsWith("1001.pdf"))
|| (url.contains("/abstracts/") && url.contains("002"))) {
deleteBlock(cu);
++deletedFileCount;
}
}
assertEquals(EXP_DELETED_FILE_COUNT, deletedFileCount);
// au should now match the aspects that the SubTreeArticleIteratorBuilder
// builds in NWAArticleIteratorFactory
Iterator<ArticleFiles> it = au.getArticleIterator(MetadataTarget.Any());
int countFullText = 0;
int countPdf = 0;
int countAbs = 0;
int countAm = 0;
// after deleting, there are 8 full text pdfs left.
while (it.hasNext()) {
ArticleFiles af = it.next();
log.info(af.toString());
CachedUrl cu = af.getFullTextCu();
String url = cu.getUrl();
assertNotNull(cu);
String contentType = cu.getContentType();
log.info("count full text " + countFullText + " url " + url
+ " " + contentType);
countFullText++;
url = af.getRoleUrl(ArticleFiles.ROLE_FULL_TEXT_PDF);
if (!StringUtil.isNullString(url) && url.contains("pdf")) {
++countPdf;
}
url = af.getRoleUrl(ArticleFiles.ROLE_ABSTRACT);
if (!StringUtil.isNullString(url) && url.contains("abstract")) {
++countAbs;
}
url = af.getRoleUrl(ArticleFiles.ROLE_ARTICLE_METADATA);
if (!StringUtil.isNullString(url) && url.contains("abstract")) {
++countAm;
}
}
log.info("Full text article count is " + countFullText);
log.info("Pdf count is " + countPdf);
log.info("Abstract count is " + countAbs);
log.info("Article Metadata count is " + countAm);
assertEquals(EXP_FULL_TEXT_COUNT, countFullText);
assertEquals(EXP_PDF_COUNT, countPdf);
assertEquals(EXP_ABS_COUNT, countAbs);
assertEquals(EXP_AM_COUNT, countAm);
}
private void deleteBlock(CachedUrl cu) throws IOException {
log.info("deleting " + cu.getUrl());
CachedUrlSetSpec cuss = new SingleNodeCachedUrlSetSpec(cu.getUrl());
ArchivalUnit au = cu.getArchivalUnit();
CachedUrlSet cus = au.makeCachedUrlSet(cuss);
NodeManager nm = au.getPlugin().getDaemon().getNodeManager(au);
nm.deleteNode(cus);
}
} |
package com.java.laiy.controller;
import com.java.laiy.model.Board;
import com.java.laiy.model.Figure;
import com.java.laiy.model.Player;
import com.java.laiy.model.exceptions.PointOccupiedException;
import org.ietf.jgss.GSSManager;
import org.junit.Test;
import static org.junit.Assert.*;
public class GameControllerTest {
@Test
public void testGetWinnerForDiags() throws Exception {
final String gameName = "XO";
final Player[] players = new Player[2];
players[0] = new Player("Ox", Figure.X);
players[1] = new Player("Xo", Figure.O);
final Board boardLeft = new Board();
final GameController gameControllerLeft = new GameController(gameName, players, boardLeft);
final Figure testValueLeft = Figure.O;
boardLeft.setFigure(0,0,testValueLeft );
boardLeft.setFigure(1,1,testValueLeft );
boardLeft.setFigure(2,2,testValueLeft );
assertEquals(players[1],gameControllerLeft.getWinner());
final Board boardRight = new Board();
final GameController gameControllerRight = new GameController(gameName, players, boardRight);
final Figure testValueRight = Figure.X;
boardRight.setFigure(2,0,testValueRight);
boardRight.setFigure(1,1,testValueRight);
boardRight.setFigure(0,2,testValueRight);
assertEquals(players[0],gameControllerRight.getWinner());
}
@Test
public void testGetWinnerNull() throws Exception {
final String gameName = "XO";
final Board board = new Board();
final Player[] players = new Player[2];
players[0] = new Player("Ox", Figure.X);
players[1] = new Player("Xo", Figure.O);
final Figure testValueO = Figure.O;
final Figure testValueX = Figure.X;
final GameController gameControllerNull = new GameController(gameName, players, board);
board.setFigure(0,0,testValueO);
board.setFigure(0,1,testValueX);
board.setFigure(1,2,testValueO);
board.setFigure(0,2,testValueX);
board.setFigure(2,0,testValueO);
board.setFigure(1,0,testValueX);
board.setFigure(1,1,testValueX);
assertNull(gameControllerNull.getWinner());
}
@Test
public void testGetWinnerForLines() throws Exception {
final String gameName = "XO";
final Board board = new Board();
final Player[] players = new Player[2];
players[0] = new Player("Ox", Figure.X);
players[1] = new Player("Xo", Figure.O);
final GameController gameController = new GameController(gameName, players, board);
final Figure testValue = Figure.O;
board.setFigure(0,0,testValue);
board.setFigure(0,1,testValue);
board.setFigure(0,2,testValue);
assertEquals(players[1],gameController.getWinner());
}
@Test
public void testGetWinnerForRows() throws Exception {
final String gameName = "XO";
final Board board = new Board();
final Player[] players = new Player[2];
players[0] = new Player("Ox", Figure.X);
players[1] = new Player("Xo", Figure.O);
final GameController gameController = new GameController(gameName, players, board);
final Figure testValue = Figure.O;
board.setFigure(0,0,testValue);
board.setFigure(1,0,testValue);
board.setFigure(2,0,testValue);
assertEquals(players[1],gameController.getWinner());
}
@Test
public void testGetGameName() throws Exception {
final String gameName = "XO";
final Board board = new Board();
final Player[] players = new Player[2];
players[0] = new Player("Ox", Figure.X);
players[1] = new Player("Xo", Figure.O);
final GameController gameController = new GameController(gameName, players, board);
assertEquals(gameName,gameController.getGameName());
}
@Test
public void testGetPlayers() throws Exception {
final String gameName = "XO";
final Board board = new Board();
final Player[] players = new Player[2];
players[0] = new Player("Ox", Figure.X);
players[1] = new Player("Xo", Figure.O);
final GameController gameController = new GameController(gameName, players, board);
assertEquals(players, gameController.getPlayers());
}
@Test
public void testGetBoard() throws Exception {
final String gameName = "XO";
final Board board = new Board();
final Player[] players = new Player[2];
players[0] = new Player("Ox", Figure.X);
players[1] = new Player("Xo", Figure.O);
final GameController gameController = new GameController(gameName, players, board);
assertEquals(board,gameController.getBoard());
}
@Test
public void testMove() throws Exception {
final String gameName = "XO";
final Figure testValue = Figure.O;
final Board board = new Board();
final Player[] players = new Player[2];
players[0] = new Player("Ox", Figure.X);
players[1] = new Player("Xo", Figure.O);
final GameController gameController = new GameController(gameName, players, board);
gameController.move(1,1,testValue);
assertEquals(testValue,gameController.getBoard().getFigure(1,1));
}
@Test
public void testIncorrectMove() throws Exception {
final String gameName = "XO";
final Figure testValue = Figure.O;
final Board board = new Board();
final Player[] players = new Player[2];
players[0] = new Player("Ox", Figure.X);
players[1] = new Player("Xo", Figure.O);
final GameController gameController = new GameController(gameName, players, board);
gameController.move(1,1,testValue);
try {
gameController.move(1,1,testValue);
fail();
} catch (PointOccupiedException e) {}
}
@Test
public void testGetCurrentPlayer() throws Exception {
final String gameName = "XO";
final Board board = new Board();
final Player[] players = new Player[2];
players[0] = new Player("Ox", Figure.X);
players[1] = new Player("Xo", Figure.O);
final GameController gameController = new GameController(gameName, players, board);
final Figure testValueO = Figure.O;
final Figure testValueX = Figure.X;
board.setFigure(0,0,testValueO);
board.setFigure(0,1,testValueX);
board.setFigure(1,2,testValueO);
board.setFigure(0,2,testValueX);
board.setFigure(2,0,testValueO);
board.setFigure(1,0,testValueX);
assertEquals(players[1],gameController.getCurrentPlayer(players[1]));
assertEquals(players[0],gameController.getCurrentPlayer(players[0]));
}
} |
package squeek.earliestofgames.content;
import java.util.ArrayList;
import java.util.List;
import squeek.earliestofgames.filters.IFilter;
import net.minecraft.command.IEntitySelector;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityHopper;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.common.util.ForgeDirection;
public class CrateTile extends TileEntity implements IInventory
{
protected ItemStack[] inventoryItems;
protected int captureCooldown = 0;
protected int captureCheckInterval = 8;
protected IFilter[] filters = new IFilter[ForgeDirection.VALID_DIRECTIONS.length];
public CrateTile()
{
inventoryItems = new ItemStack[14];
}
public void setFilterOfSide(ForgeDirection side, IFilter filter)
{
if (side == ForgeDirection.UNKNOWN)
return;
filters[side.ordinal()] = filter;
}
public boolean canItemPassThroughSide(ItemStack item, ForgeDirection side)
{
return side != ForgeDirection.UNKNOWN && filters[side.ordinal()] != null && filters[side.ordinal()].passesFilter(item);
}
public boolean isCoolingDown()
{
return captureCooldown > 0;
}
public boolean isInventoryFull()
{
for (ItemStack itemStack : inventoryItems)
{
if (itemStack == null)
return false;
}
return true;
}
public boolean couldCaptureItems()
{
return !isInventoryFull();
}
@Override
public void updateEntity()
{
super.updateEntity();
captureCooldown
if (!isCoolingDown() && couldCaptureItems())
captureItemsInside();
}
public boolean canItemEscape(ItemStack itemStack)
{
for (ForgeDirection side : ForgeDirection.VALID_DIRECTIONS)
{
if (side == ForgeDirection.UP)
continue;
if (canItemPassThroughSide(itemStack, side))
return true;
}
return false;
}
public List<ItemStack> getEscapableItemsInInventory()
{
List<ItemStack> escapableItems = new ArrayList<ItemStack>();
for (ItemStack itemStack : inventoryItems)
{
if (canItemEscape(itemStack))
escapableItems.add(itemStack);
}
return escapableItems;
}
public boolean releaseEscapableItems()
{
boolean didItemEscape = false;
List<ItemStack> escapableItems = getEscapableItemsInInventory();
for (ItemStack itemStack : escapableItems)
{
didItemEscape = true;
}
return didItemEscape;
}
public boolean captureItemsInside()
{
boolean didCapture = false;
List<EntityItem> itemEntities = getItemEntitiesInside();
for (EntityItem itemEntity : itemEntities)
{
// insertStackFromEntity
didCapture = didCapture || TileEntityHopper.func_145898_a(this, itemEntity);
}
return didCapture;
}
public List<EntityItem> getItemEntitiesInside()
{
return worldObj.selectEntitiesWithinAABB(EntityItem.class, ((Crate) getBlockType()).getInnerBoundingBox(worldObj, xCoord, yCoord, zCoord), IEntitySelector.selectAnything);
}
@Override
public int getSizeInventory()
{
return inventoryItems.length;
}
@Override
public ItemStack getStackInSlot(int slotNum)
{
return inventoryItems[slotNum];
}
@Override
public ItemStack decrStackSize(int slotNum, int count)
{
ItemStack itemStack = getStackInSlot(slotNum);
if (itemStack != null)
{
if (itemStack.stackSize <= count)
setInventorySlotContents(slotNum, null);
else
{
itemStack = itemStack.splitStack(count);
markDirty();
}
}
return itemStack;
}
@Override
public ItemStack getStackInSlotOnClosing(int slotNum)
{
ItemStack item = getStackInSlot(slotNum);
setInventorySlotContents(slotNum, null);
return item;
}
@Override
public void setInventorySlotContents(int slotNum, ItemStack itemStack)
{
inventoryItems[slotNum] = itemStack;
if (itemStack != null && itemStack.stackSize > getInventoryStackLimit())
itemStack.stackSize = getInventoryStackLimit();
markDirty();
}
@Override
public String getInventoryName()
{
return getBlockType().getLocalizedName();
}
@Override
public boolean hasCustomInventoryName()
{
return false;
}
@Override
public int getInventoryStackLimit()
{
return 64;
}
@Override
public boolean isUseableByPlayer(EntityPlayer player)
{
return this.worldObj.getTileEntity(this.xCoord, this.yCoord, this.zCoord) != this ? false : player.getDistanceSq((double) this.xCoord + 0.5D, (double) this.yCoord + 0.5D, (double) this.zCoord + 0.5D) <= 64.0D;
}
@Override
public void openInventory()
{
}
@Override
public void closeInventory()
{
}
@Override
public boolean isItemValidForSlot(int slotNum, ItemStack itemStack)
{
return true;
}
@Override
public void writeToNBT(NBTTagCompound compound)
{
super.writeToNBT(compound);
NBTTagList items = new NBTTagList();
for (int slotNum = 0; slotNum < getSizeInventory(); slotNum++)
{
ItemStack stack = getStackInSlot(slotNum);
if (stack != null)
{
NBTTagCompound item = new NBTTagCompound();
item.setByte("Slot", (byte) slotNum);
stack.writeToNBT(item);
items.appendTag(item);
}
}
compound.setTag("Items", items);
}
@Override
public void readFromNBT(NBTTagCompound compound)
{
super.readFromNBT(compound);
NBTTagList items = compound.getTagList("Items", Constants.NBT.TAG_COMPOUND);
for (int slotNum = 0; slotNum < items.tagCount(); slotNum++)
{
NBTTagCompound item = items.getCompoundTagAt(slotNum);
int slot = item.getByte("Slot");
if (slot >= 0 && slot < getSizeInventory())
{
setInventorySlotContents(slot, ItemStack.loadItemStackFromNBT(item));
}
}
}
} |
package org.opendaylight.yangtools.yang.parser.stmt.reactor;
import static java.util.Objects.requireNonNull;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.yangtools.yang.common.QNameModule;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement;
import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
import org.opendaylight.yangtools.yang.parser.spi.meta.CopyHistory;
import org.opendaylight.yangtools.yang.parser.spi.meta.CopyType;
import org.opendaylight.yangtools.yang.parser.spi.meta.ModelProcessingPhase;
import org.opendaylight.yangtools.yang.parser.spi.meta.NamespaceBehaviour.StorageNodeType;
import org.opendaylight.yangtools.yang.parser.spi.meta.ParserNamespace;
import org.opendaylight.yangtools.yang.parser.spi.meta.StatementNamespace;
import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
/**
* A replica of a different statement. It does not allow modification, but produces an effective statement from a
* designated source.
*/
final class ReplicaStatementContext<A, D extends DeclaredStatement<A>, E extends EffectiveStatement<A, D>>
extends ReactorStmtCtx<A, D, E> {
private final StatementContextBase<?, ?, ?> parent;
private final ReactorStmtCtx<A, D, E> source;
ReplicaStatementContext(final StatementContextBase<?, ?, ?> parent, final ReactorStmtCtx<A, D, E> source) {
super(source);
this.parent = requireNonNull(parent);
this.source = requireNonNull(source);
if (source.isSupportedToBuildEffective()) {
source.incRef();
// FIXME: is this call really needed? it is inherited from source
setFullyDefined();
}
}
@Override
E createEffective() {
return source.buildEffective();
}
@Override
public EffectiveConfig effectiveConfig() {
return source.effectiveConfig();
}
@Override
public D declared() {
return source.declared();
}
@Override
public A argument() {
return source.argument();
}
@Override
public StatementSourceReference sourceReference() {
return source.sourceReference();
}
@Override
public String rawArgument() {
return source.rawArgument();
}
@Override
public Optional<StmtContext<A, D, E>> getOriginalCtx() {
return source.getOriginalCtx();
}
@Override
public Collection<? extends StatementContextBase<?, ?, ?>> mutableDeclaredSubstatements() {
return source.mutableDeclaredSubstatements();
}
@Override
public Collection<? extends Mutable<?, ?, ?>> mutableEffectiveSubstatements() {
return source.mutableEffectiveSubstatements();
}
@Override
public ModelProcessingPhase getCompletedPhase() {
return source.getCompletedPhase();
}
@Override
public CopyHistory history() {
return source.history();
}
@Override
public Collection<? extends StmtContext<?, ?, ?>> getEffectOfStatement() {
return List.of();
}
@Override
public Mutable<A, D, E> replicaAsChildOf(final Mutable<?, ?, ?> newParent) {
return source.replicaAsChildOf(newParent);
}
@Override
public Optional<? extends Mutable<?, ?, ?>> copyAsChildOf(final Mutable<?, ?, ?> newParent, final CopyType type,
final QNameModule targetModule) {
return source.copyAsChildOf(newParent, type, targetModule);
}
@Override
ReactorStmtCtx<?, ?, ?> asEffectiveChildOf(final StatementContextBase<?, ?, ?> newParent, final CopyType type,
final QNameModule targetModule) {
return source.asEffectiveChildOf(newParent, type, targetModule);
}
@Override
StatementDefinitionContext<A, D, E> definition() {
return source.definition();
}
@Override
void markNoParentRef() {
// No-op
}
@Override
int sweepSubstatements() {
if (fullyDefined()) {
source.decRef();
}
return 0;
}
@Override
public <K, V, T extends K, U extends V, N extends ParserNamespace<K, V>> void addToNs(final Class<@NonNull N> type,
final T key, final U value) {
throw new UnsupportedOperationException();
}
@Override
public Optional<StmtContext<A, D, E>> getPreviousCopyCtx() {
throw new UnsupportedOperationException();
}
@Override
public <K, KT extends K, N extends StatementNamespace<K, ?, ?>> void addContext(final Class<@NonNull N> namespace,
final KT key, final StmtContext<?, ?, ?> stmt) {
throw new UnsupportedOperationException();
}
@Override
public void addAsEffectOfStatement(final Collection<? extends StmtContext<?, ?, ?>> ctxs) {
throw new UnsupportedOperationException();
}
@Override
public Mutable<?, ?, ?> childCopyOf(final StmtContext<?, ?, ?> stmt, final CopyType type,
final QNameModule targetModule) {
throw new UnsupportedOperationException();
}
@Override boolean doTryToCompletePhase(final ModelProcessingPhase phase) {
throw new UnsupportedOperationException();
}
/*
* KEEP THINGS ORGANIZED!
*
* below methods exist in the same form in InferredStatementContext/SubstatementContext. If any adjustment is made
* here, make sure it is properly updated there.
*/
@Override
@Deprecated
public Optional<SchemaPath> schemaPath() {
return substatementGetSchemaPath();
}
@Override
public StatementContextBase<?, ?, ?> getParentContext() {
return parent;
}
@Override
public StorageNodeType getStorageNodeType() {
return StorageNodeType.STATEMENT_LOCAL;
}
@Override
public StatementContextBase<?, ?, ?> getParentNamespaceStorage() {
return parent;
}
@Override
public RootStatementContext<?, ?, ?> getRoot() {
return parent.getRoot();
}
@Override
protected boolean isIgnoringIfFeatures() {
return isIgnoringIfFeatures(parent);
}
@Override
protected boolean isIgnoringConfig() {
return isIgnoringConfig(parent);
}
@Override
protected boolean isParentSupportedByFeatures() {
return parent.isSupportedByFeatures();
}
} |
package uk.ac.ebi.quickgo.annotation.service.statistics;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.mockito.Mockito.*;
public class RequiredStatisticsWithGeneProductTest {
private StatisticsTypeConfigurer configurer = mock(StatisticsTypeConfigurer.class);
@Test
public void isConstructedProperly() {
List<RequiredStatisticType> requiredStatisticTypes = new ArrayList<>();
when(configurer.getConfiguredStatsTypes(anyList())).thenReturn(requiredStatisticTypes);
RequiredStatisticsWithGeneProduct withGeneProduct = new RequiredStatisticsWithGeneProduct(configurer);
assertThat(withGeneProduct.getStatsTypes(), hasSize(7));
}
} |
package org.csstudio.opibuilder.runmode;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Objects;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.csstudio.opibuilder.OPIBuilderPlugin;
import org.csstudio.opibuilder.actions.RefreshOPIAction;
import org.csstudio.opibuilder.datadefinition.NotImplementedException;
import org.csstudio.opibuilder.editparts.ExecutionMode;
import org.csstudio.opibuilder.editparts.WidgetEditPartFactory;
import org.csstudio.opibuilder.model.AbstractContainerModel;
import org.csstudio.opibuilder.model.DisplayModel;
import org.csstudio.opibuilder.persistence.XMLUtil;
import org.csstudio.opibuilder.util.MacrosInput;
import org.csstudio.opibuilder.util.ResourceUtil;
import org.csstudio.opibuilder.util.SingleSourceHelper;
import org.eclipse.core.commands.Command;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.NotEnabledException;
import org.eclipse.core.commands.NotHandledException;
import org.eclipse.core.commands.common.NotDefinedException;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.gef.DragTracker;
import org.eclipse.gef.EditDomain;
import org.eclipse.gef.GraphicalViewer;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.CommandStack;
import org.eclipse.gef.editparts.ScalableFreeformRootEditPart;
import org.eclipse.gef.tools.DragEditPartsTracker;
import org.eclipse.gef.ui.actions.ActionRegistry;
import org.eclipse.gef.ui.parts.GraphicalViewerImpl;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.events.ShellListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IPropertyListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPartSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.commands.ICommandService;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.ui.services.IServiceLocator;
/**
* An OPIShell is a CS-Studio OPI presented in an SWT shell, which allows
* more free integration with the host operating system. In most ways
* it behaves like an OPIView.
*
* All OPIShells are maintained in a static set within this class. To
* maintain a cache of all shells, construction is limited to a static
* method. The private constructor means that this class cannot be
* extended.
*
* In order for the OPIShell to be integrated with Eclipse functionality,
* in particular the right-click context menu, it needs to be registered
* against an existing IViewPart.
*
* @author Will Rogers, Matthew Furseman
*
*/
public final class OPIShell implements IOPIRuntime {
// Estimates for the size of a window border, for how much
// bigger to make a shell than the size of its contents.
private static final int WINDOW_BORDER_X = 30;
private static final int WINDOW_BORDER_Y = 30;
private static Logger log = OPIBuilderPlugin.getLogger();
public static final String OPI_SHELLS_CHANGED_ID = "org.csstudio.opibuilder.opiShellsChanged";
// The active OPIshell, or null if no OPIShell is active
public static OPIShell activeShell = null;
// Cache of open OPI shells in order of opening.
private static final Set<OPIShell> openShells = new LinkedHashSet<OPIShell>();
// The view against which the context menu is registered.
private IViewPart view;
// Variables that do not change for any shell.
private final Image icon;
private final Shell shell;
private final ActionRegistry actionRegistry;
private final GraphicalViewer viewer;
// Variables that change if OPI input is changed.
private DisplayModel displayModel;
private IPath path;
// macrosInput should not be null. If there are no macros it should
// be an empty MacrosInput object.
private MacrosInput macrosInput;
// Private constructor means you can't open an OPIShell without adding
// it to the cache.
private OPIShell(Display display, IPath path, MacrosInput macrosInput) throws Exception {
this.path = path;
this.macrosInput = macrosInput;
icon = OPIBuilderPlugin.imageDescriptorFromPlugin(OPIBuilderPlugin.PLUGIN_ID, "icons/OPIRunner.png")
.createImage(display);
shell = new Shell(display);
shell.setImage(icon);
displayModel = new DisplayModel(path);
displayModel.setOpiRuntime(this);
actionRegistry = new ActionRegistry();
viewer = new GraphicalViewerImpl();
viewer.createControl(shell);
viewer.setEditPartFactory(new WidgetEditPartFactory(ExecutionMode.RUN_MODE));
viewer.setRootEditPart(new ScalableFreeformRootEditPart() {
@Override
public DragTracker getDragTracker(Request req) {
return new DragEditPartsTracker(this);
}
@Override
public boolean isSelectable() {
return false;
}
});
EditDomain editDomain = new EditDomain() {
@Override
public void loadDefaultTool() {
setActiveTool(new RuntimePatchedSelectionTool());
}
};
editDomain.addViewer(viewer);
displayModel = createDisplayModel();
setTitle();
shell.setLayout(new FillLayout());
shell.addShellListener(new ShellListener() {
private boolean firstRun = true;
public void shellIconified(ShellEvent e) {}
public void shellDeiconified(ShellEvent e) {}
public void shellDeactivated(ShellEvent e) {
activeShell = null;
}
public void shellClosed(ShellEvent e) {
// Remove this shell from the cache.
openShells.remove(OPIShell.this);
sendUpdateCommand();
}
public void shellActivated(ShellEvent e) {
if (firstRun) {
// Resize the shell after it's open, so we can take into account different window borders.
// Do this only the first time it's activated.
resizeToContents();
shell.setFocus();
firstRun = false;
}
activeShell = OPIShell.this;
}
});
shell.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
if (!icon.isDisposed()) icon.dispose();
}
});
/*
* Don't open the Shell here, as it causes SWT to think the window is on top when it really isn't.
* Wait until the window is open, then call shell.setFocus() in the activated listener.
*
* Make some attempt at sizing the shell, sometimes a shell is not given focus and the shellActivated
* listener callback doesn't resize the window. It's better to have something a little too large as the
* default. Related to Eclipse bug 96700.
*/
shell.setSize(displayModel.getSize().width + WINDOW_BORDER_X, displayModel.getSize().height + WINDOW_BORDER_Y);
shell.setVisible(true);
}
/**
* In order for the right-click menu to work, this shell must be registered
* with a view. Register the context menu against the view.
* Make the view the default.
* @param view
*/
public void registerWithView(IViewPart view) {
this.view = view;
actionRegistry.registerAction(new RefreshOPIAction(this));
SingleSourceHelper.registerRCPRuntimeActions(actionRegistry, this);
OPIRunnerContextMenuProvider contextMenuProvider = new OPIRunnerContextMenuProvider(viewer, this);
getSite().registerContextMenu(contextMenuProvider, viewer);
viewer.setContextMenu(contextMenuProvider);
}
public MacrosInput getMacrosInput() {
return macrosInput;
}
public IPath getPath() {
return path;
}
public void raiseToTop() {
shell.forceFocus();
shell.forceActive();
shell.setFocus();
shell.setActive();
}
@Override
public boolean equals(Object o) {
boolean equal = false;
if (o instanceof OPIShell) {
OPIShell opiShell = (OPIShell) o;
equal = opiShell.getMacrosInput().equals(this.getMacrosInput());
equal &= opiShell.getPath().equals(this.path);
}
return equal;
}
public void close() {
shell.close();
dispose();
}
private DisplayModel createDisplayModel() throws Exception {
displayModel = new DisplayModel(path);
XMLUtil.fillDisplayModelFromInputStream(ResourceUtil.pathToInputStream(path), displayModel);
if (macrosInput != null) {
macrosInput = macrosInput.getCopy();
macrosInput.getMacrosMap().putAll(displayModel.getMacrosInput().getMacrosMap());
displayModel.setPropertyValue(AbstractContainerModel.PROP_MACROS, macrosInput);
}
viewer.setContents(displayModel);
displayModel.setViewer(viewer);
displayModel.setOpiRuntime(this);
return displayModel;
}
private void setTitle() {
if (displayModel.getName() != null && displayModel.getName().trim().length() > 0) {
shell.setText(displayModel.getName());
} else { // If the name doesn't exist, use the OPI path
shell.setText(path.toString());
}
}
private void resizeToContents() {
int frameX = shell.getSize().x - shell.getClientArea().width;
int frameY = shell.getSize().y - shell.getClientArea().height;
shell.setSize(displayModel.getSize().width + frameX, displayModel.getSize().height + frameY);
}
/**
* This is the only way to create an OPIShell
*/
public static void openOPIShell(IPath path, MacrosInput macrosInput) {
if (macrosInput == null) {
macrosInput = new MacrosInput(new LinkedHashMap<String, String>(), false);
}
boolean alreadyOpen = false;
for (OPIShell opiShell : openShells) {
if (opiShell.getPath().equals(path) && opiShell.getMacrosInput().equals(macrosInput)) {
opiShell.raiseToTop();
alreadyOpen = true;
}
}
if (!alreadyOpen) {
OPIShell os = null;
try {
os = new OPIShell(Display.getCurrent(), path, macrosInput);
openShells.add(os);
sendUpdateCommand();
} catch (Exception e) {
if (os != null) {
os.dispose();
}
log.log(Level.WARNING, "Failed to create new OPIShell.", e);
}
}
}
/**
* Close all open OPIShells. Use getAllShells() for a copy
* of the set, to avoid removing items during iteration.
*/
public static void closeAll() {
for (OPIShell s : getAllShells()) {
s.close();
}
}
/**
* Show all open OPIShells.
*/
public static void showAll() {
for (OPIShell s : getAllShells()) {
s.raiseToTop();
}
}
/** Search the cache of open OPIShells to find a match for the
* input Shell object.
*
* Return associated OPIShell or Null if none found
*/
public static OPIShell getOPIShellForShell(final Shell target) {
OPIShell foundShell = null;
if (target != null) {
for (OPIShell os : openShells) {
if (os.shell == target) {
foundShell = os;
break;
}
}
}
return foundShell;
}
/**
* Return a copy of the set of open shells. Returning the same
* instance may lead to problems when closing shells.
* @return a copy of the set of open shells.
*/
public static Set<OPIShell> getAllShells() {
return new LinkedHashSet<OPIShell>(openShells);
}
/**
* Alert whoever is listening that a new OPIShell has been created.
*/
private static void sendUpdateCommand() {
IServiceLocator serviceLocator = PlatformUI.getWorkbench();
ICommandService commandService = (ICommandService) serviceLocator.getService(ICommandService.class);
try {
Command command = commandService.getCommand(OPI_SHELLS_CHANGED_ID);
command.executeWithChecks(new ExecutionEvent());
} catch (ExecutionException | NotHandledException | NotEnabledException | NotDefinedException e) {
log.log(Level.WARNING, "Failed to send OPI shells changed command", e);
}
}
@Override
public void addPropertyListener(IPropertyListener listener) {
throw new NotImplementedException();
}
@Override
public void createPartControl(Composite parent) {
throw new NotImplementedException();
}
@Override
public void dispose() {
shell.dispose();
actionRegistry.dispose();
}
@Override
public IWorkbenchPartSite getSite() {
if (view != null) {
return view.getSite();
} else {
return null;
}
}
@Override
public String getTitle() {
return shell.getText();
}
@Override
public Image getTitleImage() {
throw new NotImplementedException();
}
@Override
public String getTitleToolTip() {
return shell.getToolTipText();
}
@Override
public void removePropertyListener(IPropertyListener listener) {
throw new NotImplementedException();
}
@Override
public void setFocus() {
throw new NotImplementedException();
}
@SuppressWarnings("rawtypes")
@Override
public Object getAdapter(Class adapter) {
if (adapter == ActionRegistry.class)
return this.actionRegistry;
if (adapter == GraphicalViewer.class)
return this.viewer;
if (adapter == CommandStack.class)
return this.viewer.getEditDomain().getCommandStack();
return null;
}
@Override
public void setWorkbenchPartName(String name) {
throw new NotImplementedException();
}
/**
* Render a new OPI in the same shell. The file path
* changes but the macros remain the same. Is this correct?
*/
@Override
public void setOPIInput(IEditorInput input) throws PartInitException {
try {
if (input instanceof IFileEditorInput) {
this.path = ((IFileEditorInput) input).getFile().getFullPath();
} else if (input instanceof RunnerInput) {
this.path = ((RunnerInput) input).getPath();
}
displayModel = createDisplayModel();
setTitle();
resizeToContents();
} catch (Exception e) {
OPIBuilderPlugin.getLogger().log(Level.WARNING, "Failed to replace OPIShell contents.", e);
}
}
@Override
public IEditorInput getOPIInput() {
IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(displayModel.getOpiFilePath());
return new FileEditorInput(file);
}
@Override
public DisplayModel getDisplayModel() {
return displayModel;
}
@Override
public int hashCode() {
return Objects.hash(OPIShell.class, macrosInput, path);
}
} |
package gov.nih.nci.ess.ae.service.query.service;
import gov.nih.nci.ess.ae.service.common.AdverseEventEnterpriseServiceI;
import gov.nih.nci.ess.ae.service.query.common.QueryI;
import java.rmi.RemoteException;
import org.globus.wsrf.config.ContainerConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class QueryImpl extends QueryImplBase {
private static final String BEAN_NAME = "adverseEventQueryImpl";
private QueryI aeQuery;
public QueryImpl() throws RemoteException {
super();
String exp = ContainerConfig.getConfig().getOption(AdverseEventEnterpriseServiceI.SPRING_CLASSPATH_EXPRESSION, AdverseEventEnterpriseServiceI.DEFAULT_SPRING_CLASSPATH_EXPRESSION);
ApplicationContext ctx = new ClassPathXmlApplicationContext(exp);
aeQuery = (QueryI) ctx.getBean(BEAN_NAME);
}
public ess.caaers.nci.nih.gov.AdverseEvent[] findAdverseEvents(ess.caaers.nci.nih.gov.AdverseEvent adverseEvent) throws RemoteException, gov.nih.nci.ess.ae.service.management.stubs.types.AdverseEventServiceException {
return aeQuery.findAdverseEvents(adverseEvent);
}
public ess.caaers.nci.nih.gov.AdverseEvent getAdverseEventData(ess.caaers.nci.nih.gov.Id adverseEventIdentifier) throws RemoteException, gov.nih.nci.ess.ae.service.management.stubs.types.AdverseEventServiceException {
return aeQuery.getAdverseEventData(adverseEventIdentifier);
}
} |
package org.cagrid.identifiers.namingauthority;
import java.net.URI;
import java.util.ArrayList;
import org.cagrid.identifiers.namingauthority.domain.IdentifierData;
import org.cagrid.identifiers.namingauthority.domain.IdentifierValues;
import org.cagrid.identifiers.namingauthority.domain.KeyData;
import org.cagrid.identifiers.namingauthority.domain.KeyValues;
import org.cagrid.identifiers.namingauthority.test.NamingAuthorityTestCaseBase;
import org.cagrid.identifiers.namingauthority.util.Keys;
public class NamingAuthorityTestCase extends NamingAuthorityTestCaseBase {
private static IdentifierData globalValues = null;
static {
globalValues = new IdentifierData();
globalValues
.put("URL", new KeyData(null, new String[]{"http:
globalValues.put("CODE", new KeyData(null, new String[]{"007"}));
}
public void testInvalidIdentifier() {
// Identifier is not local to prefix hosted by naming authority
URI prefix = URI.create("http://na.cagrid.org/foo/");
try {
this.NamingAuthority.resolveIdentifier(null, prefix);
} catch (InvalidIdentifierException e) {
// expected
} catch (NamingAuthorityConfigurationException e) {
e.printStackTrace();
fail("test configuration error");
} catch (NamingAuthoritySecurityException e) {
e.printStackTrace();
fail("test configuration exception error");
}
// Identifier does not exist
prefix = URI.create(this.NamingAuthority.getConfiguration().getNaPrefixURI() + "BADIDENTIFIER");
try {
this.NamingAuthority.resolveIdentifier(null, prefix);
} catch (InvalidIdentifierException e) {
// expected
} catch (NamingAuthorityConfigurationException e) {
e.printStackTrace();
fail("test configuration error");
} catch (NamingAuthoritySecurityException e) {
e.printStackTrace();
fail("test configuration security exception");
}
}
// Test missing key name
public void testMissingKeyName() {
IdentifierData values = new IdentifierData();
values.put("", null);
try {
URI id = this.NamingAuthority.createIdentifier(null, values);
System.out.println("testMissingKeyName: " + id.normalize().toString());
fail("Expected InvalidIdentifierValuesException was not raised");
} catch (InvalidIdentifierValuesException e) {
// expected
} catch (Exception e) {
e.printStackTrace();
fail("Unexpected exception: " + e.getMessage());
}
}
// Can create and resolve identifier that has no IdentifierValues
public void testNullIdentifierValues() {
// Null IdentifierValues
assertResolvedValues(null);
// Empty IdentifierValues
IdentifierData values = null;
try {
URI id = this.NamingAuthority.createIdentifier(null, new IdentifierData());
values = this.NamingAuthority.resolveIdentifier(null, id);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
if (values != null) {
fail("Values is expected to be null");
}
}
// Create Identifier with keys that have no data
public void testCreateIdentifierKeysNoData() {
IdentifierData values = new IdentifierData();
values.put("KEY1", null);
values.put("KEY2", new KeyData());
values.put("KEY3", new KeyData(null, (ArrayList<String>) null));
values.put("KEY4", new KeyData(null, new ArrayList<String>()));
values.put("KEY5", new KeyData(null, (String[]) null));
values.put("KEY6", new KeyData(null, new String[]{}));
try {
URI id = this.NamingAuthority.createIdentifier(null, values);
System.out.println("testCreateIdentifierKeysNoData: " + id.normalize().toString());
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
// Create identifier with multiple values per key
public void testMultipleIdentifierValues() {
assertResolvedValues(globalValues);
}
// Test getKeys interface
public void testGetKeys() {
assertKeys(globalValues);
}
// Test getKeyValues interface
public void testGetKeyValues() {
assertKeyValues(globalValues, new String[]{"URL", "CODE"});
}
// Test createKeys interface
public void testCreateKeys() {
URI id = null;
IdentifierData resolvedValues = null;
try {
id = this.NamingAuthority.createIdentifier(null, globalValues);
} catch (Exception e) {
e.printStackTrace();
fail("Failed to create identifier");
}
// InvalidIdentifierValues (null)
try {
this.NamingAuthority.createKeys(null, id, null);
fail("Expected InvalidIdentifierValuesException was not raised");
} catch (InvalidIdentifierValuesException e) {
// expected
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
// InvalidIdentifierValues (bad key's rwidentifier)
IdentifierData newKeys = new IdentifierData();
newKeys.put("BAD RWINDENTIFIER", new KeyData(URI.create("http://badurl"), new ArrayList<String>()));
try {
this.NamingAuthority.createKeys(null, id, newKeys);
fail("Expected InvalidIdentifierValuesException was not raised");
} catch (InvalidIdentifierValuesException e) {
// expected
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
// InvalidIdentifierValues (bad ADMIN_IDENTIFIER)
newKeys = new IdentifierData();
newKeys.put(Keys.ADMIN_IDENTIFIERS, new KeyData(null, new String[]{"http://bad"}));
try {
this.NamingAuthority.createKeys(null, id, newKeys);
fail("Expected InvalidIdentifierValuesException was not raised");
} catch (InvalidIdentifierValuesException e) {
// expected
} catch (Exception e) {
fail(e.getMessage());
}
// InvalidIdentifierValues (bad READWRITE_IDENTIFIERS)
newKeys = new IdentifierData();
newKeys.put(Keys.READWRITE_IDENTIFIERS, new KeyData(null, new String[]{"http://bad"}));
try {
this.NamingAuthority.createKeys(null, id, newKeys);
fail("Expected InvalidIdentifierValuesException was not raised");
} catch (InvalidIdentifierValuesException e) {
// expected
} catch (Exception e) {
fail(e.getMessage());
}
// This should be successful
newKeys = new IdentifierData();
newKeys.put("ADD KEY1", new KeyData(null, new String[]{"key1 value1", "key1 value2"}));
newKeys.put("ADD KEY2", new KeyData(null, new String[]{"key2 value"}));
try {
this.NamingAuthority.createKeys(null, id, newKeys);
resolvedValues = this.NamingAuthority.resolveIdentifier(null, id);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
checkKeysWithValues(resolvedValues, new String[]{"CODE", "URL", "ADD KEY1", "ADD KEY2"});
// Key already exists
newKeys = new IdentifierData();
newKeys.put("CODE", new KeyData(null, new String[]{"code value"}));
try {
this.NamingAuthority.createKeys(null, id, newKeys);
resolvedValues = this.NamingAuthority.resolveIdentifier(null, id);
fail("Expected InvalidIdentifierValuesException was not raised");
} catch (InvalidIdentifierValuesException e) {
// expected
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
// Test deleteKeys interface
public void testDeleteKeys() {
URI id = null;
IdentifierData resolvedValues = null;
try {
id = this.NamingAuthority.createIdentifier(null, globalValues);
} catch (Exception e) {
e.printStackTrace();
fail("Failed to create identifier");
}
// InvalidIdentifierValues (null)
try {
this.NamingAuthority.deleteKeys(null, id, null);
fail("Expected InvalidIdentifierValuesException was not raised");
} catch (InvalidIdentifierValuesException e) {
// expected
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
// InvalidIdentifierValues (key doesn't exist)
String[] keyList = new String[]{"wrongKeyName"};
try {
this.NamingAuthority.deleteKeys(null, id, keyList);
fail("Expected InvalidIdentifierValuesException was not raised");
} catch (InvalidIdentifierValuesException e) {
// expected
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
// This should be successful
keyList = new String[]{"CODE"};
try {
this.NamingAuthority.deleteKeys(null, id, keyList);
resolvedValues = this.NamingAuthority.resolveIdentifier(null, id);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
if (resolvedValues.getValues("CODE") != null) {
fail("CODE still exists");
}
if (resolvedValues.getValues("URL") == null) {
fail("URL is no longer present");
}
}
// Test replaceKeys interface
public void testReplaceKeys() {
URI id = null;
IdentifierData resolvedValues = null;
try {
id = this.NamingAuthority.createIdentifier(null, globalValues);
} catch (Exception e) {
e.printStackTrace();
fail("Failed to create identifier");
}
// InvalidIdentifierValues (null)
try {
this.NamingAuthority.replaceKeyValues(null, id, null);
fail("Expected InvalidIdentifierValuesException was not raised");
} catch (InvalidIdentifierValuesException e) {
// expected
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
// InvalidIdentifierValues (key doesn't exist)
IdentifierValues values = new IdentifierValues();
values.put("wrongKeyName", null);
try {
this.NamingAuthority.replaceKeyValues(null, id, values);
fail("Expected InvalidIdentifierValuesException was not raised");
} catch (InvalidIdentifierValuesException e) {
// expected
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
// This should be successful
String newCode = "008";
values = new IdentifierValues();
values.put("CODE", new KeyValues(new String[]{newCode}));
try {
this.NamingAuthority.replaceKeyValues(null, id, values);
resolvedValues = this.NamingAuthority.resolveIdentifier(null, id);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
if (!resolvedValues.getValues("CODE").getValues().get(0).equals(newCode)) {
fail("Unexpected CODE");
}
}
} |
package org.eclipse.birt.chart.ui.swt.wizard.data;
import java.util.List;
import org.eclipse.birt.chart.exception.ChartException;
import org.eclipse.birt.chart.model.ChartWithAxes;
import org.eclipse.birt.chart.model.data.DataPackage;
import org.eclipse.birt.chart.model.data.Query;
import org.eclipse.birt.chart.model.data.SeriesDefinition;
import org.eclipse.birt.chart.model.data.SeriesGrouping;
import org.eclipse.birt.chart.model.data.impl.QueryImpl;
import org.eclipse.birt.chart.model.data.impl.SeriesGroupingImpl;
import org.eclipse.birt.chart.ui.extension.i18n.Messages;
import org.eclipse.birt.chart.ui.swt.ColorPalette;
import org.eclipse.birt.chart.ui.swt.ColumnBindingInfo;
import org.eclipse.birt.chart.ui.swt.DataDefinitionTextManager;
import org.eclipse.birt.chart.ui.swt.DataTextDropListener;
import org.eclipse.birt.chart.ui.swt.DefaultSelectDataComponent;
import org.eclipse.birt.chart.ui.swt.IQueryExpressionManager;
import org.eclipse.birt.chart.ui.swt.SimpleTextTransfer;
import org.eclipse.birt.chart.ui.swt.composites.BaseGroupSortingDialog;
import org.eclipse.birt.chart.ui.swt.composites.GroupSortingDialog;
import org.eclipse.birt.chart.ui.swt.fieldassist.CComboAssistField;
import org.eclipse.birt.chart.ui.swt.fieldassist.CTextContentAdapter;
import org.eclipse.birt.chart.ui.swt.fieldassist.FieldAssistHelper;
import org.eclipse.birt.chart.ui.swt.fieldassist.IContentChangeListener;
import org.eclipse.birt.chart.ui.swt.fieldassist.TextAssistField;
import org.eclipse.birt.chart.ui.swt.interfaces.IChartDataSheet;
import org.eclipse.birt.chart.ui.swt.interfaces.IDataServiceProvider;
import org.eclipse.birt.chart.ui.swt.interfaces.IUIServiceProvider;
import org.eclipse.birt.chart.ui.swt.wizard.ChartWizardContext;
import org.eclipse.birt.chart.ui.util.ChartUIConstants;
import org.eclipse.birt.chart.ui.util.ChartUIUtil;
import org.eclipse.birt.chart.ui.util.UIHelper;
import org.eclipse.birt.chart.util.ChartUtil;
import org.eclipse.birt.chart.util.PluginSettings;
import org.eclipse.birt.core.data.ExpressionUtil;
import org.eclipse.birt.core.data.IColumnBinding;
import org.eclipse.birt.core.exception.BirtException;
import org.eclipse.birt.core.ui.frameworks.taskwizard.WizardBase;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTarget;
import org.eclipse.swt.dnd.Transfer;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
public class BaseDataDefinitionComponent extends DefaultSelectDataComponent implements
SelectionListener,
ModifyListener,
FocusListener,
KeyListener,
IQueryExpressionManager
{
protected Composite cmpTop;
private CCombo cmbDefinition;
protected Text txtDefinition = null;
private Button btnBuilder = null;
private Button btnGroup = null;
protected Query query = null;
protected SeriesDefinition seriesdefinition = null;
protected ChartWizardContext context = null;
private String sTitle = null;
private String description = ""; //$NON-NLS-1$
private String tooltipWhenBlank = Messages.getString( "BaseDataDefinitionComponent.Tooltip.InputValueExpression" ); //$NON-NLS-1$
protected boolean isQueryModified;
private final String queryType;
private int style = BUTTON_NONE;
private AggregateEditorComposite fAggEditorComposite;
/** Indicates no button */
public static final int BUTTON_NONE = 0;
/** Indicates button for group sorting will be created */
public static final int BUTTON_GROUP = 1;
/** Indicates button for aggregation will be created */
public static final int BUTTON_AGGREGATION = 2;
/**
*
* @param queryType
* @param seriesdefinition
* @param query
* @param context
* @param sTitle
*/
public BaseDataDefinitionComponent( String queryType,
SeriesDefinition seriesdefinition, Query query,
ChartWizardContext context, String sTitle )
{
this( BUTTON_NONE, queryType, seriesdefinition, query, context, sTitle );
}
/**
*
*
* @param style
* Specify buttons by using '|'. See {@link #BUTTON_GROUP},
* {@link #BUTTON_NONE}, {@link #BUTTON_AGGREGATION}
* @param queryType
* query type. See {@link ChartUIConstants#QUERY_CATEGORY},
* {@link ChartUIConstants#QUERY_VALUE},
* {@link ChartUIConstants#QUERY_OPTIONAL}
* @param seriesdefinition
* @param query
* @param context
* @param sTitle
*/
public BaseDataDefinitionComponent( int style, String queryType,
SeriesDefinition seriesdefinition, Query query,
ChartWizardContext context, String sTitle )
{
super( );
this.query = query;
this.queryType = queryType;
this.seriesdefinition = seriesdefinition;
this.context = context;
this.sTitle = ( sTitle == null || sTitle.length( ) == 0 ) ? Messages.getString( "BaseDataDefinitionComponent.Text.SpecifyDataDefinition" ) //$NON-NLS-1$
: sTitle;
this.style = style;
}
public Composite createArea( Composite parent )
{
int numColumns = 2;
if ( description != null && description.length( ) > 0 )
{
numColumns++;
}
if ( ( style & BUTTON_AGGREGATION ) == BUTTON_AGGREGATION )
{
numColumns++;
}
if ( ( style & BUTTON_GROUP ) == BUTTON_GROUP )
{
numColumns++;
}
cmpTop = new Composite( parent, SWT.NONE );
{
GridLayout glContent = new GridLayout( );
glContent.numColumns = numColumns;
glContent.marginHeight = 0;
glContent.marginWidth = 0;
glContent.horizontalSpacing = 2;
cmpTop.setLayout( glContent );
GridData gd = new GridData( GridData.FILL_HORIZONTAL );
cmpTop.setLayoutData( gd );
}
Label lblDesc = null;
if ( description != null && description.length( ) > 0 )
{
lblDesc = new Label( cmpTop, SWT.NONE );
lblDesc.setText( description );
lblDesc.setToolTipText( tooltipWhenBlank );
}
if ( ( style & BUTTON_AGGREGATION ) == BUTTON_AGGREGATION )
{
createAggregationItem( cmpTop );
}
boolean isSharingChart = context.getDataServiceProvider( ).checkState( IDataServiceProvider.SHARE_CHART_QUERY );
final Object[] predefinedQuery = context.getPredefinedQuery( queryType );
// If current is the sharing query case and predefined queries are not null,
// the input field should be a combo component.
IDataServiceProvider provider = context.getDataServiceProvider( );
boolean needComboField = predefinedQuery != null
&& predefinedQuery.length > 0
&& ( provider.checkState( IDataServiceProvider.SHARE_QUERY )
|| provider.checkState( IDataServiceProvider.HAS_CUBE ) || provider.checkState( IDataServiceProvider.INHERIT_COLUMNS_GROUPS ) );
needComboField &= !isSharingChart;
boolean hasContentAssist = ( !isSharingChart && predefinedQuery != null && predefinedQuery.length > 0 );
if ( needComboField )
{
// Create a composite to decorate combo field for the content assist function.
Composite control = new Composite( cmpTop, SWT.NONE );
GridData gd = new GridData( GridData.FILL_BOTH );
gd.widthHint = 80;
control.setLayoutData( gd );
GridLayout gl = new GridLayout( );
FieldAssistHelper.getInstance( ).initDecorationMargin( gl );
control.setLayout( gl );
cmbDefinition = new CCombo( control,
context.getDataServiceProvider( )
.checkState( IDataServiceProvider.PART_CHART ) ? SWT.READ_ONLY
| SWT.BORDER
: SWT.BORDER );
gd = new GridData( GridData.FILL_HORIZONTAL );
gd.grabExcessHorizontalSpace = true;
cmbDefinition.setLayoutData( gd );
// Initialize content assist.
if ( hasContentAssist )
{
String[] items = getContentItems( predefinedQuery );
if ( items != null )
{
new CComboAssistField( cmbDefinition, null, items );
}
}
if ( predefinedQuery.length > 0 )
{
populateExprComboItems( predefinedQuery );
}
else if ( getQuery( ).getDefinition( ) == null
|| getQuery( ).getDefinition( ).equals( "" ) ) //$NON-NLS-1$
{
cmbDefinition.setEnabled( false );
}
cmbDefinition.addListener( SWT.Selection, new Listener( ) {
public void handleEvent( Event event )
{
String oldQuery = query.getDefinition( ) == null ? "" : query.getDefinition( ); //$NON-NLS-1$
// Combo may be disposed, so cache the text first
String text = cmbDefinition.getText( );
// Do nothing for the same query
if ( !isTableSharedBinding( ) && text.equals( oldQuery ) )
{
return;
}
updateQuery( text );
// Set category/Y optional expression by value series
// expression if it is crosstab sharing.
if ( !oldQuery.equals( text )
&& queryType == ChartUIConstants.QUERY_VALUE )
{
if ( context.getDataServiceProvider( )
.update( ChartUIConstants.QUERY_VALUE, text ) )
{
Event e = new Event( );
e.data = BaseDataDefinitionComponent.this;
e.widget = cmbDefinition;
e.type = IChartDataSheet.EVENT_QUERY;
context.getDataSheet( ).notifyListeners( e );
}
}
// Change direction once category query is changed in xtab
// case
if ( context.getDataServiceProvider( )
.checkState( IDataServiceProvider.PART_CHART )
&& ChartUIConstants.QUERY_CATEGORY.equals( queryType )
&& context.getModel( ) instanceof ChartWithAxes )
{
( (ChartWithAxes) context.getModel( ) ).setTransposed( cmbDefinition.getSelectionIndex( ) > 0 );
}
if ( predefinedQuery.length == 0
&& ( getQuery( ).getDefinition( ) == null || getQuery( ).getDefinition( )
.equals( "" ) ) ) //$NON-NLS-1$
{
cmbDefinition.setEnabled( false );
}
}
} );
cmbDefinition.addModifyListener( this );
cmbDefinition.addFocusListener( this );
cmbDefinition.addKeyListener( this );
initComboExprText( );
}
else
{
Composite control = cmpTop;
if ( hasContentAssist )
{
// Create a composite to decorate text field for the content assist function.
control = new Composite( cmpTop, SWT.NONE );
GridData gd = new GridData( GridData.FILL_BOTH );
gd.widthHint = 80;
control.setLayoutData( gd );
GridLayout gl = new GridLayout( );
FieldAssistHelper.getInstance( ).initDecorationMargin( gl );
control.setLayout( gl );
}
txtDefinition = new Text( control, SWT.BORDER | SWT.SINGLE );
GridData gdTXTDefinition = new GridData( GridData.FILL_HORIZONTAL );
gdTXTDefinition.widthHint = 80;
gdTXTDefinition.grabExcessHorizontalSpace = true;
txtDefinition.setLayoutData( gdTXTDefinition );
if ( query != null && query.getDefinition( ) != null )
{
txtDefinition.setText( query.getDefinition( ) );
txtDefinition.setToolTipText( getTooltipForDataText( query.getDefinition( ) ) );
}
txtDefinition.addModifyListener( this );
txtDefinition.addFocusListener( this );
txtDefinition.addKeyListener( this );
// Initialize content assist.
if ( hasContentAssist )
{
String[] items = getContentItems( predefinedQuery );
if ( items != null )
{
TextAssistField taf = new TextAssistField( txtDefinition, null, items );
((CTextContentAdapter)taf.getContentAdapter( )).addContentChangeListener( new IContentChangeListener(){
public void contentChanged( Control control,
Object newValue, Object oldValue )
{
isQueryModified = true;
saveQuery( );
}} );
}
}
}
// Listener for handling dropping of custom table header
Control dropControl = getInputControl( );
DropTarget target = new DropTarget( dropControl, DND.DROP_COPY );
Transfer[] types = new Transfer[]{
SimpleTextTransfer.getInstance( )
};
target.setTransfer( types );
// Add drop support
target.addDropListener( new DataTextDropListener( dropControl ) );
// Add color manager
DataDefinitionTextManager.getInstance( )
.addDataDefinitionText( dropControl, this );
btnBuilder = new Button( cmpTop, SWT.PUSH );
{
GridData gdBTNBuilder = new GridData( );
ChartUIUtil.setChartImageButtonSizeByPlatform( gdBTNBuilder );
btnBuilder.setLayoutData( gdBTNBuilder );
btnBuilder.setImage( UIHelper.getImage( "icons/obj16/expressionbuilder.gif" ) ); //$NON-NLS-1$
btnBuilder.addSelectionListener( this );
btnBuilder.setToolTipText( Messages.getString( "DataDefinitionComposite.Tooltip.InvokeExpressionBuilder" ) ); //$NON-NLS-1$
btnBuilder.getImage( ).setBackground( btnBuilder.getBackground( ) );
btnBuilder.setEnabled( context.getUIServiceProvider( )
.isInvokingSupported( ) );
btnBuilder.setVisible( context.getUIServiceProvider( )
.isEclipseModeSupported( ) );
}
if ( ( style & BUTTON_GROUP ) == BUTTON_GROUP )
{
btnGroup = new Button( cmpTop, SWT.PUSH );
GridData gdBTNGroup = new GridData( );
ChartUIUtil.setChartImageButtonSizeByPlatform( gdBTNGroup );
btnGroup.setLayoutData( gdBTNGroup );
btnGroup.setImage( UIHelper.getImage( "icons/obj16/group.gif" ) ); //$NON-NLS-1$
btnGroup.addSelectionListener( this );
btnGroup.setToolTipText( Messages.getString( "BaseDataDefinitionComponent.Label.EditGroupSorting" ) ); //$NON-NLS-1$
}
// Updates color setting
setColor( );
// In shared binding, only support predefined query
boolean isCubeNoMultiDimensions = ( provider.checkState( IDataServiceProvider.HAS_CUBE ) || provider.checkState( IDataServiceProvider.SHARE_CROSSTAB_QUERY ) )
&& !provider.checkState( IDataServiceProvider.MULTI_CUBE_DIMENSIONS );
if ( context.getDataServiceProvider( )
.checkState( IDataServiceProvider.PART_CHART )
|| context.getDataServiceProvider( )
.checkState( IDataServiceProvider.SHARE_QUERY ) )
{
// Sharing query with crosstab allows user to edit category and Y
// optional expression, so here doesn't disable the text field if it
// is SHARE_CROSSTAB_QUERY.
if ( txtDefinition != null
&& ( !context.getDataServiceProvider( )
.checkState( IDataServiceProvider.SHARE_CROSSTAB_QUERY ) || isSharingChart ) )
{
// allow y-optional if contains definition
if ( !ChartUIConstants.QUERY_OPTIONAL.equals( queryType )
|| !provider.checkState( IDataServiceProvider.SHARE_TABLE_QUERY )
|| getQuery( ).getDefinition( ) == null
|| getQuery( ).getDefinition( ).trim( ).length( ) == 0 )
{
txtDefinition.setEnabled( false );
}
}
btnBuilder.setEnabled( false );
if ( btnGroup != null )
{
btnGroup.setEnabled( false );
}
}
if ( cmbDefinition != null
&& ChartUIConstants.QUERY_OPTIONAL.equals( queryType )
&& isCubeNoMultiDimensions )
{
cmbDefinition.setEnabled( false );
btnBuilder.setEnabled( false );
}
setTooltipForInputControl( );
boolean isRequiredField = ( ChartUIConstants.QUERY_CATEGORY.equals( queryType ) );
if ( lblDesc != null && isRequiredField )
{
FieldAssistHelper.getInstance( ).addRequiredFieldIndicator( lblDesc );
}
return cmpTop;
}
/**
* Initialize combo text and data.
*/
private void initComboExprText( )
{
if ( isTableSharedBinding( ) )
{
initComboExprTextForSharedBinding( );
}
else
{
cmbDefinition.setText( query.getDefinition( ) );
}
}
/**
* Check if current is using table shared binding.
*
* @return
* @since 2.3
*/
private boolean isTableSharedBinding( )
{
return cmbDefinition != null
&& cmbDefinition.getData( ) != null
&& ( context.getDataServiceProvider( )
.checkState( IDataServiceProvider.SHARE_QUERY ) || context.getDataServiceProvider( )
.checkState( IDataServiceProvider.INHERIT_COLUMNS_GROUPS ) );
}
/**
* Initialize combo text and data for shared binding.
*/
private void initComboExprTextForSharedBinding( )
{
setUITextForSharedBinding( cmbDefinition, query.getDefinition( ) );
}
/**
* Returns available items in predefined query.
*
* @param predefinedQuery
* @return
*/
private String[] getContentItems( Object[] predefinedQuery )
{
if ( predefinedQuery[0] instanceof Object[] )
{
String[] items = new String[predefinedQuery.length];
for ( int i = 0; i < items.length; i++ )
{
items[i] = (String) ( (Object[]) predefinedQuery[i] )[0];
}
return items;
}
else if ( predefinedQuery[0] instanceof String )
{
String[] items = new String[predefinedQuery.length];
for ( int i = 0; i < items.length; i++ )
{
items[i] = (String) predefinedQuery[i];
}
return items;
}
return null;
}
/**
* Populate expression items for combo.
*
* @param predefinedQuery
*/
private void populateExprComboItems( Object[] predefinedQuery )
{
if ( predefinedQuery[0] instanceof Object[] )
{
String[] items = new String[predefinedQuery.length];
Object[] data = new Object[predefinedQuery.length];
for ( int i = 0; i < items.length; i++ )
{
items[i] = (String) ( (Object[]) predefinedQuery[i] )[0];
data[i] = ( (Object[]) predefinedQuery[i] )[1];
}
cmbDefinition.setItems( items );
cmbDefinition.setData( data );
}
else if ( predefinedQuery[0] instanceof String )
{
String[] items = new String[predefinedQuery.length];
for ( int i = 0; i < items.length; i++ )
{
items[i] = (String) predefinedQuery[i];
}
cmbDefinition.setItems( items );
}
}
public void selectArea( boolean selected, Object data )
{
if ( data instanceof Object[] )
{
Object[] array = (Object[]) data;
seriesdefinition = (SeriesDefinition) array[0];
query = (Query) array[1];
setUIText( getInputControl( ), query.getDefinition( ) );
DataDefinitionTextManager.getInstance( )
.addDataDefinitionText( getInputControl( ), this );
if ( fAggEditorComposite != null )
{
fAggEditorComposite.setAggregation( query, seriesdefinition );
}
}
setColor( );
}
private void setColor( )
{
if ( query != null )
{
Color cColor = ColorPalette.getInstance( )
.getColor( getDisplayExpression( ) );
if ( getInputControl( ) != null )
{
ChartUIUtil.setBackgroundColor( getInputControl( ),
true,
cColor );
}
}
}
public void dispose( )
{
if ( getInputControl( ) != null )
{
DataDefinitionTextManager.getInstance( )
.removeDataDefinitionText( getInputControl( ) );
}
super.dispose( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetSelected( SelectionEvent e )
{
if ( e.getSource( ).equals( btnBuilder ) )
{
handleBuilderAction( );
}
else if ( e.getSource( ).equals( btnGroup ) )
{
handleGroupAction( );
}
}
/**
* Handle grouping/sorting action.
*/
protected void handleGroupAction( )
{
SeriesDefinition sdBackup = seriesdefinition.copyInstance( );
GroupSortingDialog groupDialog = createGroupSortingDialog( sdBackup );
if ( groupDialog.open( ) == Window.OK )
{
if ( !sdBackup.eIsSet( DataPackage.eINSTANCE.getSeriesDefinition_Sorting( ) ) )
{
seriesdefinition.eUnset( DataPackage.eINSTANCE.getSeriesDefinition_Sorting( ) );
}
else
{
seriesdefinition.setSorting( sdBackup.getSorting( ) );
}
seriesdefinition.setSortKey( sdBackup.getSortKey( ) );
seriesdefinition.getSortKey( )
.eAdapters( )
.addAll( seriesdefinition.eAdapters( ) );
seriesdefinition.setGrouping( sdBackup.getGrouping( ) );
seriesdefinition.getGrouping( )
.eAdapters( )
.addAll( seriesdefinition.eAdapters( ) );
ChartUIUtil.checkGroupType( context, context.getModel( ) );
ChartUIUtil.checkAggregateType( context );
}
}
/**
* Handle builder dialog action.
*/
protected void handleBuilderAction( )
{
try
{
String oldExpr = getExpression( getInputControl( ) );
String sExpr = context.getUIServiceProvider( )
.invoke( IUIServiceProvider.COMMAND_EXPRESSION_DATA_BINDINGS,
oldExpr,
context.getExtendedItem( ),
sTitle );
// do not need to save query if it's not changed, or it may throw a
// SWT exception(widget disposed).
if ( !oldExpr.equals( sExpr ) )
{
boolean isSuccess = setUIText( getInputControl( ), sExpr );
updateQuery( sExpr );
if ( !isSuccess )
{
Event event = new Event( );
event.type = IChartDataSheet.EVENT_QUERY;
event.data = queryType;
context.getDataSheet( ).notifyListeners( event );
}
}
}
catch ( ChartException e1 )
{
WizardBase.displayException( e1 );
}
}
/**
* Create instance of <code>GroupSortingDialog</code> for base series or Y
* series.
*
* @param sdBackup
* @return
*/
protected GroupSortingDialog createGroupSortingDialog(
SeriesDefinition sdBackup )
{
return new BaseGroupSortingDialog( cmpTop.getShell( ),
context,
sdBackup );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
*/
public void widgetDefaultSelected( SelectionEvent e )
{
}
/*
* (non-Javadoc)
*
* @see org.eclipse.swt.events.ModifyListener#modifyText(org.eclipse.swt.events.ModifyEvent)
*/
public void modifyText( ModifyEvent e )
{
if ( e.getSource( ).equals( getInputControl( ) ) )
{
isQueryModified = true;
// Reset tooltip
setTooltipForInputControl( );
}
}
/**
* Set tooltip for input control.
*/
private void setTooltipForInputControl( )
{
getInputControl( ).setToolTipText( getTooltipForDataText( getExpression( getInputControl( ) ) ) );
}
/**
* Sets the description in the left of data text box.
*
* @param description
*/
public void setDescription( String description )
{
this.description = description;
}
public void focusGained( FocusEvent e )
{
// TODO Auto-generated method stub
}
public void focusLost( FocusEvent e )
{
// Null event is fired by Drop Listener manually
if ( e == null || e.widget.equals( getInputControl( ) ) )
{
if ( !ChartUIUtil.getText( getInputControl( ) )
.equals( query.getDefinition( ) ) )
{
saveQuery( );
}
}
}
protected void saveQuery( )
{
if ( isQueryModified )
{
updateQuery( ChartUIUtil.getText( getInputControl( ) ) );
// Refresh color from ColorPalette
setColor( );
getInputControl( ).getParent( ).layout( );
Event e = new Event( );
e.text = query.getDefinition( ) == null ? "" //$NON-NLS-1$
: query.getDefinition( );
e.data = e.text;
e.widget = getInputControl( );
e.type = 0;
fireEvent( e );
isQueryModified = false;
}
}
private String getTooltipForDataText( String queryText )
{
if ( isTableSharedBinding( ) )
{
int index = cmbDefinition.getSelectionIndex( );
if ( index >= 0 )
{
ColumnBindingInfo cbi = (ColumnBindingInfo) ( (Object[]) cmbDefinition.getData( ) )[index];
if ( cbi.getColumnType( ) == ColumnBindingInfo.GROUP_COLUMN
|| cbi.getColumnType( ) == ColumnBindingInfo.AGGREGATE_COLUMN )
{
return cbi.getTooltip( );
}
}
}
if ( queryText.trim( ).length( ) == 0 )
{
return tooltipWhenBlank;
}
return queryText;
}
public void keyPressed( KeyEvent e )
{
if ( e.keyCode == SWT.CR || e.keyCode == SWT.KEYPAD_CR )
{
saveQuery( );
}
}
public void keyReleased( KeyEvent e )
{
// TODO Auto-generated method stub
}
public void setTooltipWhenBlank( String tootipWhenBlank )
{
this.tooltipWhenBlank = tootipWhenBlank;
}
private void createAggregationItem( Composite composite )
{
SeriesDefinition baseSD = ChartUIUtil.getBaseSeriesDefinitions( context.getModel( ) )
.get( 0 );
boolean enabled = ChartUIUtil.isGroupingSupported( context )
&& ( PluginSettings.instance( ).inEclipseEnv( ) || baseSD.getGrouping( )
.isEnabled( ) );
if ( query.getGrouping( ) == null )
{
// Set default aggregate function
SeriesGrouping aggGrouping = SeriesGroupingImpl.create( );
aggGrouping.setAggregateExpression( seriesdefinition.getGrouping( )
.getAggregateExpression( ) );
query.setGrouping( aggGrouping );
}
fAggEditorComposite = new AggregateEditorComposite( composite,
seriesdefinition,
context,
enabled,
query );
}
private Control getInputControl( )
{
if ( txtDefinition != null )
{
return txtDefinition;
}
if ( cmbDefinition != null )
{
return cmbDefinition;
}
return null;
}
private String getExpression( Control control )
{
return getActualExpression( control );
}
private boolean setUIText( Control control, String expression )
{
if ( control == null || control.isDisposed( ) )
{
return false;
}
if ( control instanceof Text )
{
( (Text) control ).setText( expression );
}
else if ( control instanceof CCombo )
{
if ( isTableSharedBinding( ) )
{
setUITextForSharedBinding( (CCombo) control, expression );
}
else
{
( (CCombo) control ).setText( expression );
}
}
return true;
}
/**
* @param control
* @param expression
*/
private void setUITextForSharedBinding( CCombo control, String expression )
{
Object[] data = (Object[]) control.getData( );
if ( data == null || data.length == 0 )
{
control.setText( expression );
}
else
{
String expr = getDisplayExpressionForSharedBinding( control, expression );
control.setText( expr );
}
}
/**
* Update query by specified expression.
* <p>
* Under shared binding case, update grouping/aggregate attributes of chart
* model if the selected item is group/aggregate expression.
*/
public void updateQuery( String expression )
{
if ( getInputControl( ) instanceof CCombo )
{
String oldQuery = query.getDefinition( ) == null
? "" : query.getDefinition( ); //$NON-NLS-1$
Object checkResult = context.getDataServiceProvider( )
.checkData( queryType, expression );
if ( checkResult != null && checkResult instanceof Boolean )
{
if ( !( (Boolean) checkResult ).booleanValue( ) )
{
// Can't select expressions of one dimension to set
// on category series and Y optional at one time.
// did not show the warning since its logic is different
// from others
// ChartWizard.showException( ChartWizard.BaseDataDefCom_ID,
// Messages.getString( "BaseDataDefinitionComponent.WarningMessage.ExpressionsForbidden" ) ); //$NON-NLS-1$
setUIText( getInputControl( ), oldQuery );
return;
}
// else
// ChartWizard.removeException(
// ChartWizard.BaseDataDefCom_ID );
}
}
if ( !isTableSharedBinding( ) )
{
setQueryExpression( expression );
return;
}
updateQueryForSharedBinding( expression );
// Binding color to input control by expression and refresh color of
// preview table.
String regex = "\\Qrow[\"\\E.*\\Q\"]\\E"; //$NON-NLS-1$
if ( expression.matches( regex ) )
{
DataDefinitionTextManager.getInstance( )
.updateControlBackground( getInputControl( ), expression );
final Event e = new Event( );
e.data = BaseDataDefinitionComponent.this;
e.widget = getInputControl( );
e.type = IChartDataSheet.EVENT_QUERY;
e.detail = IChartDataSheet.DETAIL_UPDATE_COLOR;
// Use async thread to update UI to prevent control disposed
Display.getCurrent( ).asyncExec( new Runnable( ) {
public void run( )
{
context.getDataSheet( ).notifyListeners( e );
}
} );
}
else
{
getInputControl( ).setBackground( null );
}
}
/**
* Update query expression for sharing query with table.
*
* @param expression
*/
private void updateQueryForSharedBinding( String expression )
{
Object[] data = (Object[]) cmbDefinition.getData( );
if ( data != null && data.length > 0 )
{
String expr = expression;
if ( ChartUIConstants.QUERY_CATEGORY.equals( queryType )
|| ChartUIConstants.QUERY_OPTIONAL.equals( queryType ) )
{
boolean isGroupExpr = false;
for ( int i = 0; i < data.length; i++ )
{
ColumnBindingInfo chi = (ColumnBindingInfo) data[i];
int type = chi.getColumnType( );
if ( type == ColumnBindingInfo.GROUP_COLUMN )
{
String groupRegex = ChartUtil.createRegularRowExpression( chi.getName( ),
false );
String regex = ChartUtil.createRegularRowExpression( chi.getName( ),
true );
if ( expression.matches( regex ) )
{
isGroupExpr = true;
expr = expression.replaceAll( groupRegex,
chi.getExpression( ) );
break;
}
}
}
if ( ChartUIConstants.QUERY_CATEGORY.equals( queryType ) )
{
if ( isGroupExpr )
{
seriesdefinition.getGrouping( ).setEnabled( true );
}
else
{
seriesdefinition.getGrouping( ).setEnabled( false );
}
}
}
else if ( ChartUIConstants.QUERY_VALUE.equals( queryType ) )
{
boolean isAggregationExpr = false;
ColumnBindingInfo chi = null;
for ( int i = 0; i < data.length; i++ )
{
chi = (ColumnBindingInfo) data[i];
int type = chi.getColumnType( );
if ( type == ColumnBindingInfo.AGGREGATE_COLUMN )
{
String aggRegex = ChartUtil.createRegularRowExpression( chi.getName( ),
false );
String regex = ChartUtil.createRegularRowExpression( chi.getName( ),
true );
if ( expression.matches( regex ) )
{
isAggregationExpr = true;
expr = expression.replaceAll( aggRegex,
chi.getExpression( ) );
break;
}
}
}
if ( isAggregationExpr )
{
query.getGrouping( ).setEnabled( true );
query.getGrouping( )
.setAggregateExpression( chi.getChartAggExpression( ) );
}
else
{
query.getGrouping( ).setEnabled( false );
query.getGrouping( ).setAggregateExpression( null );
}
}
setQueryExpression( expr );
}
else
{
setQueryExpression( expression );
}
}
private void setQueryExpression( String expression )
{
if ( query != null )
{
query.setDefinition( expression );
}
else
{
query = QueryImpl.create( expression );
query.eAdapters( ).addAll( seriesdefinition.eAdapters( ) );
// Since the data query must be non-null, it's created in
// ChartUIUtil.getDataQuery(), assume current null is a grouping
// query
seriesdefinition.setQuery( query );
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.ui.swt.IQueryExpressionManager#getQuery()
*/
public Query getQuery( )
{
if ( query == null )
{
query = QueryImpl.create( getExpression( getInputControl( ) ) );
query.eAdapters( ).addAll( seriesdefinition.eAdapters( ) );
// Since the data query must be non-null, it's created in
// ChartUIUtil.getDataQuery(), assume current null is a grouping
// query
seriesdefinition.setQuery( query );
}
return query;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.ui.swt.IQueryExpressionManager#getDisplayExpression()
*/
public String getDisplayExpression( )
{
if ( cmbDefinition != null && isTableSharedBinding( ) )
{
return getDisplayExpressionForSharedBinding( cmbDefinition, query.getDefinition( ) );
}
else
{
String expr = query.getDefinition( );
return ( expr == null ) ? "" : expr; //$NON-NLS-1$
}
}
private String getDisplayExpressionForSharedBinding( CCombo combo, String expression )
{
String expr = expression;
Object[] data = (Object[]) combo.getData( );
for ( int i = 0; data != null && i < data.length; i++ )
{
ColumnBindingInfo chi = (ColumnBindingInfo) data[i];
if ( chi.getExpression( ) == null )
{
continue;
}
String columnExpr = null;
try
{
List bindings = ExpressionUtil.extractColumnExpressions( chi.getExpression( ) );
if ( bindings.isEmpty( ) )
{
continue;
}
columnExpr = ( (IColumnBinding) bindings.get( 0 ) ).getResultSetColumnName( );
}
catch ( BirtException e )
{
continue;
}
String columnRegex = ChartUtil.createRegularRowExpression( columnExpr,
false );
String regex = ChartUtil.createRegularRowExpression( columnExpr,
true );
if ( expression != null && expression.matches( regex ) )
{
if ( queryType == ChartUIConstants.QUERY_CATEGORY )
{
boolean sdGrouped = seriesdefinition.getGrouping( )
.isEnabled( );
boolean groupedBinding = ( chi.getColumnType( ) == ColumnBindingInfo.GROUP_COLUMN );
if ( sdGrouped && groupedBinding )
{
expr = expression.replaceAll( columnRegex,
ExpressionUtil.createJSRowExpression( chi.getName( ) ) );
break;
}
}
else if ( queryType == ChartUIConstants.QUERY_OPTIONAL )
{
expr = expression.replaceAll( columnRegex,
ExpressionUtil.createJSRowExpression( chi.getName( ) ) );
break;
}
}
}
return ( expr == null ) ? "" : expr; //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see org.eclipse.birt.chart.ui.swt.IQueryExpressionManager#isValidExpression(java.lang.String)
*/
public boolean isValidExpression( String expression )
{
if ( context.getDataServiceProvider( )
.checkState( IDataServiceProvider.SHARE_QUERY ) )
{
if ( cmbDefinition == null )
return false;
int index = cmbDefinition.indexOf( expression );
if ( index < 0 )
{
return false;
}
return true;
}
return true;
}
/**
* The method is used to get actual expression from input control.For shared
* binding case, the expression is stored in data field of combo widget.
*
* @param control
* @return
* @since 2.3
*/
private String getActualExpression( Control control )
{
if ( control instanceof Text )
{
return ( (Text) control ).getText( );
}
if ( control instanceof CCombo )
{
Object[] data = (Object[]) control.getData( );
if ( data != null
&& data.length > 0
&& data[0] instanceof ColumnBindingInfo )
{
String txt = ( (CCombo) control ).getText( );
String[] items = ( (CCombo) control ).getItems( );
int index = 0;
for ( ; items != null
&& items.length > 0
&& index < items.length; index++ )
{
if ( items[index].equals( txt ) )
{
break;
}
}
if ( items != null && index >= 0 && index < items.length )
{
return ( (ColumnBindingInfo) data[index] ).getExpression( );
}
}
return ( (CCombo) control ).getText( );
}
return ""; //$NON-NLS-1$
}
} |
package io.cattle.platform.docker.process.instance;
import io.cattle.platform.core.constants.InstanceConstants;
import io.cattle.platform.core.model.Image;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.core.model.Network;
import io.cattle.platform.core.util.SystemLabels;
import io.cattle.platform.docker.constants.DockerInstanceConstants;
import io.cattle.platform.docker.storage.dao.DockerStorageDao;
import io.cattle.platform.engine.handler.HandlerResult;
import io.cattle.platform.engine.handler.ProcessPreListener;
import io.cattle.platform.engine.process.ProcessInstance;
import io.cattle.platform.engine.process.ProcessState;
import io.cattle.platform.network.NetworkService;
import io.cattle.platform.object.ObjectManager;
import io.cattle.platform.object.util.DataAccessor;
import io.cattle.platform.object.util.DataUtils;
import io.cattle.platform.process.common.handler.AbstractObjectProcessLogic;
import io.cattle.platform.util.exception.ExecutionException;
import io.cattle.platform.util.type.Priority;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import org.apache.commons.lang3.StringUtils;
public class DockerInstancePreCreate extends AbstractObjectProcessLogic implements ProcessPreListener, Priority {
@Inject
ObjectManager objectManager;
@Inject
DockerStorageDao dockerStorageDao;
@Inject
NetworkService networkService;
@Override
public String[] getProcessNames() {
return new String[]{"instance.create"};
}
@Override
public HandlerResult handle(ProcessState state, ProcessInstance process) {
Instance instance = (Instance)state.getResource();
if (!InstanceConstants.CONTAINER_LIKE.contains(instance.getKind())) {
return null;
}
Image image = objectManager.loadResource(Image.class, instance.getImageId());
if (image == null) {
dockerStorageDao.createImageForInstance(instance);
}
Map<Object, Object> data = new HashMap<>();
String mode = networkService.getNetworkMode(DataUtils.getFields(instance));
data.put(DockerInstanceConstants.FIELD_NETWORK_MODE, mode);
Network network = networkService.resolveNetwork(instance.getAccountId(), mode);
if (network == null && StringUtils.isNotBlank(mode) && !instance.getNativeContainer()) {
objectProcessManager.scheduleProcessInstance(InstanceConstants.PROCESS_REMOVE, instance, null);
throw new ExecutionException(String.format("Failed to find network for networkMode %s", mode),
null, state.getResource());
}
if (network != null) {
data.put(InstanceConstants.FIELD_NETWORK_IDS, Arrays.asList(network.getId()));
}
Map<String, Object> labels = DataAccessor.fieldMap(instance, InstanceConstants.FIELD_LABELS);
Object ip = labels.get(SystemLabels.LABEL_REQUESTED_IP);
if (ip != null) {
data.put(InstanceConstants.FIELD_REQUESTED_IP_ADDRESS, ip.toString());
}
return new HandlerResult(data).withShouldContinue(true);
}
@Override
public int getPriority() {
return Priority.PRE - 1;
}
} |
package com.github.dandelion.datatables.core.generator.configuration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.dandelion.core.utils.StringUtils;
import com.github.dandelion.datatables.core.asset.JavascriptSnippet;
import com.github.dandelion.datatables.core.configuration.ColumnConfig;
import com.github.dandelion.datatables.core.configuration.ColumnConfiguration;
import com.github.dandelion.datatables.core.configuration.TableConfig;
import com.github.dandelion.datatables.core.constants.DTConstants;
import com.github.dandelion.datatables.core.export.Format;
import com.github.dandelion.datatables.core.extension.feature.FilterPlaceholder;
import com.github.dandelion.datatables.core.extension.feature.FilterType;
import com.github.dandelion.datatables.core.html.HtmlColumn;
import com.github.dandelion.datatables.core.html.HtmlTable;
import com.github.dandelion.datatables.core.util.CollectionUtils;
/**
* <p>
* Class in charge of Column Filtering widget configuration generation.
*
* @author Thibault Duchateau
*/
public class ColumnFilteringGenerator extends AbstractConfigurationGenerator {
// Logger
private static Logger logger = LoggerFactory.getLogger(ColumnFilteringGenerator.class);
public Map<String, Object> generateConfig(HtmlTable table) {
logger.debug("Generating Column Filtering configuration...");
// Filtering configuration object
Map<String, Object> filteringConf = new HashMap<String, Object>();
FilterPlaceholder filterPlaceholder = TableConfig.FEATURE_FILTER_PLACEHOLDER.valueFrom(table);
if(filterPlaceholder != null){
filteringConf.put(DTConstants.DT_S_PLACEHOLDER, filterPlaceholder.getName());
}
// Columns configuration
Map<String, Object> tmp = null;
List<Map<String, Object>> aoColumnsContent = new ArrayList<Map<String, Object>>();
for (HtmlColumn column : table.getLastHeaderRow().getColumns()) {
Set<String> enabledDisplayTypes = column.getEnabledDisplayTypes();
if (CollectionUtils.containsAny(enabledDisplayTypes, Format.ALL, Format.HTML)) {
tmp = new HashMap<String, Object>();
ColumnConfiguration columnConfiguration = column.getColumnConfiguration();
Boolean filterable = ColumnConfig.FILTERABLE.valueFrom(columnConfiguration);
FilterType filterType = ColumnConfig.FILTERTYPE.valueFrom(columnConfiguration);
if (filterable != null && filterable && filterType != null) {
switch(filterType){
case INPUT:
tmp.put(DTConstants.DT_FILTER_TYPE, "text");
break;
case NUMBER:
tmp.put(DTConstants.DT_FILTER_TYPE, "number");
break;
case SELECT:
tmp.put(DTConstants.DT_FILTER_TYPE, "select");
break;
case NUMBER_RANGE:
tmp.put(DTConstants.DT_FILTER_TYPE, "number-range");
break;
}
}
else{
tmp.put(DTConstants.DT_FILTER_TYPE, "null");
}
String selector = ColumnConfig.SELECTOR.valueFrom(columnConfiguration);
if(StringUtils.isNotBlank(selector)){
tmp.put(DTConstants.DT_S_SELECTOR, selector);
}
String filterValues = ColumnConfig.FILTERVALUES.valueFrom(columnConfiguration);
if(StringUtils.isNotBlank(filterValues)){
tmp.put(DTConstants.DT_FILTER_VALUES, new JavascriptSnippet(filterValues));
}
Integer filterLength = ColumnConfig.FILTERLENGTH.valueFrom(columnConfiguration);
if(filterLength != null){
tmp.put(DTConstants.DT_FILTER_LENGTH, filterLength);
}
aoColumnsContent.add(tmp);
}
}
filteringConf.put(DTConstants.DT_AOCOLUMNS, aoColumnsContent);
logger.debug("Column filtering configuration generated");
return filteringConf;
}
} |
package org.deeplearning4j.models.embeddings.inmemory;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import org.apache.commons.lang.math.RandomUtils;
import org.deeplearning4j.models.abstractvectors.sequence.SequenceElement;
import org.deeplearning4j.models.embeddings.WeightLookupTable;
import org.deeplearning4j.models.word2vec.VocabWord;
import org.deeplearning4j.models.word2vec.wordstore.VocabCache;
import org.deeplearning4j.plot.Tsne;
import org.nd4j.linalg.api.ndarray.INDArray;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
/**
* This is going to be primitive implementation of joint WeightLookupTable, used for ParagraphVectors and Word2Vec joint training.
*
* Main idea of this implementation nr.1: in some cases you have to train corpus for 2 vocabs instead of 1. Or you need to extend vocab,
* and you can use few separate instead of rebuilding one big WeightLookupTable which can double used memory.
*
*
* WORK IS IN PROGRESS, PLEASE DO NOT USE
*
* @author raver119@gmail.com
*/
public class JointStorage<T extends SequenceElement> implements WeightLookupTable<T>, VocabCache<T> {
private Map<Long, WeightLookupTable<T>> mapTables = new ConcurrentHashMap<>();
private Map<Long, VocabCache<T>> mapVocabs = new ConcurrentHashMap<>();
private int layerSize;
@Getter @Setter protected Long tableId;
@Override
public void loadVocab() {
}
@Override
public boolean vocabExists() {
return false;
}
@Override
public void saveVocab() {
}
@Override
public Collection<String> words() {
return null;
}
@Override
public void incrementWordCount(String word) {
}
@Override
public void incrementWordCount(String word, int increment) {
}
@Override
public int wordFrequency(String word) {
return 0;
}
@Override
public boolean containsWord(String word) {
return false;
}
@Override
public String wordAtIndex(int index) {
return null;
}
@Override
public T elementAtIndex(int index) {
return null;
}
@Override
public int indexOf(String word) {
return 0;
}
/**
* Returns all SequenceElements in this JointStorage instance.
* Please note, if used in distributed environment this can cause OOM exceptions. Use with caution, or use iterator instead
*
* @return Collection of all VocabWords in this JointStorage
*/
@Override
public Collection<T> vocabWords() {
ArrayList<T> words = new ArrayList<>();
for (VocabCache cache: mapVocabs.values()) {
words.addAll(cache.vocabWords());
}
return Collections.unmodifiableCollection(words);
}
@Override
public long totalWordOccurrences() {
return 0;
}
@Override
public T wordFor(String word) {
return null;
}
@Override
public void addWordToIndex(int index, String word) {
}
@Override
public void putVocabWord(String word) {
}
/**
* Returns number of words in all underlying vocabularies
*
* @return
*/
@Override
public int numWords() {
// TODO: this should return Long in future, since joint storage mechanics should allow really huge vocabularies and maps
AtomicLong counter = new AtomicLong(0);
for (VocabCache cache: mapVocabs.values()) {
counter.addAndGet(cache.numWords());
}
return counter.intValue();
}
@Override
public int docAppearedIn(String word) {
return 0;
}
@Override
public void incrementDocCount(String word, int howMuch) {
}
@Override
public void setCountForDoc(String word, int count) {
}
@Override
public int totalNumberOfDocs() {
return 0;
}
@Override
public void incrementTotalDocCount() {
}
@Override
public void incrementTotalDocCount(int by) {
}
@Override
public Collection<T> tokens() {
return null;
}
@Override
public void addToken(SequenceElement word) {
}
@Override
public T tokenFor(String word) {
return null;
}
@Override
public boolean hasToken(String token) {
return false;
}
@Override
public void importVocabulary(VocabCache<T> vocabCache) {
}
@Override
public void updateWordsOccurencies() {
}
@Override
public void removeElement(String label) {
}
@Override
public void removeElement(T element) {
}
@Override
public int layerSize() {
return this.layerSize;
}
@Override
public void resetWeights(boolean reset) {
}
@Override
public void plotVocab(Tsne tsne) {
}
@Override
public void plotVocab() {
}
@Override
public void putCode(int codeIndex, INDArray code) {
}
@Override
public INDArray loadCodes(int[] codes) {
return null;
}
@Override
public void iterate(T w1, T w2) {
}
@Override
public void iterateSample(T w1, T w2, AtomicLong nextRandom, double alpha) {
}
@Override
public void putVector(String word, INDArray vector) {
}
@Override
public INDArray vector(String word) {
return null;
}
@Override
public void resetWeights() {
}
@Override
public void setLearningRate(double lr) {
}
@Override
public Iterator<INDArray> vectors() {
return null;
}
@Override
public INDArray getWeights() {
return null;
}
@Override
public int getVectorLength() {
return 0;
}
public static class Builder<T extends SequenceElement> {
private Map<Long, WeightLookupTable<T>> mapTables = new ConcurrentHashMap<>();
private Map<Long, VocabCache<T>> mapVocabs = new ConcurrentHashMap<>();
private int layerSize;
public Builder() {
}
/**
* Adds InMemoryLookupTable into JointStorage, VocabCache will be fetched from table
*
* @param lookupTable InMemoryLookupTable that's going to be part of Joint Lookup Table
* @return
*/
public Builder addLookupPair(@NonNull InMemoryLookupTable<T> lookupTable) {
return addLookupPair(lookupTable, lookupTable.getVocab());
}
/**
* Adds WeightLookupTable into JointStorage
*
* @param lookupTable WeightLookupTable that's going to be part of Joint Lookup Table
* @param cache VocabCache that contains vocabulary for lookupTable
* @return
*/
public Builder addLookupPair(@NonNull WeightLookupTable<T> lookupTable, @NonNull VocabCache<T> cache) {
/*
we should assume, that each word in VocabCache is tagged with pair Vocab/Table ID
*/
if (lookupTable.getTableId() == null || lookupTable.getTableId().longValue() == 0)
lookupTable.setTableId(RandomUtils.nextLong());
for (T word: cache.vocabWords()) {
// each word should be tagged here
word.setStorageId(lookupTable.getTableId());
}
mapTables.put(lookupTable.getTableId(), lookupTable);
mapVocabs.put(lookupTable.getTableId(), cache);
return this;
}
public Builder layerSize(int layerSize) {
this.layerSize = layerSize;
return this;
}
public JointStorage build() {
JointStorage<T> lookupTable = new JointStorage();
lookupTable.mapTables = this.mapTables;
lookupTable.mapVocabs = this.mapVocabs;
lookupTable.layerSize = this.layerSize;
return lookupTable;
}
}
} |
package org.drools.runtime.pipeline.impl;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.custommonkey.xmlunit.XMLTestCase;
import org.drools.Cheese;
import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.TestVariable;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.definition.KnowledgePackage;
import org.drools.io.Resource;
import org.drools.io.ResourceFactory;
import org.drools.runtime.BatchExecutionResults;
import org.drools.runtime.StatelessKnowledgeSession;
import org.drools.runtime.StatefulKnowledgeSession;
import org.drools.runtime.help.BatchExecutionHelper;
import org.drools.runtime.pipeline.Action;
import org.drools.runtime.pipeline.KnowledgeRuntimeCommand;
import org.drools.runtime.pipeline.Pipeline;
import org.drools.runtime.pipeline.PipelineFactory;
import org.drools.runtime.pipeline.ResultHandler;
import org.drools.runtime.pipeline.Transformer;
import org.xml.sax.SAXException;
public class XStreamBatchExecutionTest extends XMLTestCase {
public void testInsertObject() throws Exception {
String str = "";
str += "package org.drools \n";
str += "import org.drools.Cheese \n";
str += "rule rule1 \n";
str += " when \n";
str += " $c : Cheese() \n";
str += " \n";
str += " then \n";
str += " $c.setPrice( $c.getPrice() + 5 ); \n";
str += "end\n";
String inXml = "";
inXml += "<batch-execution>";
inXml += " <insert out-identifier='outStilton'>";
inXml += " <org.drools.Cheese>";
inXml += " <type>stilton</type>";
inXml += " <price>25</price>";
inXml += " <oldPrice>0</oldPrice>";
inXml += " </org.drools.Cheese>";
inXml += " </insert>";
inXml += "</batch-execution>";
StatelessKnowledgeSession ksession = getSession2( ResourceFactory.newByteArrayResource( str.getBytes() ) );
ResultHandlerImpl resultHandler = new ResultHandlerImpl();
getPipeline(ksession).insert( inXml, resultHandler );
String outXml = ( String ) resultHandler.getObject();
String expectedXml = "";
expectedXml += "<batch-execution-results>\n";
expectedXml += " <result identifier=\"outStilton\">\n";
expectedXml += " <org.drools.Cheese>\n";
expectedXml += " <type>stilton</type>\n";
expectedXml += " <oldPrice>0</oldPrice>\n";
expectedXml += " <price>30</price>\n";
expectedXml += " </org.drools.Cheese>\n";
expectedXml += " </result>\n";
expectedXml += "</batch-execution-results>\n";
assertXMLEqual(expectedXml, outXml );
BatchExecutionResults result = ( BatchExecutionResults ) BatchExecutionHelper.newXStreamMarshaller().fromXML( outXml );
Cheese stilton = ( Cheese ) result.getValue( "outStilton" );
assertEquals( 30,
stilton.getPrice() );
}
public void testInsertElements() throws Exception {
String str = "";
str += "package org.drools \n";
str += "import org.drools.Cheese \n";
str += "global java.util.List list \n";
str += "rule rule1 \n";
str += " when \n";
str += " $c : Cheese() \n";
str += " \n";
str += " then \n";
str += " $c.setPrice( $c.getPrice() + 5 ); \n";
str += " list.add( $c );";
str += "end\n";
String inXml = "";
inXml += "<batch-execution>";
inXml += " <set-global identifier='list' out='true'>";
inXml += " <list/>";
inXml += " </set-global>";
inXml += " <insert-elements>";
inXml += " <org.drools.Cheese>";
inXml += " <type>stilton</type>";
inXml += " <price>25</price>";
inXml += " <oldPrice>0</oldPrice>";
inXml += " </org.drools.Cheese>";
inXml += " <org.drools.Cheese>";
inXml += " <type>stilton</type>";
inXml += " <price>30</price>";
inXml += " <oldPrice>0</oldPrice>";
inXml += " </org.drools.Cheese>";
inXml += " </insert-elements>";
inXml += "</batch-execution>";
StatelessKnowledgeSession ksession = getSession2( ResourceFactory.newByteArrayResource( str.getBytes() ) );
ResultHandlerImpl resultHandler = new ResultHandlerImpl();
getPipeline(ksession).insert( inXml, resultHandler );
String outXml = ( String ) resultHandler.getObject();
String expectedXml = "";
expectedXml += "<batch-execution-results>\n";
expectedXml += " <result identifier='list'>\n";
expectedXml += " <list>\n";
expectedXml += " <org.drools.Cheese>\n";
expectedXml += " <type>stilton</type>\n";
expectedXml += " <price>35</price>\n";
expectedXml += " <oldPrice>0</oldPrice>\n";
expectedXml += " </org.drools.Cheese>\n";
expectedXml += " <org.drools.Cheese>\n";
expectedXml += " <type>stilton</type>\n";
expectedXml += " <price>30</price>\n";
expectedXml += " <oldPrice>0</oldPrice>\n";
expectedXml += " </org.drools.Cheese>\n";
expectedXml += " </list>\n";
expectedXml += " </result>\n";
expectedXml += "</batch-execution-results>\n";
assertXMLEqual( expectedXml, outXml );
BatchExecutionResults result = ( BatchExecutionResults ) BatchExecutionHelper.newXStreamMarshaller().fromXML( outXml );
List list = ( List ) result.getValue( "list" );
Cheese stilton25 = new Cheese( "stilton", 30);
Cheese stilton30 = new Cheese( "stilton", 35);
Set expectedList = new HashSet();
expectedList.add( stilton25 );
expectedList.add( stilton30 );
assertEquals( expectedList, new HashSet( list ));
}
public void testSetGlobal() throws Exception {
String str = "";
str += "package org.drools \n";
str += "import org.drools.Cheese \n";
str += "global java.util.List list1 \n";
str += "global java.util.List list2 \n";
str += "global java.util.List list3 \n";
str += "rule rule1 \n";
str += " when \n";
str += " $c : Cheese() \n";
str += " \n";
str += " then \n";
str += " $c.setPrice( 30 ); \n";
str += " list1.add( $c ); \n";
str += " list2.add( $c ); \n";
str += " list3.add( $c ); \n";
str += "end\n";
String inXml = "";
inXml += "<batch-execution>";
inXml += " <set-global identifier='list1'>";
inXml += " <list/>";
inXml += " </set-global>";
inXml += " <set-global identifier='list2' out='true'>";
inXml += " <list/>";
inXml += " </set-global>";
inXml += " <set-global identifier='list3' out-identifier='outList3'>";
inXml += " <list/>";
inXml += " </set-global>";
inXml += " <insert>";
inXml += " <org.drools.Cheese>";
inXml += " <type>stilton</type>";
inXml += " <price>5</price>";
inXml += " <oldPrice>0</oldPrice>";
inXml += " </org.drools.Cheese>";
inXml += " </insert>";
inXml += "</batch-execution>";
StatelessKnowledgeSession ksession = getSession2( ResourceFactory.newByteArrayResource( str.getBytes() ) );
ResultHandlerImpl resultHandler = new ResultHandlerImpl();
getPipeline(ksession).insert( inXml, resultHandler );
String outXml = ( String ) resultHandler.getObject();
String expectedXml = "";
expectedXml += "<batch-execution-results>\n";
expectedXml += " <result identifier='list2'>\n";
expectedXml += " <list>\n";
expectedXml += " <org.drools.Cheese>\n";
expectedXml += " <type>stilton</type>\n";
expectedXml += " <price>30</price>\n";
expectedXml += " <oldPrice>0</oldPrice>\n";
expectedXml += " </org.drools.Cheese>\n";
expectedXml += " </list>\n";
expectedXml += " </result>\n";
expectedXml += " <result identifier='outList3'>\n";
expectedXml += " <list>\n";
expectedXml += " <org.drools.Cheese reference='../../../result/list/org.drools.Cheese'/>\n";
expectedXml += " </list>\n";
expectedXml += " </result>\n";
expectedXml += "</batch-execution-results>\n";
assertXMLEqual(expectedXml, outXml );
BatchExecutionResults result = ( BatchExecutionResults ) BatchExecutionHelper.newXStreamMarshaller().fromXML( outXml );
Cheese stilton = new Cheese( "stilton", 30 );
assertNull( result.getValue( "list1" ) );
List list2 = ( List ) result.getValue( "list2" );
assertEquals( 1, list2.size() );
assertEquals( stilton, list2.get( 0 ) );
List list3 = ( List ) result.getValue( "outList3" );
assertEquals( 1, list3.size() );
assertEquals( stilton, list3.get( 0 ) );
}
public void testGetGlobal() throws Exception {
String str = "";
str += "package org.drools \n";
str += "import org.drools.Cheese \n";
str += "global java.util.List list \n";
str += "rule rule1 \n";
str += " when \n";
str += " $c : Cheese() \n";
str += " \n";
str += " then \n";
str += " list.add( $c ); \n";
str += "end\n";
String inXml = "";
inXml += "<batch-execution>";
inXml += " <set-global identifier='list'>";
inXml += " <list/>";
inXml += " </set-global>";
inXml += " <insert>";
inXml += " <org.drools.Cheese>";
inXml += " <type>stilton</type>";
inXml += " <price>25</price>";
inXml += " <oldPrice>0</oldPrice>";
inXml += " </org.drools.Cheese>";
inXml += " </insert>";
inXml += " <get-global identifier='list' out-identifier='out-list'/>";
inXml += "</batch-execution>";
StatelessKnowledgeSession ksession = getSession2( ResourceFactory.newByteArrayResource( str.getBytes() ) );
ResultHandlerImpl resultHandler = new ResultHandlerImpl();
getPipeline(ksession).insert( inXml, resultHandler );
String outXml = ( String ) resultHandler.getObject();
String expectedXml = "";
expectedXml += "<batch-execution-results>\n";
expectedXml += " <result identifier=\"out-list\">\n";
expectedXml += " <list>\n";
expectedXml += " <org.drools.Cheese>\n";
expectedXml += " <type>stilton</type>\n";
expectedXml += " <price>25</price>\n";
expectedXml += " <oldPrice>0</oldPrice>\n";
expectedXml += " </org.drools.Cheese>\n";
expectedXml += " </list>\n";
expectedXml += " </result>\n";
expectedXml += "</batch-execution-results>\n";
assertXMLEqual(expectedXml, outXml );
}
public void testGetObjects() throws Exception {
String str = "";
str += "package org.drools \n";
str += "import org.drools.Cheese \n";
str += "rule rule1 \n";
str += " when \n";
str += " $c : Cheese() \n";
str += " \n";
str += " then \n";
str += " $c.setPrice( $c.getPrice() + 5 ); \n";
str += "end\n";
String inXml = "";
inXml += "<batch-execution>";
inXml += " <insert-elements>";
inXml += " <org.drools.Cheese>";
inXml += " <type>stilton</type>";
inXml += " <price>25</price>";
inXml += " <oldPrice>0</oldPrice>";
inXml += " </org.drools.Cheese>";
inXml += " <org.drools.Cheese>";
inXml += " <type>stilton</type>";
inXml += " <price>30</price>";
inXml += " <oldPrice>0</oldPrice>";
inXml += " </org.drools.Cheese>";
inXml += " </insert-elements>";
inXml += " <get-objects out-identifier='list' />";
inXml += "</batch-execution>";
StatelessKnowledgeSession ksession = getSession2( ResourceFactory.newByteArrayResource( str.getBytes() ) );
ResultHandlerImpl resultHandler = new ResultHandlerImpl();
getPipeline(ksession).insert( inXml, resultHandler );
String outXml = ( String ) resultHandler.getObject();
String expectedXml = "";
expectedXml += "<batch-execution-results>\n";
expectedXml += " <result identifier='list'>\n";
expectedXml += " <list>\n";
expectedXml += " <org.drools.Cheese>\n";
expectedXml += " <type>stilton</type>\n";
expectedXml += " <price>30</price>\n";
expectedXml += " <oldPrice>0</oldPrice>\n";
expectedXml += " </org.drools.Cheese>\n";
expectedXml += " <org.drools.Cheese>\n";
expectedXml += " <type>stilton</type>\n";
expectedXml += " <price>35</price>\n";
expectedXml += " <oldPrice>0</oldPrice>\n";
expectedXml += " </org.drools.Cheese>\n";
expectedXml += " </list>\n";
expectedXml += " </result>\n";
expectedXml += "</batch-execution-results>\n";
assertXMLEqual( expectedXml, outXml );
BatchExecutionResults result = ( BatchExecutionResults ) BatchExecutionHelper.newXStreamMarshaller().fromXML( outXml );
List list = ( List ) result.getValue( "list" );
Cheese stilton25 = new Cheese( "stilton", 30);
Cheese stilton30 = new Cheese( "stilton", 35);
Set expectedList = new HashSet();
expectedList.add( stilton25 );
expectedList.add( stilton30 );
assertEquals( expectedList, new HashSet( list ));
}
public void testQuery() throws Exception {
String str = "";
str += "package org.drools.test \n";
str += "import org.drools.Cheese \n";
str += "query cheeses \n";
str += " stilton : Cheese(type == 'stilton') \n";
str += " cheddar : Cheese(type == 'cheddar', price == stilton.price) \n";
str += "end\n";
str += "query cheesesWithParams(String a, String b) \n";
str += " stilton : Cheese(type == a) \n";
str += " cheddar : Cheese(type == b, price == stilton.price) \n";
str += "end\n";
String inXml = "";
inXml += "<batch-execution>";
inXml += " <insert>";
inXml += " <org.drools.Cheese>";
inXml += " <type>stilton</type>";
inXml += " <price>1</price>";
inXml += " <oldPrice>0</oldPrice>";
inXml += " </org.drools.Cheese>";
inXml += " </insert>";
inXml += " <insert>";
inXml += " <org.drools.Cheese>";
inXml += " <type>stilton</type>";
inXml += " <price>2</price>";
inXml += " <oldPrice>0</oldPrice>";
inXml += " </org.drools.Cheese>";
inXml += " </insert>";
inXml += " <insert>";
inXml += " <org.drools.Cheese>";
inXml += " <type>cheddar</type>";
inXml += " <price>1</price>";
inXml += " <oldPrice>0</oldPrice>";
inXml += " </org.drools.Cheese>";
inXml += " </insert>";
inXml += " <insert>";
inXml += " <org.drools.Cheese>";
inXml += " <type>cheddar</type>";
inXml += " <price>2</price>";
inXml += " <oldPrice>0</oldPrice>";
inXml += " </org.drools.Cheese>";
inXml += " </insert>";
inXml += " <query out-identifier='cheeses' name='cheeses'/>";
inXml += " <query out-identifier='cheeses2' name='cheesesWithParams'>";
inXml += " <string>stilton</string>";
inXml += " <string>cheddar</string>";
inXml += " </query>";
inXml += "</batch-execution>";
StatelessKnowledgeSession ksession = getSession2( ResourceFactory.newByteArrayResource( str.getBytes() ) );
ResultHandlerImpl resultHandler = new ResultHandlerImpl();
getPipeline(ksession).insert( inXml, resultHandler );
String outXml = ( String ) resultHandler.getObject();
String expectedXml = "";
expectedXml +="<batch-execution-results>\n";
expectedXml +=" <result identifier='cheeses'>\n";
expectedXml +=" <query-results>\n";
expectedXml +=" <identifiers>\n";
expectedXml +=" <identifier>stilton</identifier>\n";
expectedXml +=" <identifier>cheddar</identifier>\n";
expectedXml +=" </identifiers>\n";
expectedXml +=" <row>\n";
expectedXml +=" <org.drools.Cheese>\n";
expectedXml +=" <type>stilton</type>\n";
expectedXml +=" <price>2</price>\n";
expectedXml +=" <oldPrice>0</oldPrice>\n";
expectedXml +=" </org.drools.Cheese>\n";
expectedXml +=" <org.drools.Cheese>\n";
expectedXml +=" <type>cheddar</type>\n";
expectedXml +=" <price>2</price>\n";
expectedXml +=" <oldPrice>0</oldPrice>\n";
expectedXml +=" </org.drools.Cheese>\n";
expectedXml +=" </row>\n";
expectedXml +=" <row>\n";
expectedXml +=" <org.drools.Cheese>\n";
expectedXml +=" <type>stilton</type>\n";
expectedXml +=" <price>1</price>\n";
expectedXml +=" <oldPrice>0</oldPrice>\n";
expectedXml +=" </org.drools.Cheese>\n";
expectedXml +=" <org.drools.Cheese>\n";
expectedXml +=" <type>cheddar</type>\n";
expectedXml +=" <price>1</price>\n";
expectedXml +=" <oldPrice>0</oldPrice>\n";
expectedXml +=" </org.drools.Cheese>\n";
expectedXml +=" </row>\n";
expectedXml +=" </query-results>\n";
expectedXml +=" </result>\n";
expectedXml +=" <result identifier='cheeses2'>\n";
expectedXml +=" <query-results>\n";
expectedXml +=" <identifiers>\n";
expectedXml +=" <identifier>stilton</identifier>\n";
expectedXml +=" <identifier>cheddar</identifier>\n";
expectedXml +=" </identifiers>\n";
expectedXml +=" <row>\n";
expectedXml +=" <org.drools.Cheese reference=\"../../../../result/query-results/row/org.drools.Cheese\"/>\n";
expectedXml +=" <org.drools.Cheese reference=\"../../../../result/query-results/row/org.drools.Cheese[2]\"/>\n";
expectedXml +=" </row>\n";
expectedXml +=" <row>\n";
expectedXml +=" <org.drools.Cheese reference=\"../../../../result/query-results/row[2]/org.drools.Cheese\"/>\n";
expectedXml +=" <org.drools.Cheese reference=\"../../../../result/query-results/row[2]/org.drools.Cheese[2]\"/>\n";
expectedXml +=" </row>\n";
expectedXml +=" </query-results>\n";
expectedXml +=" </result>\n";
expectedXml +="</batch-execution-results>\n";;
assertXMLEqual(expectedXml, outXml );
BatchExecutionResults batchResult = ( BatchExecutionResults ) BatchExecutionHelper.newXStreamMarshaller().fromXML( outXml );
Cheese stilton1 = new Cheese( "stilton", 1);
Cheese cheddar1 = new Cheese( "cheddar", 1);
Cheese stilton2 = new Cheese( "stilton", 2);
Cheese cheddar2 = new Cheese( "cheddar", 2);
Set set = new HashSet();
List list = new ArrayList();
list.add(stilton1);
list.add(cheddar1);
set.add( list );
list = new ArrayList();
list.add(stilton2);
list.add(cheddar2);
set.add( list );
org.drools.runtime.rule.QueryResults results = ( org.drools.runtime.rule.QueryResults) batchResult.getValue( "cheeses" );
assertEquals( 2, results.size() );
assertEquals( 2, results.getIdentifiers().length );
Set newSet = new HashSet();
for ( org.drools.runtime.rule.QueryResultsRow result : results ) {
list = new ArrayList();
list.add( result.get( "stilton" ) );
list.add( result.get( "cheddar" ));
newSet.add( list );
}
assertEquals( set, newSet );
}
public void testManualFireAllRules() throws Exception {
String str = "";
str += "package org.drools \n";
str += "import org.drools.Cheese \n";
str += "global java.util.List list \n";
str += "rule rule1 \n";
str += " when \n";
str += " $c : Cheese() \n";
str += " \n";
str += " then \n";
str += " $c.setPrice( $c.getPrice() + 5 ); \n";
str += " list.add( $c );";
str += "end\n";
String inXml = "";
inXml += "<batch-execution>";
inXml += " <set-global identifier='list' out='true'>";
inXml += " <list/>";
inXml += " </set-global>";
inXml += " <insert-elements>";
inXml += " <org.drools.Cheese>";
inXml += " <type>stilton</type>";
inXml += " <price>25</price>";
inXml += " <oldPrice>0</oldPrice>";
inXml += " </org.drools.Cheese>";
inXml += " <org.drools.Cheese>";
inXml += " <type>stilton</type>";
inXml += " <price>30</price>";
inXml += " <oldPrice>0</oldPrice>";
inXml += " </org.drools.Cheese>";
inXml += " </insert-elements>";
inXml += " <fire-all-rules />";
inXml += " <insert out-identifier='outBrie'>";
inXml += " <org.drools.Cheese>";
inXml += " <type>brie</type>";
inXml += " <price>10</price>";
inXml += " <oldPrice>5</oldPrice>";
inXml += " </org.drools.Cheese>";
inXml += " </insert>";
inXml += "</batch-execution>";
StatelessKnowledgeSession ksession = getSession2( ResourceFactory.newByteArrayResource( str.getBytes() ) );
ResultHandlerImpl resultHandler = new ResultHandlerImpl();
getPipeline(ksession).insert( inXml, resultHandler );
String outXml = ( String ) resultHandler.getObject();
String expectedXml = "";
expectedXml += "<batch-execution-results>\n";
expectedXml += " <result identifier='list'>\n";
expectedXml += " <list>\n";
expectedXml += " <org.drools.Cheese>\n";
expectedXml += " <type>stilton</type>\n";
expectedXml += " <price>35</price>\n";
expectedXml += " <oldPrice>0</oldPrice>\n";
expectedXml += " </org.drools.Cheese>\n";
expectedXml += " <org.drools.Cheese>\n";
expectedXml += " <type>stilton</type>\n";
expectedXml += " <price>30</price>\n";
expectedXml += " <oldPrice>0</oldPrice>\n";
expectedXml += " </org.drools.Cheese>\n";
expectedXml += " </list>\n";
expectedXml += " </result>\n";
expectedXml += " <result identifier='outBrie'>\n";
expectedXml += " <org.drools.Cheese>\n";
expectedXml += " <type>brie</type>\n";
expectedXml += " <price>10</price>\n";
expectedXml += " <oldPrice>5</oldPrice>\n";
expectedXml += " </org.drools.Cheese>\n";
expectedXml += " </result>\n";
expectedXml += "</batch-execution-results>\n";
assertXMLEqual( expectedXml, outXml );
BatchExecutionResults result = ( BatchExecutionResults ) BatchExecutionHelper.newXStreamMarshaller().fromXML( outXml );
// brie should not have been added to the list
List list = ( List ) result.getValue( "list" );
Cheese stilton25 = new Cheese( "stilton", 30);
Cheese stilton30 = new Cheese( "stilton", 35);
Set expectedList = new HashSet();
expectedList.add( stilton25 );
expectedList.add( stilton30 );
assertEquals( expectedList, new HashSet( list ));
// brie should not have changed
Cheese brie10 = new Cheese( "brie", 10);
brie10.setOldPrice( 5 );
assertEquals( brie10, result.getValue( "outBrie" ) );
}
public void testProcess() throws SAXException, IOException {
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
Reader source = new StringReader(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<process xmlns=\"http://drools.org/drools-5.0/process\"\n" +
" xmlns:xs=\"http:
" xs:schemaLocation=\"http://drools.org/drools-5.0/process drools-processes-5.0.xsd\"\n" +
" type=\"RuleFlow\" name=\"flow\" id=\"org.drools.actions\" package-name=\"org.drools\" version=\"1\" >\n" +
"\n" +
" <header>\n" +
" <imports>\n" +
" <import name=\"org.drools.TestVariable\" />\n" +
" </imports>\n" +
" <globals>\n" +
" <global identifier=\"list\" type=\"java.util.List\" />\n" +
" </globals>\n" +
" <variables>\n" +
" <variable name=\"person\" >\n" +
" <type name=\"org.drools.process.core.datatype.impl.type.ObjectDataType\" className=\"TestVariable\" />\n" +
" </variable>\n" +
" </variables>\n" +
" </header>\n" +
"\n" +
" <nodes>\n" +
" <start id=\"1\" name=\"Start\" />\n" +
" <actionNode id=\"2\" name=\"MyActionNode\" >\n" +
" <action type=\"expression\" dialect=\"mvel\" >System.out.println(\"Triggered\");\n" +
"list.add(person.name);\n" +
"</action>\n" +
" </actionNode>\n" +
" <end id=\"3\" name=\"End\" />\n" +
" </nodes>\n" +
"\n" +
" <connections>\n" +
" <connection from=\"1\" to=\"2\" />\n" +
" <connection from=\"2\" to=\"3\" />\n" +
" </connections>\n" +
"\n" +
"</process>");
kbuilder.add( ResourceFactory.newReaderResource( source ), ResourceType.DRF );
if ( kbuilder.hasErrors()) {
fail ( kbuilder.getErrors().toString() );
}
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
StatelessKnowledgeSession ksession = kbase.newStatelessKnowledgeSession();
List<String> list = new ArrayList<String>();
ksession.setGlobal("list", list);
TestVariable person = new TestVariable("John Doe");
String inXml = "";
inXml += "<batch-execution>";
inXml += " <startProcess processId='org.drools.actions'>";
inXml += " <parameter identifier='person'>";
inXml += " <org.drools.TestVariable>";
inXml += " <name>John Doe</name>";
inXml += " </org.drools.TestVariable>";
inXml += " </parameter>";
inXml += " </startProcess>";
inXml += " <get-global identifier='list' out-identifier='out-list'/>";
inXml += "</batch-execution>";
ResultHandlerImpl resultHandler = new ResultHandlerImpl();
getPipeline(ksession).insert( inXml, resultHandler );
String outXml = ( String ) resultHandler.getObject();
assertEquals(1, list.size());
assertEquals("John Doe", list.get(0));
String expectedXml = "";
expectedXml += "<batch-execution-results>\n";
expectedXml += " <result identifier=\"out-list\">\n";
expectedXml += " <list>\n";
expectedXml += " <string>John Doe</string>\n";
expectedXml += " </list>\n";
expectedXml += " </result>\n";
expectedXml += "</batch-execution-results>\n";
assertXMLEqual(expectedXml, outXml );
}
public void testInsertObjectWithDeclaredFact() throws Exception {
String str = "";
str += "package org.foo \n";
str += "declare Whee \n\ttype: String\n\tprice: Integer\n\toldPrice: Integer\nend\n";
str += "rule rule1 \n";
str += " when \n";
str += " $c : Whee() \n";
str += " \n";
str += " then \n";
str += " $c.setPrice( $c.getPrice() + 5 ); \n";
str += "end\n";
String inXml = "";
inXml += "<batch-execution>";
inXml += " <insert out-identifier='outStilton'>";
inXml += " <org.foo.Whee>";
inXml += " <type>stilton</type>";
inXml += " <price>25</price>";
inXml += " <oldPrice>0</oldPrice>";
inXml += " </org.foo.Whee>";
inXml += " </insert>";
inXml += "</batch-execution>";
StatelessKnowledgeSession ksession = getSession2( ResourceFactory.newByteArrayResource( str.getBytes() ) );
ResultHandlerImpl resultHandler = new ResultHandlerImpl();
getPipeline(ksession).insert( inXml, resultHandler );
String outXml = ( String ) resultHandler.getObject();
String expectedXml = "";
expectedXml += "<batch-execution-results>\n";
expectedXml += " <result identifier=\"outStilton\">\n";
expectedXml += " <org.foo.Whee>\n";
expectedXml += " <type>stilton</type>\n";
expectedXml += " <oldPrice>0</oldPrice>\n";
expectedXml += " <price>30</price>\n";
expectedXml += " </org.foo.Whee>\n";
expectedXml += " </result>\n";
expectedXml += "</batch-execution-results>\n";
assertXMLEqual(expectedXml, outXml );
}
public void testInsertObjectStateful() throws Exception {
String str = "";
str += "package org.foo \n";
str += "declare Whee \n\ttype: String\n\tprice: Integer\n\toldPrice: Integer\nend\n";
str += "rule rule1 \n";
str += " when \n";
str += " $c : Whee(price < 30) \n";
str += " \n";
str += " then \n";
str += " $c.setPrice( $c.getPrice() + 5 ); \n update($c);\n";
str += "end\n";
str += "query results\n";
str += " w: Whee(price == 30)";
str += "end\n";
String inXml = "";
inXml += "<batch-execution>";
inXml += " <insert>";
inXml += " <org.foo.Whee>";
inXml += " <type>stilton</type>";
inXml += " <price>25</price>";
inXml += " <oldPrice>0</oldPrice>";
inXml += " </org.foo.Whee>";
inXml += " </insert>";
inXml += "</batch-execution>";
StatefulKnowledgeSession ksession = getSessionStateful( ResourceFactory.newByteArrayResource( str.getBytes() ) );
ResultHandlerImpl resultHandler = new ResultHandlerImpl();
getPipelineStateful(ksession).insert( inXml, resultHandler );
String nextXML = "<batch-execution><query out-identifier='matchingthings' name='results'/></batch-execution>";
getPipelineStateful(ksession).insert( nextXML, resultHandler );
String outXml = ( String ) resultHandler.getObject();
//we have not fired the rules yet
assertFalse(outXml.indexOf("<price>30</price>") > -1);
ksession.fireAllRules();
//ok lets try that again...
getPipelineStateful(ksession).insert( nextXML, resultHandler );
outXml = ( String ) resultHandler.getObject();
assertTrue(outXml.indexOf("<price>30</price>") > -1);
}
private Pipeline getPipeline(StatelessKnowledgeSession ksession) {
Action executeResultHandler = PipelineFactory.newExecuteResultHandler();
Action assignResult = PipelineFactory.newAssignObjectAsResult();
assignResult.setReceiver( executeResultHandler );
Transformer outTransformer = PipelineFactory.newXStreamToXmlTransformer( BatchExecutionHelper.newXStreamMarshaller() );
outTransformer.setReceiver( assignResult );
KnowledgeRuntimeCommand batchExecution = PipelineFactory.newBatchExecutor();
batchExecution.setReceiver( outTransformer );
Transformer inTransformer = PipelineFactory.newXStreamFromXmlTransformer( BatchExecutionHelper.newXStreamMarshaller() );
inTransformer.setReceiver( batchExecution );
Pipeline pipeline = PipelineFactory.newStatelessKnowledgeSessionPipeline( ksession );
pipeline.setReceiver( inTransformer );
return pipeline;
}
private Pipeline getPipelineStateful(StatefulKnowledgeSession ksession) {
Action executeResultHandler = PipelineFactory.newExecuteResultHandler();
Action assignResult = PipelineFactory.newAssignObjectAsResult();
assignResult.setReceiver( executeResultHandler );
Transformer outTransformer = PipelineFactory.newXStreamToXmlTransformer( BatchExecutionHelper.newXStreamMarshaller() );
outTransformer.setReceiver( assignResult );
KnowledgeRuntimeCommand batchExecution = PipelineFactory.newBatchExecutor();
batchExecution.setReceiver( outTransformer );
Transformer inTransformer = PipelineFactory.newXStreamFromXmlTransformer( BatchExecutionHelper.newXStreamMarshaller() );
inTransformer.setReceiver( batchExecution );
Pipeline pipeline = PipelineFactory.newStatefulKnowledgeSessionPipeline( ksession );
pipeline.setReceiver( inTransformer );
return pipeline;
}
public static class ResultHandlerImpl
implements
ResultHandler {
Object object;
public void handleResult(Object object) {
this.object = object;
}
public Object getObject() {
return this.object;
}
}
private StatelessKnowledgeSession getSession2(Resource resource) throws Exception {
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add( resource, ResourceType.DRL );
if (kbuilder.hasErrors() ) {
System.out.println( kbuilder.getErrors() );
}
assertFalse( kbuilder.hasErrors() );
Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages();
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages( pkgs );
StatelessKnowledgeSession session = kbase.newStatelessKnowledgeSession();
return session;
}
private StatefulKnowledgeSession getSessionStateful(Resource resource) throws Exception {
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add( resource, ResourceType.DRL );
if (kbuilder.hasErrors() ) {
System.out.println( kbuilder.getErrors() );
}
assertFalse( kbuilder.hasErrors() );
Collection<KnowledgePackage> pkgs = kbuilder.getKnowledgePackages();
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages( pkgs );
StatefulKnowledgeSession session = kbase.newStatefulKnowledgeSession();
return session;
}
} |
package org.elasticsearch.xpack.prelert.job.process.normalizer;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.xpack.prelert.job.quantiles.Quantiles;
import org.mockito.ArgumentCaptor;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
public class ShortCircuitingRenormalizerTests extends ESTestCase {
private static final String JOB_ID = "foo";
// Never reduce this below 4, otherwise some of the logic in the test will break
private static final int TEST_SIZE = 1000;
public void testNormalize() throws InterruptedException {
ExecutorService threadpool = Executors.newScheduledThreadPool(10);
try {
ScoresUpdater scoresUpdater = mock(ScoresUpdater.class);
boolean isPerPartitionNormalization = randomBoolean();
ShortCircuitingRenormalizer renormalizer = new ShortCircuitingRenormalizer(JOB_ID, scoresUpdater, threadpool,
isPerPartitionNormalization);
// Blast through many sets of quantiles in quick succession, faster than the normalizer can process them
for (int i = 1; i < TEST_SIZE / 2; ++i) {
Quantiles quantiles = new Quantiles(JOB_ID, new Date(), Integer.toString(i));
renormalizer.renormalize(quantiles);
}
renormalizer.waitUntilIdle();
for (int i = TEST_SIZE / 2; i <= TEST_SIZE; ++i) {
Quantiles quantiles = new Quantiles(JOB_ID, new Date(), Integer.toString(i));
renormalizer.renormalize(quantiles);
}
renormalizer.waitUntilIdle();
ArgumentCaptor<String> stateCaptor = ArgumentCaptor.forClass(String.class);
verify(scoresUpdater, atLeastOnce()).update(stateCaptor.capture(), anyLong(), anyLong(), eq(isPerPartitionNormalization));
List<String> quantilesUsed = stateCaptor.getAllValues();
assertFalse(quantilesUsed.isEmpty());
assertTrue("quantilesUsed.size() is " + quantilesUsed.size(), quantilesUsed.size() <= TEST_SIZE);
// Last quantiles state that was actually used must be the last quantiles state we supplied
assertEquals(Integer.toString(TEST_SIZE), quantilesUsed.get(quantilesUsed.size() - 1));
// Earlier quantiles states that were processed must have been processed in the supplied order
int previous = 0;
for (String state : quantilesUsed) {
int current = Integer.parseInt(state);
assertTrue("Out of sequence states were " + previous + " and " + current + " in " + quantilesUsed, current > previous);
previous = current;
}
// The quantiles immediately before the intermediate wait for idle must have been processed
int intermediateWaitPoint = TEST_SIZE / 2 - 1;
assertTrue(quantilesUsed + " should contain " + intermediateWaitPoint,
quantilesUsed.contains(Integer.toString(intermediateWaitPoint)));
} finally {
threadpool.shutdown();
}
assertTrue(threadpool.awaitTermination(1, TimeUnit.SECONDS));
}
} |
package org.ovirt.engine.ui.uicommonweb.models.quota;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.PermissionsOperationsParameters;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.businessentities.DbGroup;
import org.ovirt.engine.core.common.businessentities.DbUser;
import org.ovirt.engine.core.common.businessentities.Permissions;
import org.ovirt.engine.core.common.businessentities.Quota;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.UICommand;
import org.ovirt.engine.ui.uicommonweb.auth.ApplicationGuids;
import org.ovirt.engine.ui.uicommonweb.help.HelpTag;
import org.ovirt.engine.ui.uicommonweb.models.ConfirmationModel;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.SearchableListModel;
import org.ovirt.engine.ui.uicommonweb.models.users.AdElementListModel;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
import org.ovirt.engine.ui.uicompat.FrontendMultipleActionAsyncResult;
import org.ovirt.engine.ui.uicompat.IFrontendMultipleActionAsyncCallback;
public class QuotaUserListModel extends SearchableListModel {
public QuotaUserListModel() {
setTitle(ConstantsManager.getInstance().getConstants().usersTitle());
setHelpTag(HelpTag.users);
setHashName("users"); //$NON-NLS-1$
setAddCommand(new UICommand("Add", this)); //$NON-NLS-1$
setRemoveCommand(new UICommand("Remove", this)); //$NON-NLS-1$
updateActionAvailability();
}
private UICommand privateAddCommand;
public UICommand getAddCommand()
{
return privateAddCommand;
}
private void setAddCommand(UICommand value)
{
privateAddCommand = value;
}
private UICommand privateRemoveCommand;
public UICommand getRemoveCommand()
{
return privateRemoveCommand;
}
private void setRemoveCommand(UICommand value)
{
privateRemoveCommand = value;
}
@Override
protected void syncSearch() {
super.syncSearch();
IdQueryParameters param = new IdQueryParameters(((Quota) getEntity()).getId());
param.setRefresh(getIsQueryFirstTime());
AsyncQuery _asyncQuery = new AsyncQuery();
_asyncQuery.setModel(this);
_asyncQuery.asyncCallback = new INewAsyncCallback() {
@Override
public void onSuccess(Object model, Object ReturnValue)
{
SearchableListModel searchableListModel = (SearchableListModel) model;
ArrayList<Permissions> list =
(ArrayList<Permissions>) ((VdcQueryReturnValue) ReturnValue).getReturnValue();
Map<Guid, Permissions> map = new HashMap<Guid, Permissions>();
for (Permissions permission : list) {
//filter out sys-admin and dc admin from consumers sub-tab
if (permission.getrole_id().equals(ApplicationGuids.superUser.asGuid())
|| permission.getrole_id().equals(ApplicationGuids.dataCenterAdmin.asGuid())) {
continue;
}
if (!map.containsKey(permission.getad_element_id())) {
map.put(permission.getad_element_id(), permission);
} else {
if (map.get(permission.getad_element_id())
.getrole_id()
.equals(ApplicationGuids.quotaConsumer.asGuid())) {
map.put(permission.getad_element_id(), permission);
}
}
}
list.clear();
for (Permissions permission : map.values()) {
list.add(permission);
}
searchableListModel.setItems(list);
}
};
param.setRefresh(getIsQueryFirstTime());
Frontend.getInstance().runQuery(VdcQueryType.GetPermissionsToConsumeQuotaByQuotaId, param, _asyncQuery);
setIsQueryFirstTime(false);
}
@Override
protected void onEntityChanged()
{
super.onEntityChanged();
if (getEntity() == null) {
return;
}
getSearchCommand().execute();
updateActionAvailability();
}
@Override
protected void selectedItemsChanged() {
super.selectedItemsChanged();
updateActionAvailability();
}
@Override
protected String getListName() {
return "QuotaUserListModel"; //$NON-NLS-1$
}
private void updateActionAvailability() {
ArrayList<Permissions> items =
(((ArrayList<Permissions>) getSelectedItems()) != null) ? (ArrayList<Permissions>) getSelectedItems()
: new ArrayList<Permissions>();
boolean removeExe = false;
if (items.size() > 0) {
removeExe = true;
}
for (Permissions perm : items) {
if (!perm.getrole_id().equals(ApplicationGuids.quotaConsumer.asGuid())) {
removeExe = false;
break;
}
}
getRemoveCommand().setIsExecutionAllowed(removeExe);
}
public void add()
{
if (getWindow() != null)
{
return;
}
AdElementListModel model = new AdElementListModel();
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().assignUsersAndGroupsToQuotaTitle());
model.setHelpTag(HelpTag.assign_users_and_groups_to_quota);
model.setHashName("assign_users_and_groups_to_quota"); //$NON-NLS-1$
model.setIsRoleListHidden(true);
model.getIsEveryoneSelectionHidden().setEntity(false);
UICommand tempVar = new UICommand("OnAdd", this); //$NON-NLS-1$
tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok());
tempVar.setIsDefault(true);
model.getCommands().add(tempVar);
UICommand tempVar2 = new UICommand("Cancel", this); //$NON-NLS-1$
tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel());
tempVar2.setIsCancel(true);
model.getCommands().add(tempVar2);
}
public void remove()
{
if (getWindow() != null)
{
return;
}
ConfirmationModel model = new ConfirmationModel();
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().removeQuotaAssignmentFromUsersTitle());
model.setHelpTag(HelpTag.remove_quota_assignment_from_user);
model.setHashName("remove_quota_assignment_from_user"); //$NON-NLS-1$
ArrayList<String> list = new ArrayList<String>();
for (Permissions item : Linq.<Permissions> cast(getSelectedItems()))
{
list.add(item.getOwnerName());
}
model.setItems(list);
UICommand tempVar = new UICommand("OnRemove", this); //$NON-NLS-1$
tempVar.setTitle(ConstantsManager.getInstance().getConstants().ok());
tempVar.setIsDefault(true);
model.getCommands().add(tempVar);
UICommand tempVar2 = new UICommand("Cancel", this); //$NON-NLS-1$
tempVar2.setTitle(ConstantsManager.getInstance().getConstants().cancel());
tempVar2.setIsCancel(true);
model.getCommands().add(tempVar2);
}
private void cancel() {
setWindow(null);
}
public void onAdd()
{
AdElementListModel model = (AdElementListModel) getWindow();
if (model.getProgress() != null)
{
return;
}
if (model.getSelectedItems() == null && !model.getIsEveryoneSelected())
{
cancel();
return;
}
ArrayList<DbUser> items = new ArrayList<DbUser>();
if (model.getIsEveryoneSelected())
{
DbUser tempVar = new DbUser();
tempVar.setId(ApplicationGuids.everyone.asGuid());
items.add(tempVar);
}
else {
for (Object item : model.getItems())
{
EntityModel entityModel = (EntityModel) item;
if (entityModel.getIsSelected())
{
items.add((DbUser) entityModel.getEntity());
}
}
}
model.startProgress(null);
ArrayList<VdcActionParametersBase> list = new ArrayList<VdcActionParametersBase>();
PermissionsOperationsParameters permissionParams;
for (DbUser user : items)
{
Permissions tempVar2 = new Permissions();
tempVar2.setad_element_id(user.getId());
tempVar2.setrole_id(ApplicationGuids.quotaConsumer.asGuid());
Permissions perm = tempVar2;
perm.setObjectId(((Quota) getEntity()).getId());
perm.setObjectType(VdcObjectType.Quota);
permissionParams = new PermissionsOperationsParameters();
if (user.isGroup())
{
DbGroup group = new DbGroup();
group.setId(user.getId());
group.setExternalId(user.getExternalId());
group.setName(user.getFirstName());
group.setDomain(user.getDomain());
permissionParams.setGroup(group);
}
else
{
permissionParams.setUser(user);
}
permissionParams.setPermission(perm);
list.add(permissionParams);
}
Frontend.getInstance().runMultipleAction(VdcActionType.AddPermission, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void executed(FrontendMultipleActionAsyncResult result) {
QuotaUserListModel localModel = (QuotaUserListModel) result.getState();
localModel.stopProgress();
cancel();
}
}, model);
cancel();
}
private void onRemove()
{
if (getSelectedItems() != null && getSelectedItems().size() > 0)
{
ConfirmationModel model = (ConfirmationModel) getWindow();
if (model.getProgress() != null)
{
return;
}
ArrayList<VdcActionParametersBase> list = new ArrayList<VdcActionParametersBase>();
for (Object perm : getSelectedItems())
{
PermissionsOperationsParameters tempVar = new PermissionsOperationsParameters();
tempVar.setPermission((Permissions) perm);
list.add(tempVar);
}
model.startProgress(null);
Frontend.getInstance().runMultipleAction(VdcActionType.RemovePermission, list,
new IFrontendMultipleActionAsyncCallback() {
@Override
public void executed(FrontendMultipleActionAsyncResult result) {
ConfirmationModel localModel = (ConfirmationModel) result.getState();
localModel.stopProgress();
cancel();
}
}, model);
}
cancel();
}
@Override
public void executeCommand(UICommand command)
{
super.executeCommand(command);
if (command == getAddCommand())
{
add();
}
if (command == getRemoveCommand())
{
remove();
}
if ("Cancel".equals(command.getName())) //$NON-NLS-1$
{
cancel();
}
if ("OnAdd".equals(command.getName())) //$NON-NLS-1$
{
onAdd();
}
if ("OnRemove".equals(command.getName())) //$NON-NLS-1$
{
onRemove();
}
}
} |
package org.ovirt.engine.ui.uicommonweb.models.storage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.ovirt.engine.core.common.action.AddSANStorageDomainParameters;
import org.ovirt.engine.core.common.action.ExtendSANStorageDomainParameters;
import org.ovirt.engine.core.common.action.RemoveStorageDomainParameters;
import org.ovirt.engine.core.common.action.StorageDomainManagementParameter;
import org.ovirt.engine.core.common.action.StorageDomainParametersBase;
import org.ovirt.engine.core.common.action.StorageDomainPoolParametersBase;
import org.ovirt.engine.core.common.action.StorageServerConnectionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionParametersBase;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.businessentities.LUNs;
import org.ovirt.engine.core.common.businessentities.NfsVersion;
import org.ovirt.engine.core.common.businessentities.StorageDomain;
import org.ovirt.engine.core.common.businessentities.StorageDomainSharedStatus;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatic;
import org.ovirt.engine.core.common.businessentities.StorageDomainStatus;
import org.ovirt.engine.core.common.businessentities.StorageDomainType;
import org.ovirt.engine.core.common.businessentities.StorageFormatType;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.StorageServerConnections;
import org.ovirt.engine.core.common.businessentities.StorageType;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.interfaces.SearchType;
import org.ovirt.engine.core.common.mode.ApplicationMode;
import org.ovirt.engine.core.common.queries.SearchParameters;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.StringHelper;
import org.ovirt.engine.core.searchbackend.SearchObjects;
import org.ovirt.engine.ui.frontend.AsyncQuery;
import org.ovirt.engine.ui.frontend.Frontend;
import org.ovirt.engine.ui.frontend.INewAsyncCallback;
import org.ovirt.engine.ui.uicommonweb.Cloner;
import org.ovirt.engine.ui.uicommonweb.Linq;
import org.ovirt.engine.ui.uicommonweb.UICommand;
import org.ovirt.engine.ui.uicommonweb.dataprovider.AsyncDataProvider;
import org.ovirt.engine.ui.uicommonweb.models.ConfirmationModel;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.ISupportSystemTreeContext;
import org.ovirt.engine.ui.uicommonweb.models.ListModel;
import org.ovirt.engine.ui.uicommonweb.models.ListWithDetailsModel;
import org.ovirt.engine.ui.uicommonweb.models.Model;
import org.ovirt.engine.ui.uicommonweb.models.SystemTreeItemModel;
import org.ovirt.engine.ui.uicommonweb.models.SystemTreeItemType;
import org.ovirt.engine.ui.uicommonweb.models.configure.PermissionListModel;
import org.ovirt.engine.ui.uicommonweb.models.reports.ReportModel;
import org.ovirt.engine.ui.uicommonweb.validation.IValidation;
import org.ovirt.engine.ui.uicommonweb.validation.NotEmptyValidation;
import org.ovirt.engine.ui.uicommonweb.validation.RegexValidation;
import org.ovirt.engine.ui.uicompat.ConstantsManager;
import org.ovirt.engine.ui.uicompat.Event;
import org.ovirt.engine.ui.uicompat.EventArgs;
import org.ovirt.engine.ui.uicompat.FrontendActionAsyncResult;
import org.ovirt.engine.ui.uicompat.FrontendMultipleActionAsyncResult;
import org.ovirt.engine.ui.uicompat.IEventListener;
import org.ovirt.engine.ui.uicompat.IFrontendActionAsyncCallback;
import org.ovirt.engine.ui.uicompat.IFrontendMultipleActionAsyncCallback;
import org.ovirt.engine.ui.uicompat.ITaskTarget;
import org.ovirt.engine.ui.uicompat.NotifyCollectionChangedEventArgs;
import org.ovirt.engine.ui.uicompat.ObservableCollection;
import org.ovirt.engine.ui.uicompat.PropertyChangedEventArgs;
import org.ovirt.engine.ui.uicompat.Task;
import org.ovirt.engine.ui.uicompat.TaskContext;
import org.ovirt.engine.ui.uicompat.UIConstants;
@SuppressWarnings("unused")
public class StorageListModel extends ListWithDetailsModel implements ITaskTarget, ISupportSystemTreeContext
{
private UICommand privateNewDomainCommand;
public UICommand getNewDomainCommand()
{
return privateNewDomainCommand;
}
private void setNewDomainCommand(UICommand value)
{
privateNewDomainCommand = value;
}
private UICommand privateImportDomainCommand;
public UICommand getImportDomainCommand()
{
return privateImportDomainCommand;
}
private void setImportDomainCommand(UICommand value)
{
privateImportDomainCommand = value;
}
private UICommand privateEditCommand;
@Override
public UICommand getEditCommand()
{
return privateEditCommand;
}
private void setEditCommand(UICommand value)
{
privateEditCommand = value;
}
private UICommand privateRemoveCommand;
public UICommand getRemoveCommand()
{
return privateRemoveCommand;
}
private void setRemoveCommand(UICommand value)
{
privateRemoveCommand = value;
}
private UICommand privateDestroyCommand;
public UICommand getDestroyCommand()
{
return privateDestroyCommand;
}
private void setDestroyCommand(UICommand value)
{
privateDestroyCommand = value;
}
private ArrayList<String> usedLunsMessages;
public ArrayList<String> getUsedLunsMessages() {
return usedLunsMessages;
}
public void setUsedLunsMessages(ArrayList<String> usedLunsMessages) {
this.usedLunsMessages = usedLunsMessages;
}
// get { return SelectedItems == null ? new object[0] : SelectedItems.Cast<storage_domains>().Select(a =>
// a.id).Cast<object>().ToArray(); }
protected Object[] getSelectedKeys()
{
if (getSelectedItems() == null)
{
return new Object[0];
}
else
{
ArrayList<Object> items = new ArrayList<Object>();
for (Object item : getSelectedItems())
{
StorageDomain i = (StorageDomain) item;
items.add(i.getId());
}
return items.toArray(new Object[] {});
}
}
public StorageListModel()
{
setTitle(ConstantsManager.getInstance().getConstants().storageTitle());
setDefaultSearchString("Storage:"); //$NON-NLS-1$
setSearchString(getDefaultSearchString());
setSearchObjects(new String[] { SearchObjects.VDC_STORAGE_DOMAIN_OBJ_NAME, SearchObjects.VDC_STORAGE_DOMAIN_PLU_OBJ_NAME });
setAvailableInModes(ApplicationMode.VirtOnly);
setNewDomainCommand(new UICommand("NewDomain", this)); //$NON-NLS-1$
setImportDomainCommand(new UICommand("ImportDomain", this)); //$NON-NLS-1$
setEditCommand(new UICommand("Edit", this)); //$NON-NLS-1$
setRemoveCommand(new UICommand("Remove", this)); //$NON-NLS-1$
setDestroyCommand(new UICommand("Destroy", this)); //$NON-NLS-1$
updateActionAvailability();
getSearchNextPageCommand().setIsAvailable(true);
getSearchPreviousPageCommand().setIsAvailable(true);
}
private EntityModel generalModel;
private EntityModel vmBackupModel;
private EntityModel templateBackupModel;
private ListModel dcListModel;
private ListModel vmListModel;
private ListModel templateListModel;
private ListModel isoListModel;
private ListModel diskListModel;
public StorageDomainStatic storageDomain;
public TaskContext context;
public IStorageModel storageModel;
public Guid storageId;
public StorageServerConnections fileConnection;
public StorageServerConnections connection;
public Guid hostId = Guid.Empty;
public String path;
public StorageDomainType domainType = StorageDomainType.values()[0];
public StorageType storageType;
public boolean removeConnection;
@Override
protected void initDetailModels()
{
super.initDetailModels();
generalModel = new StorageGeneralModel();
generalModel.setIsAvailable(false);
dcListModel = new StorageDataCenterListModel();
dcListModel.setIsAvailable(false);
vmBackupModel = new VmBackupModel();
vmBackupModel.setIsAvailable(false);
templateBackupModel = new TemplateBackupModel();
templateBackupModel.setIsAvailable(false);
vmListModel = new StorageVmListModel();
vmListModel.setIsAvailable(false);
templateListModel = new StorageTemplateListModel();
templateListModel.setIsAvailable(false);
isoListModel = new StorageIsoListModel();
isoListModel.setIsAvailable(false);
diskListModel = new StorageDiskListModel();
diskListModel.setIsAvailable(false);
ObservableCollection<EntityModel> list = new ObservableCollection<EntityModel>();
list.add(generalModel);
list.add(dcListModel);
list.add(vmBackupModel);
list.add(templateBackupModel);
list.add(vmListModel);
list.add(templateListModel);
list.add(isoListModel);
list.add(diskListModel);
list.add(new StorageEventListModel());
list.add(new PermissionListModel());
setDetailModels(list);
}
@Override
public boolean isSearchStringMatch(String searchString)
{
return searchString.trim().toLowerCase().startsWith("storage"); //$NON-NLS-1$
}
@Override
protected void syncSearch()
{
SearchParameters tempVar = new SearchParameters(getSearchString(), SearchType.StorageDomain);
tempVar.setMaxCount(getSearchPageSize());
super.syncSearch(VdcQueryType.Search, tempVar);
}
private void newDomain()
{
if (getWindow() != null)
{
return;
}
StorageModel model = new StorageModel(new NewEditStorageModelBehavior());
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().newDomainTitle());
model.setHashName("new_domain"); //$NON-NLS-1$
model.setSystemTreeSelectedItem(getSystemTreeSelectedItem());
ArrayList<IStorageModel> items = new ArrayList<IStorageModel>();
// putting all Data domains at the beginning on purpose (so when choosing the
// first selectable storage type/function, it will be a Data one, if relevant).
NfsStorageModel nfsDataModel = new NfsStorageModel();
nfsDataModel.setRole(StorageDomainType.Data);
items.add(nfsDataModel);
IscsiStorageModel iscsiDataModel = new IscsiStorageModel();
iscsiDataModel.setRole(StorageDomainType.Data);
iscsiDataModel.setIsGrouppedByTarget(true);
items.add(iscsiDataModel);
FcpStorageModel fcpDataModel = new FcpStorageModel();
fcpDataModel.setRole(StorageDomainType.Data);
items.add(fcpDataModel);
LocalStorageModel localDataModel = new LocalStorageModel();
localDataModel.setRole(StorageDomainType.Data);
items.add(localDataModel);
LocalStorageModel localIsoModel = new LocalStorageModel();
localIsoModel.setRole(StorageDomainType.ISO);
items.add(localIsoModel);
PosixStorageModel posixDataModel = new PosixStorageModel();
posixDataModel.setRole(StorageDomainType.Data);
items.add(posixDataModel);
PosixStorageModel posixIsoModel = new PosixStorageModel();
posixIsoModel.setRole(StorageDomainType.ISO);
items.add(posixIsoModel);
NfsStorageModel nfsIsoModel = new NfsStorageModel();
nfsIsoModel.setRole(StorageDomainType.ISO);
items.add(nfsIsoModel);
NfsStorageModel nfsExportModel = new NfsStorageModel();
nfsExportModel.setRole(StorageDomainType.ImportExport);
items.add(nfsExportModel);
GlusterStorageModel GlusterDataModel = new GlusterStorageModel();
GlusterDataModel.setRole(StorageDomainType.Data);
items.add(GlusterDataModel);
model.setItems(items);
model.initialize();
UICommand command = createOKCommand("OnSave"); //$NON-NLS-1$
model.getCommands().add(command);
command = createCancelCommand("Cancel"); //$NON-NLS-1$
model.getCommands().add(command);
}
private void edit()
{
StorageDomain storage = (StorageDomain) getSelectedItem();
if (getWindow() != null)
{
return;
}
final UIConstants constants = ConstantsManager.getInstance().getConstants();
StorageModel model = new StorageModel(new NewEditStorageModelBehavior());
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().editDomainTitle());
model.setHashName("edit_domain"); //$NON-NLS-1$
model.setSystemTreeSelectedItem(getSystemTreeSelectedItem());
model.setStorage(storage);
model.getName().setEntity(storage.getStorageName());
model.getDescription().setEntity(storage.getDescription());
model.getComment().setEntity(storage.getComment());
model.setOriginalName(storage.getStorageName());
model.getDataCenter().setIsChangable(false);
model.getFormat().setIsChangable(false);
boolean isStorageEditable = model.isStorageActive() || model.isNewStorage();
model.getHost().setIsChangable(false);
model.getName().setIsChangable(isStorageEditable);
model.getDescription().setIsChangable(isStorageEditable);
model.getComment().setIsChangable(isStorageEditable);
//set the field domain type to non editable
model.getAvailableStorageItems().setIsChangable(false);
model.setIsChangable(isStorageEditable);
boolean isPathEditable = isPathEditable(storage);
isStorageEditable = isStorageEditable || isPathEditable;
IStorageModel item = null;
switch (storage.getStorageType()) {
case NFS:
item = prepareNfsStorageForEdit(storage);
//when storage is active, only SPM can perform actions on it, thus it is set above that host is not changeable.
//If storage is editable but not active (maintenance) - any host can perform the edit so the changeable here is set based on that
model.getHost().setIsChangable(isPathEditable);
break;
case FCP:
item = prepareFcpStorageForEdit(storage);
break;
case ISCSI:
item = prepareIscsiStorageForEdit(storage);
break;
case LOCALFS:
item = prepareLocalStorageForEdit(storage);
model.getHost().setIsChangable(isPathEditable);
break;
case POSIXFS:
item = preparePosixStorageForEdit(storage);
//when storage is active, only SPM can perform actions on it, thus it is set above that host is not changeable.
//If storage is editable but not active (maintenance) - any host can perform the edit so the changeable here is set based on that
model.getHost().setIsChangable(isPathEditable);
break;
case GLUSTERFS:
item = prepareGlusterStorageForEdit(storage);
break;
}
model.setItems(new ArrayList<IStorageModel>(Arrays.asList(new IStorageModel[] {item})));
model.setSelectedItem(item);
model.initialize();
if (getSystemTreeSelectedItem() != null && getSystemTreeSelectedItem().getType() == SystemTreeItemType.Storage)
{
model.getName().setIsChangable(false);
model.getName().setChangeProhibitionReason(constants.cannotEditNameInTreeContext());
}
UICommand command;
if (isStorageEditable) {
command = createOKCommand("OnSave"); //$NON-NLS-1$
model.getCommands().add(command);
command = createCancelCommand("Cancel"); //$NON-NLS-1$
model.getCommands().add(command);
}
else {
// close is created the same as cancel, but with a different title
// thus most of creation code can be reused.
command = createCancelCommand("Cancel"); //$NON-NLS-1$
command.setTitle(ConstantsManager.getInstance().getConstants().close());
model.getCommands().add(command);
}
}
private IStorageModel prepareNfsStorageForEdit(StorageDomain storage)
{
final NfsStorageModel model = new NfsStorageModel();
model.setRole(storage.getStorageDomainType());
boolean isNfsPathEditable = isPathEditable(storage);
model.getPath().setIsChangable(isNfsPathEditable);
model.getOverride().setIsChangable(isNfsPathEditable);
AsyncDataProvider.getStorageConnectionById(new AsyncQuery(null, new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
StorageServerConnections connection = (StorageServerConnections) returnValue;
model.getPath().setEntity(connection.getconnection());
model.getRetransmissions().setEntity(connection.getNfsRetrans());
model.getTimeout().setEntity(connection.getNfsTimeo());
for (Object item : model.getVersion().getItems()) {
EntityModel itemModel = (EntityModel) item;
boolean noNfsVersion = itemModel.getEntity() == null && connection.getNfsVersion() == null;
boolean foundNfsVersion = itemModel.getEntity() != null &&
itemModel.getEntity().equals(connection.getNfsVersion());
if (noNfsVersion || foundNfsVersion) {
model.getVersion().setSelectedItem(item);
break;
}
}
// If any settings were overridden, reflect this in the override checkbox
model.getOverride().setEntity(
connection.getNfsVersion() != null ||
connection.getNfsRetrans() != null ||
connection.getNfsTimeo() != null);
}
}), storage.getStorage(), true);
return model;
}
private boolean isPathEditable(StorageDomain storage) {
if (storage.getStorageType().isFileDomain() && !storage.getStorageType().equals(StorageType.GLUSTERFS)) {
return ((storage.getStorageDomainType() == StorageDomainType.Data || storage.getStorageDomainType() == StorageDomainType.Master) && (storage.getStatus() == StorageDomainStatus.Maintenance || storage.getStorageDomainSharedStatus() == StorageDomainSharedStatus.Unattached));
}
return false;
}
private IStorageModel prepareLocalStorageForEdit(StorageDomain storage)
{
LocalStorageModel model = new LocalStorageModel();
model.setRole(storage.getStorageDomainType());
boolean isPathEditable = isPathEditable(storage);
model.getPath().setIsChangable(isPathEditable);
AsyncDataProvider.getStorageConnectionById(new AsyncQuery(model, new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
LocalStorageModel localStorageModel = (LocalStorageModel) target;
StorageServerConnections connection = (StorageServerConnections) returnValue;
localStorageModel.getPath().setEntity(connection.getconnection());
}
}), storage.getStorage(), true);
return model;
}
private IStorageModel preparePosixStorageForEdit(StorageDomain storage) {
final PosixStorageModel model = new PosixStorageModel();
model.setRole(storage.getStorageDomainType());
boolean isPathEditable = isPathEditable(storage);
model.getPath().setIsChangable(isPathEditable);
model.getVfsType().setIsChangable(isPathEditable);
model.getMountOptions().setIsChangable(isPathEditable);
AsyncDataProvider.getStorageConnectionById(new AsyncQuery(null, new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
StorageServerConnections connection = (StorageServerConnections) returnValue;
model.getPath().setEntity(connection.getconnection());
model.getVfsType().setEntity(connection.getVfsType());
model.getMountOptions().setEntity(connection.getMountOptions());
}
}), storage.getStorage(), true);
return model;
}
private IStorageModel prepareIscsiStorageForEdit(StorageDomain storage)
{
IscsiStorageModel model = new IscsiStorageModel();
model.setRole(storage.getStorageDomainType());
prepareSanStorageForEdit(model);
return model;
}
private IStorageModel prepareFcpStorageForEdit(StorageDomain storage)
{
FcpStorageModel model = new FcpStorageModel();
model.setRole(storage.getStorageDomainType());
prepareSanStorageForEdit(model);
return model;
}
private IStorageModel prepareGlusterStorageForEdit(StorageDomain storage) {
final GlusterStorageModel model = new GlusterStorageModel();
model.setRole(storage.getStorageDomainType());
model.getPath().setIsChangable(true);
model.getVfsType().setIsChangable(false);
model.getMountOptions().setIsChangable(false);
AsyncDataProvider.getStorageConnectionById(new AsyncQuery(null, new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
StorageServerConnections connection = (StorageServerConnections) returnValue;
model.getPath().setEntity(connection.getconnection());
model.getVfsType().setEntity(connection.getVfsType());
model.getMountOptions().setEntity(connection.getMountOptions());
}
}), storage.getStorage(), true);
return model;
}
private void prepareSanStorageForEdit(final SanStorageModel model)
{
StorageModel storageModel = (StorageModel) getWindow();
boolean isStorageEditable = storageModel.isStorageActive() || storageModel.isNewStorage();
if (isStorageEditable) {
storageModel.getHost().getSelectedItemChangedEvent().addListener(new IEventListener() {
@Override
public void eventRaised(Event ev, Object sender, EventArgs args) {
postPrepareSanStorageForEdit(model, true);
}
});
}
else {
postPrepareSanStorageForEdit(model, false);
}
}
private void postPrepareSanStorageForEdit(SanStorageModel model, boolean isStorageActive)
{
StorageModel storageModel = (StorageModel) getWindow();
StorageDomain storage = (StorageDomain) getSelectedItem();
model.setStorageDomain(storage);
VDS host = (VDS) storageModel.getHost().getSelectedItem();
Guid hostId = host != null && isStorageActive ? host.getId() : null;
AsyncDataProvider.getLunsByVgId(new AsyncQuery(model, new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
SanStorageModel sanStorageModel = (SanStorageModel) target;
ArrayList<LUNs> lunList = (ArrayList<LUNs>) returnValue;
sanStorageModel.applyData(lunList, true);
}
}, storageModel.getHash()), storage.getStorage(), hostId);
}
private void importDomain()
{
if (getWindow() != null)
{
return;
}
StorageModel model = new StorageModel(new ImportStorageModelBehavior());
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().importPreConfiguredDomainTitle());
model.setHashName("import_pre-configured_domain"); //$NON-NLS-1$
model.setSystemTreeSelectedItem(getSystemTreeSelectedItem());
model.getName().setIsAvailable(false);
model.getDescription().setIsAvailable(false);
model.getComment().setIsAvailable(false);
model.getFormat().setIsAvailable(false);
ArrayList<IStorageModel> items = new ArrayList<IStorageModel>();
NfsStorageModel tempVar = new NfsStorageModel();
tempVar.setRole(StorageDomainType.ISO);
items.add(tempVar);
LocalStorageModel localIsoModel = new LocalStorageModel();
localIsoModel.setRole(StorageDomainType.ISO);
items.add(localIsoModel);
PosixStorageModel posixIsoModel = new PosixStorageModel();
posixIsoModel.setRole(StorageDomainType.ISO);
items.add(posixIsoModel);
NfsStorageModel tempVar2 = new NfsStorageModel();
tempVar2.setRole(StorageDomainType.ImportExport);
items.add(tempVar2);
model.setItems(items);
model.initialize();
UICommand command;
command = createOKCommand("OnImport"); //$NON-NLS-1$
model.getCommands().add(command);
command = createCancelCommand("Cancel"); //$NON-NLS-1$
model.getCommands().add(command);
}
private void onImport()
{
StorageModel model = (StorageModel) getWindow();
if (model.getProgress() != null)
{
return;
}
if (!model.validate())
{
return;
}
model.startProgress(ConstantsManager.getInstance().getConstants().importingStorageDomainProgress());
VDS host = (VDS) model.getHost().getSelectedItem();
// Save changes.
if (model.getSelectedItem() instanceof NfsStorageModel)
{
NfsStorageModel nfsModel = (NfsStorageModel) model.getSelectedItem();
nfsModel.setMessage(null);
Task.Create(this,
new ArrayList<Object>(Arrays.asList(new Object[] { "ImportFile", //$NON-NLS-1$
host.getId(), nfsModel.getPath().getEntity(), nfsModel.getRole(), StorageType.NFS }))).Run();
}
else if (model.getSelectedItem() instanceof LocalStorageModel)
{
LocalStorageModel localModel = (LocalStorageModel) model.getSelectedItem();
localModel.setMessage(null);
Task.Create(this,
new ArrayList<Object>(Arrays.asList(new Object[] { "ImportFile", //$NON-NLS-1$
host.getId(), localModel.getPath().getEntity(), localModel.getRole(), StorageType.LOCALFS }))).Run();
}
else if (model.getSelectedItem() instanceof PosixStorageModel)
{
PosixStorageModel posixModel = (PosixStorageModel) model.getSelectedItem();
posixModel.setMessage(null);
Task.Create(this,
new ArrayList<Object>(Arrays.asList(new Object[] { "ImportFile", //$NON-NLS-1$
host.getId(), posixModel.getPath().getEntity(), posixModel.getRole(), StorageType.POSIXFS}))).Run();
}
else
{
Task.Create(this,
new ArrayList<Object>(Arrays.asList(new Object[] { "ImportSan", //$NON-NLS-1$
host.getId() }))).Run();
}
}
public void storageNameValidation()
{
StorageModel model = (StorageModel) getWindow();
String name = (String) model.getName().getEntity();
model.getName().setIsValid(true);
AsyncDataProvider.isStorageDomainNameUnique(new AsyncQuery(this, new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
StorageListModel storageListModel = (StorageListModel) target;
StorageModel storageModel = (StorageModel) storageListModel.getWindow();
String name1 = (String) storageModel.getName().getEntity();
String tempVar = storageModel.getOriginalName();
String originalName = (tempVar != null) ? tempVar : ""; //$NON-NLS-1$
boolean isNameUnique = (Boolean) returnValue;
if (!isNameUnique && name1.compareToIgnoreCase(originalName) != 0) {
storageModel.getName()
.getInvalidityReasons()
.add(ConstantsManager.getInstance().getConstants().nameMustBeUniqueInvalidReason());
storageModel.getName().setIsValid(false);
storageListModel.postStorageNameValidation();
} else {
AsyncDataProvider.getStorageDomainMaxNameLength(new AsyncQuery(storageListModel, new INewAsyncCallback() {
@Override
public void onSuccess(Object target1, Object returnValue1) {
StorageListModel storageListModel1 = (StorageListModel) target1;
StorageModel storageModel1 = (StorageModel) storageListModel1.getWindow();
int nameMaxLength = (Integer) returnValue1;
RegexValidation tempVar2 = new RegexValidation();
tempVar2.setExpression("^[A-Za-z0-9_-]{1," + nameMaxLength + "}$"); //$NON-NLS-1$ //$NON-NLS-2$
tempVar2.setMessage(ConstantsManager.getInstance().getMessages()
.nameCanContainOnlyMsg(nameMaxLength));
storageModel1.getName().validateEntity(new IValidation[] {
new NotEmptyValidation(), tempVar2});
storageListModel1.postStorageNameValidation();
}
}));
}
}
}),
name);
}
public void postStorageNameValidation()
{
if (getLastExecutedCommand().getName().equals("OnSave")) //$NON-NLS-1$
{
onSavePostNameValidation();
}
}
private void cleanConnection(StorageServerConnections connection, Guid hostId) {
// if create connection command was the one to fail and didn't create a connection
// then the id of connection will be empty, and there's nothing to delete.
if (connection.getid() != null && !connection.getid().equals("")) { //$NON-NLS-1$
Frontend.RunAction(VdcActionType.RemoveStorageServerConnection, new StorageServerConnectionParametersBase(connection, hostId),
null, this);
}
}
private void remove()
{
if (getWindow() != null)
{
return;
}
RemoveStorageModel model = new RemoveStorageModel();
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().removeStoragesTitle());
model.setHashName("remove_storage"); //$NON-NLS-1$
model.setMessage(ConstantsManager.getInstance().getConstants().areYouSureYouWantToRemoveTheStorageDomainMsg());
model.getFormat().setIsAvailable(false);
StorageDomain storage = (StorageDomain) getSelectedItem();
boolean localFsOnly = storage.getStorageType() == StorageType.LOCALFS;
AsyncDataProvider.getHostsForStorageOperation(new AsyncQuery(new Object[]{this, model}, new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
Object[] array = (Object[]) target;
StorageListModel storageListModel = (StorageListModel) array[0];
RemoveStorageModel removeStorageModel = (RemoveStorageModel) array[1];
StorageDomain storage = (StorageDomain) storageListModel.getSelectedItem();
ArrayList<VDS> hosts = (ArrayList<VDS>) returnValue;
removeStorageModel.getHostList().setItems(hosts);
removeStorageModel.getHostList().setSelectedItem(Linq.firstOrDefault(hosts));
removeStorageModel.getFormat()
.setIsAvailable(storage.getStorageDomainType() == StorageDomainType.ISO
|| storage.getStorageDomainType() == StorageDomainType.ImportExport);
if (hosts.isEmpty()) {
UICommand tempVar = createCancelCommand("Cancel"); //$NON-NLS-1$
tempVar.setIsDefault(true);
removeStorageModel.getCommands().add(tempVar);
} else {
UICommand command;
command = createOKCommand("OnRemove"); //$NON-NLS-1$
removeStorageModel.getCommands().add(command);
command = createCancelCommand("Cancel"); //$NON-NLS-1$
removeStorageModel.getCommands().add(command);
}
}
}), null, localFsOnly);
}
private void onRemove()
{
if (getSelectedItem() != null)
{
StorageDomain storage = (StorageDomain) getSelectedItem();
RemoveStorageModel model = (RemoveStorageModel) getWindow();
if (!model.validate())
{
return;
}
VDS host = (VDS) model.getHostList().getSelectedItem();
RemoveStorageDomainParameters tempVar = new RemoveStorageDomainParameters(storage.getId());
tempVar.setVdsId(host.getId());
tempVar.setDoFormat((storage.getStorageDomainType() == StorageDomainType.Data || storage.getStorageDomainType() == StorageDomainType.Master) ? true
: (Boolean) model.getFormat().getEntity());
Frontend.RunAction(VdcActionType.RemoveStorageDomain, tempVar, null, this);
}
cancel();
}
private void destroy()
{
ConfirmationModel model = new ConfirmationModel();
setWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().destroyStorageDomainTitle());
model.setHashName("destroy_storage_domain"); //$NON-NLS-1$
ArrayList<String> items = new ArrayList<String>();
items.add(((StorageDomain) getSelectedItem()).getStorageName());
model.setItems(items);
model.getLatch().setIsAvailable(true);
model.getLatch().setIsChangable(true);
UICommand command;
command = createOKCommand("OnDestroy"); //$NON-NLS-1$
model.getCommands().add(command);
command = createCancelCommand("Cancel"); //$NON-NLS-1$
model.getCommands().add(command);
}
private void onDestroy()
{
ConfirmationModel model = (ConfirmationModel) getWindow();
if (model.getProgress() != null)
{
return;
}
if (!model.validate())
{
return;
}
StorageDomain storageDomain = (StorageDomain) getSelectedItem();
model.startProgress(null);
Frontend.RunMultipleAction(VdcActionType.ForceRemoveStorageDomain,
new ArrayList<VdcActionParametersBase>(Arrays.asList(new VdcActionParametersBase[]{new StorageDomainParametersBase(storageDomain.getId())})),
new IFrontendMultipleActionAsyncCallback() {
@Override
public void executed(FrontendMultipleActionAsyncResult result) {
ConfirmationModel localModel = (ConfirmationModel) result.getState();
localModel.stopProgress();
cancel();
}
},
model);
}
private void onSave()
{
storageNameValidation();
}
private void onSavePostNameValidation()
{
StorageModel model = (StorageModel) getWindow();
if (!model.validate())
{
return;
}
if (model.getSelectedItem() instanceof NfsStorageModel)
{
saveNfsStorage();
}
else if (model.getSelectedItem() instanceof LocalStorageModel)
{
saveLocalStorage();
}
else if (model.getSelectedItem() instanceof PosixStorageModel)
{
savePosixStorage();
}
else if (model.getSelectedItem() instanceof GlusterStorageModel)
{
saveGlusterStorage();
}
else
{
saveSanStorage();
}
}
private void saveLocalStorage()
{
if (getWindow().getProgress() != null)
{
return;
}
getWindow().startProgress(null);
Task.Create(this, new ArrayList<Object>(Arrays.asList(new Object[] { "SaveLocal" }))).Run(); //$NON-NLS-1$
}
private void saveNfsStorage()
{
if (getWindow().getProgress() != null)
{
return;
}
getWindow().startProgress(null);
Task.Create(this, new ArrayList<Object>(Arrays.asList(new Object[] { "SaveNfs" }))).Run(); //$NON-NLS-1$
}
private void savePosixStorage() {
if (getWindow().getProgress() != null) {
return;
}
getWindow().startProgress(null);
Task.Create(this, new ArrayList<Object>(Arrays.asList(new Object[] {"SavePosix"}))).Run(); //$NON-NLS-1$
}
private void saveGlusterStorage() {
if (getWindow().getProgress() != null) {
return;
}
getWindow().startProgress(null);
Task.Create(this, new ArrayList<Object>(Arrays.asList(new Object[] {"SaveGluster"}))).Run(); //$NON-NLS-1$
}
private void saveSanStorage()
{
StorageModel storageModel = (StorageModel) getWindow();
SanStorageModel sanStorageModel = (SanStorageModel) storageModel.getSelectedItem();
ArrayList<String> usedLunsMessages = sanStorageModel.getUsedLunsMessages();
if (usedLunsMessages.isEmpty()) {
onSaveSanStorage();
}
else {
forceCreationWarning(usedLunsMessages);
}
}
private void onSaveSanStorage()
{
ConfirmationModel confirmationModel = (ConfirmationModel) getConfirmWindow();
if (confirmationModel != null && !confirmationModel.validate())
{
return;
}
cancelConfirm();
getWindow().startProgress(null);
Task.Create(this, new ArrayList<Object>(Arrays.asList(new Object[] { "SaveSan" }))).Run(); //$NON-NLS-1$
}
private void forceCreationWarning(ArrayList<String> usedLunsMessages) {
StorageModel storageModel = (StorageModel) getWindow();
SanStorageModel sanStorageModel = (SanStorageModel) storageModel.getSelectedItem();
sanStorageModel.setForce(true);
ConfirmationModel model = new ConfirmationModel();
setConfirmWindow(model);
model.setTitle(ConstantsManager.getInstance().getConstants().forceStorageDomainCreation());
model.setMessage(ConstantsManager.getInstance().getConstants().lunsAlreadyInUse());
model.setHashName("force_storage_domain_creation"); //$NON-NLS-1$
model.setItems(usedLunsMessages);
UICommand command = createOKCommand("OnSaveSanStorage"); //$NON-NLS-1$
model.getCommands().add(command);
command = createCancelCommand("CancelConfirm"); //$NON-NLS-1$
model.getCommands().add(command);
}
private void cancelConfirm()
{
setConfirmWindow(null);
}
private void cancel()
{
setWindow(null);
Frontend.Unsubscribe();
}
@Override
protected void onSelectedItemChanged()
{
super.onSelectedItemChanged();
updateActionAvailability();
}
@Override
protected void itemsCollectionChanged(Object sender, NotifyCollectionChangedEventArgs e)
{
super.itemsCollectionChanged(sender, e);
// Try to select an item corresponding to the system tree selection.
if (getSystemTreeSelectedItem() != null && getSystemTreeSelectedItem().getType() == SystemTreeItemType.Storage)
{
StorageDomain storage = (StorageDomain) getSystemTreeSelectedItem().getEntity();
setSelectedItem(Linq.firstOrDefault(Linq.<StorageDomain> cast(getItems()),
new Linq.StoragePredicate(storage.getId())));
}
}
@Override
protected void updateDetailsAvailability()
{
if (getSelectedItem() != null)
{
StorageDomain storage = (StorageDomain) getSelectedItem();
boolean isBackupStorage = storage.getStorageDomainType() == StorageDomainType.ImportExport;
boolean isDataStorage =
storage.getStorageDomainType() == StorageDomainType.Data
|| storage.getStorageDomainType() == StorageDomainType.Master;
boolean isImageStorage =
storage.getStorageDomainType() == StorageDomainType.Image ||
storage.getStorageDomainType() == StorageDomainType.ISO;
boolean isDataCenterAvailable = storage.getStorageType() != StorageType.GLANCE;
boolean isGeneralAvailable = storage.getStorageType() != StorageType.GLANCE;
generalModel.setIsAvailable(isGeneralAvailable);
dcListModel.setIsAvailable(isDataCenterAvailable);
vmBackupModel.setIsAvailable(isBackupStorage);
templateBackupModel.setIsAvailable(isBackupStorage);
vmListModel.setIsAvailable(isDataStorage);
templateListModel.setIsAvailable(isDataStorage);
diskListModel.setIsAvailable(isDataStorage);
isoListModel.setIsAvailable(isImageStorage);
}
}
@Override
protected void selectedItemsChanged()
{
super.selectedItemsChanged();
updateActionAvailability();
}
@Override
protected void selectedItemPropertyChanged(Object sender, PropertyChangedEventArgs e)
{
super.selectedItemPropertyChanged(sender, e);
if (e.PropertyName.equals("storage_domain_shared_status")) //$NON-NLS-1$
{
updateActionAvailability();
}
}
private void updateActionAvailability()
{
ArrayList<StorageDomain> items =
getSelectedItems() != null ? Linq.<StorageDomain> cast(getSelectedItems())
: new ArrayList<StorageDomain>();
StorageDomain item = (StorageDomain) getSelectedItem();
getNewDomainCommand().setIsAvailable(true);
getEditCommand().setIsExecutionAllowed(items.size() == 1 && isEditAvailable(item));
getRemoveCommand().setIsExecutionAllowed(items.size() == 1
&& items.get(0).getStorageType() != StorageType.GLANCE
&& Linq.findAllStorageDomainsBySharedStatus(items, StorageDomainSharedStatus.Unattached).size() == items.size());
getDestroyCommand().setIsExecutionAllowed(item != null && items.size() == 1
&& item.getStatus() != StorageDomainStatus.Active);
// System tree dependent actions.
boolean isAvailable =
!(getSystemTreeSelectedItem() != null && getSystemTreeSelectedItem().getType() == SystemTreeItemType.Storage);
getNewDomainCommand().setIsAvailable(isAvailable);
getRemoveCommand().setIsAvailable(isAvailable);
getDestroyCommand().setIsAvailable(isAvailable);
}
private boolean isEditAvailable(StorageDomain storageDomain) {
if (storageDomain == null) {
return false;
}
boolean isEditAvailable;
boolean isActive = storageDomain.getStorageDomainSharedStatus() == StorageDomainSharedStatus.Active
|| storageDomain.getStorageDomainSharedStatus() == StorageDomainSharedStatus.Mixed;
boolean isInMaintenance = (storageDomain.getStatus() == StorageDomainStatus.Maintenance);
boolean isUnattached = (storageDomain.getStorageDomainSharedStatus() == StorageDomainSharedStatus.Unattached);
boolean isDataDomain = (storageDomain.getStorageDomainType() == StorageDomainType.Data) || (storageDomain.getStorageDomainType() == StorageDomainType.Master);
boolean isBlockStorage = storageDomain.getStorageType().isBlockDomain();
isEditAvailable = isActive || isBlockStorage || ((isInMaintenance || isUnattached) && isDataDomain);
return isEditAvailable;
}
@Override
public void executeCommand(UICommand command)
{
super.executeCommand(command);
if (command == getNewDomainCommand())
{
newDomain();
}
else if (command == getImportDomainCommand())
{
importDomain();
}
else if (command == getEditCommand())
{
edit();
}
else if (command == getRemoveCommand())
{
remove();
}
else if (command == getDestroyCommand())
{
destroy();
}
else if (StringHelper.stringsEqual(command.getName(), "OnSave")) //$NON-NLS-1$
{
onSave();
}
else if (StringHelper.stringsEqual(command.getName(), "Cancel")) //$NON-NLS-1$
{
cancel();
}
else if (StringHelper.stringsEqual(command.getName(), "CancelConfirm")) //$NON-NLS-1$
{
cancelConfirm();
}
else if (StringHelper.stringsEqual(command.getName(), "OnImport")) //$NON-NLS-1$
{
onImport();
}
else if (StringHelper.stringsEqual(command.getName(), "OnRemove")) //$NON-NLS-1$
{
onRemove();
}
else if (StringHelper.stringsEqual(command.getName(), "OnDestroy")) //$NON-NLS-1$
{
onDestroy();
}
else if (StringHelper.stringsEqual(command.getName(), "OnSaveSanStorage")) //$NON-NLS-1$
{
onSaveSanStorage();
}
}
private void savePosixStorage(TaskContext context) {
this.context = context;
StorageDomain selectedItem = (StorageDomain) getSelectedItem();
StorageModel model = (StorageModel) getWindow();
boolean isNew = model.getStorage() == null;
storageModel = model.getSelectedItem();
PosixStorageModel posixModel = (PosixStorageModel) storageModel;
path = (String) posixModel.getPath().getEntity();
storageDomain = isNew ? new StorageDomainStatic() : (StorageDomainStatic) Cloner.clone(selectedItem.getStorageStaticData());
storageDomain.setStorageType(isNew ? storageModel.getType() : storageDomain.getStorageType());
storageDomain.setStorageDomainType(isNew ? storageModel.getRole() : storageDomain.getStorageDomainType());
storageDomain.setStorageName((String) model.getName().getEntity());
storageDomain.setDescription((String) model.getDescription().getEntity());
storageDomain.setComment((String) model.getComment().getEntity());
storageDomain.setStorageFormat((StorageFormatType) model.getFormat().getSelectedItem());
if (isNew) {
AsyncDataProvider.getStorageDomainsByConnection(new AsyncQuery(this, new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
StorageListModel storageListModel = (StorageListModel) target;
ArrayList<StorageDomain> storages = (ArrayList<StorageDomain>) returnValue;
if (storages != null && storages.size() > 0) {
handleDomainAlreadyExists(storageListModel, storages);
} else {
storageListModel.saveNewPosixStorage();
}
}
}), null, path);
} else {
StorageDomain storageDomain = (StorageDomain) getSelectedItem();
if (isPathEditable(storageDomain)) {
updatePath();
}
else {
updateStorageDomain();
}
}
}
private void updateStorageDomain() {
Frontend.RunAction(VdcActionType.UpdateStorageDomain, new StorageDomainManagementParameter(this.storageDomain), new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
StorageListModel storageListModel = (StorageListModel) result.getState();
storageListModel.onFinish(storageListModel.context, true, storageListModel.storageModel);
}
}, this);
}
public void saveNewPosixStorage() {
StorageModel model = (StorageModel) getWindow();
PosixStorageModel posixModel = (PosixStorageModel) model.getSelectedItem();
VDS host = (VDS) model.getHost().getSelectedItem();
hostId = host.getId();
// Create storage connection.
StorageServerConnections connection = new StorageServerConnections();
connection.setconnection(path);
connection.setstorage_type(posixModel.getType());
connection.setVfsType((String) posixModel.getVfsType().getEntity());
connection.setMountOptions((String) posixModel.getMountOptions().getEntity());
this.connection = connection;
ArrayList<VdcActionType> actionTypes = new ArrayList<VdcActionType>();
ArrayList<VdcActionParametersBase> parameters = new ArrayList<VdcActionParametersBase>();
actionTypes.add(VdcActionType.AddStorageServerConnection);
actionTypes.add(VdcActionType.AddPosixFsStorageDomain);
parameters.add(new StorageServerConnectionParametersBase(this.connection, host.getId()));
StorageDomainManagementParameter parameter = new StorageDomainManagementParameter(storageDomain);
parameter.setVdsId(host.getId());
parameters.add(parameter);
IFrontendActionAsyncCallback callback1 = new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
StorageListModel storageListModel = (StorageListModel) result.getState();
VdcReturnValueBase vdcReturnValueBase = result.getReturnValue();
storageListModel.storageDomain.setStorage((String) vdcReturnValueBase.getActionReturnValue());
storageListModel.connection.setid((String)vdcReturnValueBase.getActionReturnValue());
}
};
IFrontendActionAsyncCallback callback2 = new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
StorageListModel storageListModel = (StorageListModel) result.getState();
VdcReturnValueBase vdcReturnValueBase = result.getReturnValue();
storageListModel.storageId = (Guid) vdcReturnValueBase.getActionReturnValue();
// Attach storage to data center as necessary.
StorageModel storageModel = (StorageModel) storageListModel.getWindow();
StoragePool dataCenter = (StoragePool) storageModel.getDataCenter().getSelectedItem();
if (!dataCenter.getId().equals(StorageModel.UnassignedDataCenterId)) {
storageListModel.attachStorageToDataCenter(storageListModel.storageId, dataCenter.getId());
}
storageListModel.onFinish(storageListModel.context, true, storageListModel.storageModel);
}
};
IFrontendActionAsyncCallback failureCallback = new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
StorageListModel storageListModel = (StorageListModel) result.getState();
storageListModel.cleanConnection(storageListModel.connection, storageListModel.hostId);
storageListModel.onFinish(storageListModel.context, false, storageListModel.storageModel);
}
};
Frontend.RunMultipleActions(actionTypes,
parameters,
new ArrayList<IFrontendActionAsyncCallback>(Arrays.asList(new IFrontendActionAsyncCallback[] {
callback1, callback2 })),
failureCallback,
this);
}
private void saveGlusterStorage(TaskContext context) {
this.context = context;
StorageDomain selectedItem = (StorageDomain) getSelectedItem();
StorageModel model = (StorageModel) getWindow();
boolean isNew = model.getStorage() == null;
storageModel = model.getSelectedItem();
GlusterStorageModel glusterModel = (GlusterStorageModel) storageModel;
path = (String) glusterModel.getPath().getEntity();
storageDomain = isNew ? new StorageDomainStatic() : (StorageDomainStatic) Cloner.clone(selectedItem.getStorageStaticData());
storageDomain.setStorageType(isNew ? storageModel.getType() : storageDomain.getStorageType());
storageDomain.setStorageDomainType(isNew ? storageModel.getRole() : storageDomain.getStorageDomainType());
storageDomain.setStorageName((String) model.getName().getEntity());
storageDomain.setStorageFormat((StorageFormatType) model.getFormat().getSelectedItem());
if (isNew) {
AsyncDataProvider.getStorageDomainsByConnection(new AsyncQuery(this, new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
StorageListModel storageListModel = (StorageListModel) target;
ArrayList<StorageDomain> storages = (ArrayList<StorageDomain>) returnValue;
if (storages != null && storages.size() > 0) {
handleDomainAlreadyExists(storageListModel, storages);
} else {
storageListModel.saveNewGlusterStorage();
}
}
}), null, path);
} else {
updateStorageDomain();
}
}
public void saveNewGlusterStorage() {
StorageModel model = (StorageModel) getWindow();
GlusterStorageModel glusterModel = (GlusterStorageModel) model.getSelectedItem();
VDS host = (VDS) model.getHost().getSelectedItem();
hostId = host.getId();
// Create storage connection.
StorageServerConnections connection = new StorageServerConnections();
connection.setconnection(path);
connection.setstorage_type(glusterModel.getType());
connection.setVfsType((String) glusterModel.getVfsType().getEntity());
connection.setMountOptions((String) glusterModel.getMountOptions().getEntity());
this.connection = connection;
ArrayList<VdcActionType> actionTypes = new ArrayList<VdcActionType>();
ArrayList<VdcActionParametersBase> parameters = new ArrayList<VdcActionParametersBase>();
actionTypes.add(VdcActionType.AddStorageServerConnection);
actionTypes.add(VdcActionType.AddGlusterFsStorageDomain);
parameters.add(new StorageServerConnectionParametersBase(this.connection, host.getId()));
StorageDomainManagementParameter parameter = new StorageDomainManagementParameter(storageDomain);
parameter.setVdsId(host.getId());
parameters.add(parameter);
IFrontendActionAsyncCallback callback1 = new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
StorageListModel storageListModel = (StorageListModel) result.getState();
VdcReturnValueBase vdcReturnValueBase = result.getReturnValue();
storageListModel.storageDomain.setStorage((String) vdcReturnValueBase.getActionReturnValue());
}
};
IFrontendActionAsyncCallback callback2 = new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
StorageListModel storageListModel = (StorageListModel) result.getState();
VdcReturnValueBase vdcReturnValueBase = result.getReturnValue();
storageListModel.storageId = (Guid) vdcReturnValueBase.getActionReturnValue();
// Attach storage to data center as necessary.
StorageModel storageModel = (StorageModel) storageListModel.getWindow();
StoragePool dataCenter = (StoragePool) storageModel.getDataCenter().getSelectedItem();
if (!dataCenter.getId().equals(StorageModel.UnassignedDataCenterId)) {
storageListModel.attachStorageToDataCenter(storageListModel.storageId, dataCenter.getId());
}
storageListModel.onFinish(storageListModel.context, true, storageListModel.storageModel);
}
};
IFrontendActionAsyncCallback failureCallback = new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
StorageListModel storageListModel = (StorageListModel) result.getState();
storageListModel.cleanConnection(storageListModel.connection, storageListModel.hostId);
storageListModel.onFinish(storageListModel.context, false, storageListModel.storageModel);
}
};
Frontend.RunMultipleActions(actionTypes,
parameters,
new ArrayList<IFrontendActionAsyncCallback>(Arrays.asList(new IFrontendActionAsyncCallback[] {
callback1, callback2 })),
failureCallback,
this);
}
private void saveNfsStorage(TaskContext context)
{
this.context = context;
StorageDomain selectedItem = (StorageDomain) getSelectedItem();
StorageModel model = (StorageModel) getWindow();
boolean isNew = model.getStorage() == null;
storageModel = model.getSelectedItem();
NfsStorageModel nfsModel = (NfsStorageModel) storageModel;
path = (String) nfsModel.getPath().getEntity();
storageDomain =
isNew ? new StorageDomainStatic()
: (StorageDomainStatic) Cloner.clone(selectedItem.getStorageStaticData());
storageDomain.setStorageType(isNew ? storageModel.getType() : storageDomain.getStorageType());
storageDomain.setStorageDomainType(isNew ? storageModel.getRole() : storageDomain.getStorageDomainType());
storageDomain.setStorageName((String) model.getName().getEntity());
storageDomain.setDescription((String) model.getDescription().getEntity());
storageDomain.setComment((String) model.getComment().getEntity());
storageDomain.setStorageFormat((StorageFormatType) model.getFormat().getSelectedItem());
if (isNew)
{
AsyncDataProvider.getStorageDomainsByConnection(new AsyncQuery(this, new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
StorageListModel storageListModel = (StorageListModel) target;
ArrayList<StorageDomain> storages = (ArrayList<StorageDomain>) returnValue;
if (storages != null && storages.size() > 0) {
handleDomainAlreadyExists(storageListModel, storages);
} else {
storageListModel.saveNewNfsStorage();
}
}
}), null, path);
}
else
{
StorageDomain storageDomain = (StorageDomain) getSelectedItem();
if (isPathEditable(storageDomain)) {
updatePath();
}
else {
updateStorageDomain();
}
}
}
private void updatePath() {
StorageModel model = (StorageModel) getWindow();
VDS host = (VDS) model.getHost().getSelectedItem();
Guid hostId = Guid.Empty;
if (host != null) {
hostId = host.getId();
}
IStorageModel storageModel = model.getSelectedItem();
connection = new StorageServerConnections();
connection.setid(storageDomain.getStorage());
connection.setconnection(path);
connection.setstorage_type(storageModel.getType());
if (storageModel.getType().equals(StorageType.NFS)) {
updateNFSProperties(storageModel);
}
else if (storageModel.getType().equals(StorageType.POSIXFS)) {
updatePosixProperties(storageModel);
}
StorageServerConnectionParametersBase parameters =
new StorageServerConnectionParametersBase(connection, hostId);
Frontend.RunAction(VdcActionType.UpdateStorageServerConnection, parameters,
new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
StorageListModel storageListModel = (StorageListModel) result.getState();
storageListModel.onFinish(storageListModel.context, true, storageListModel.storageModel);
}
}, this);
}
private void updateNFSProperties(IStorageModel storageModel) {
NfsStorageModel nfsModel = (NfsStorageModel) storageModel;
if ((Boolean) nfsModel.getOverride().getEntity()) {
connection.setNfsVersion((NfsVersion) ((EntityModel) nfsModel.getVersion().getSelectedItem()).getEntity());
connection.setNfsRetrans(nfsModel.getRetransmissions().asConvertible().nullableShort());
connection.setNfsTimeo(nfsModel.getTimeout().asConvertible().nullableShort());
}
}
private void updatePosixProperties(IStorageModel storageModel) {
PosixStorageModel posixModel = (PosixStorageModel) storageModel;
connection.setVfsType(posixModel.getVfsType().getEntity().toString());
if (posixModel.getMountOptions().getEntity() != null) {
connection.setMountOptions(posixModel.getMountOptions().getEntity().toString());
}
}
public void saveNewNfsStorage()
{
StorageModel model = (StorageModel) getWindow();
NfsStorageModel nfsModel = (NfsStorageModel) model.getSelectedItem();
VDS host = (VDS) model.getHost().getSelectedItem();
hostId = host.getId();
// Create storage connection.
StorageServerConnections tempVar = new StorageServerConnections();
tempVar.setconnection(path);
tempVar.setstorage_type(nfsModel.getType());
if ((Boolean) nfsModel.getOverride().getEntity()) {
tempVar.setNfsVersion((NfsVersion) ((EntityModel) nfsModel.getVersion().getSelectedItem()).getEntity());
tempVar.setNfsRetrans(nfsModel.getRetransmissions().asConvertible().nullableShort());
tempVar.setNfsTimeo(nfsModel.getTimeout().asConvertible().nullableShort());
}
connection = tempVar;
ArrayList<VdcActionType> actionTypes = new ArrayList<VdcActionType>();
ArrayList<VdcActionParametersBase> parameters = new ArrayList<VdcActionParametersBase>();
actionTypes.add(VdcActionType.AddStorageServerConnection);
actionTypes.add(VdcActionType.AddNFSStorageDomain);
actionTypes.add(VdcActionType.DisconnectStorageServerConnection);
parameters.add(new StorageServerConnectionParametersBase(connection, host.getId()));
StorageDomainManagementParameter tempVar2 = new StorageDomainManagementParameter(storageDomain);
tempVar2.setVdsId(host.getId());
parameters.add(tempVar2);
parameters.add(new StorageServerConnectionParametersBase(connection, host.getId()));
IFrontendActionAsyncCallback callback1 = new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
StorageListModel storageListModel = (StorageListModel) result.getState();
VdcReturnValueBase vdcReturnValueBase = result.getReturnValue();
storageListModel.storageDomain.setStorage((String) vdcReturnValueBase.getActionReturnValue());
storageListModel.connection.setid((String)vdcReturnValueBase.getActionReturnValue());
}
};
IFrontendActionAsyncCallback callback2 = new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
StorageListModel storageListModel = (StorageListModel) result.getState();
VdcReturnValueBase vdcReturnValueBase = result.getReturnValue();
storageListModel.storageId = (Guid) vdcReturnValueBase.getActionReturnValue();
}
};
IFrontendActionAsyncCallback callback3 = new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
StorageListModel storageListModel = (StorageListModel) result.getState();
StorageModel storageModel = (StorageModel) storageListModel.getWindow();
// Attach storage to data center as necessary.
StoragePool dataCenter = (StoragePool) storageModel.getDataCenter().getSelectedItem();
if (!dataCenter.getId().equals(StorageModel.UnassignedDataCenterId))
{
storageListModel.attachStorageToDataCenter(storageListModel.storageId, dataCenter.getId());
}
storageListModel.onFinish(storageListModel.context, true, storageListModel.storageModel);
}
};
IFrontendActionAsyncCallback failureCallback = new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
StorageListModel storageListModel = (StorageListModel) result.getState();
storageListModel.cleanConnection(storageListModel.connection, storageListModel.hostId);
storageListModel.onFinish(storageListModel.context, false, storageListModel.storageModel);
}
};
Frontend.RunMultipleActions(actionTypes,
parameters,
new ArrayList<IFrontendActionAsyncCallback>(Arrays.asList(new IFrontendActionAsyncCallback[] {
callback1, callback2, callback3 })),
failureCallback,
this);
}
public void saveNewSanStorage()
{
StorageModel model = (StorageModel) getWindow();
SanStorageModel sanModel = (SanStorageModel) model.getSelectedItem();
VDS host = (VDS) model.getHost().getSelectedItem();
boolean force = sanModel.isForce();
ArrayList<String> lunIds = new ArrayList<String>();
for (LunModel lun : sanModel.getAddedLuns())
{
lunIds.add(lun.getLunId());
}
AddSANStorageDomainParameters params = new AddSANStorageDomainParameters(storageDomain);
params.setVdsId(host.getId());
params.setLunIds(lunIds);
params.setForce(force);
Frontend.RunAction(VdcActionType.AddSANStorageDomain, params,
new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
StorageListModel storageListModel = (StorageListModel) result.getState();
StorageModel storageModel = (StorageModel) storageListModel.getWindow();
storageListModel.storageModel = storageModel.getSelectedItem();
if (!result.getReturnValue().getSucceeded()) {
storageListModel.onFinish(storageListModel.context, false, storageListModel.storageModel);
return;
}
StoragePool dataCenter = (StoragePool) storageModel.getDataCenter().getSelectedItem();
if (!dataCenter.getId().equals(StorageModel.UnassignedDataCenterId)) {
VdcReturnValueBase returnValue = result.getReturnValue();
Guid storageId = (Guid) returnValue.getActionReturnValue();
storageListModel.attachStorageToDataCenter(storageId, dataCenter.getId());
}
storageListModel.onFinish(storageListModel.context, true, storageListModel.storageModel);
}
}, this);
}
private void saveLocalStorage(TaskContext context)
{
this.context = context;
StorageDomain selectedItem = (StorageDomain) getSelectedItem();
StorageModel model = (StorageModel) getWindow();
VDS host = (VDS) model.getHost().getSelectedItem();
boolean isNew = model.getStorage() == null;
storageModel = model.getSelectedItem();
LocalStorageModel localModel = (LocalStorageModel) storageModel;
path = (String) localModel.getPath().getEntity();
storageDomain =
isNew ? new StorageDomainStatic()
: (StorageDomainStatic) Cloner.clone(selectedItem.getStorageStaticData());
storageDomain.setStorageType(isNew ? storageModel.getType() : storageDomain.getStorageType());
storageDomain.setStorageDomainType(isNew ? storageModel.getRole() : storageDomain.getStorageDomainType());
storageDomain.setStorageName((String) model.getName().getEntity());
storageDomain.setDescription((String) model.getDescription().getEntity());
storageDomain.setComment((String) model.getComment().getEntity());
if (isNew)
{
AsyncDataProvider.getStorageDomainsByConnection(new AsyncQuery(this, new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
StorageListModel storageListModel = (StorageListModel) target;
ArrayList<StorageDomain> storages = (ArrayList<StorageDomain>) returnValue;
if (storages != null && storages.size() > 0) {
handleDomainAlreadyExists(storageListModel, storages);
} else {
storageListModel.saveNewLocalStorage();
}
}
}), host.getStoragePoolId(), path);
}
else
{
StorageDomain storageDomain = (StorageDomain) getSelectedItem();
if (isPathEditable(storageDomain)) {
updatePath();
}
else {
updateStorageDomain();
}
}
}
private void handleDomainAlreadyExists(StorageListModel storageListModel, ArrayList<StorageDomain> storages) {
String storageName = storages.get(0).getStorageName();
onFinish(storageListModel.context,
false,
storageListModel.storageModel,
ConstantsManager.getInstance().getMessages().createFailedDomainAlreadyExistStorageMsg(storageName));
}
public void saveNewLocalStorage()
{
StorageModel model = (StorageModel) getWindow();
LocalStorageModel localModel = (LocalStorageModel) model.getSelectedItem();
VDS host = (VDS) model.getHost().getSelectedItem();
hostId = host.getId();
// Create storage connection.
StorageServerConnections tempVar = new StorageServerConnections();
tempVar.setconnection(path);
tempVar.setstorage_type(localModel.getType());
connection = tempVar;
ArrayList<VdcActionType> actionTypes = new ArrayList<VdcActionType>();
ArrayList<VdcActionParametersBase> parameters = new ArrayList<VdcActionParametersBase>();
actionTypes.add(VdcActionType.AddStorageServerConnection);
actionTypes.add(VdcActionType.AddLocalStorageDomain);
parameters.add(new StorageServerConnectionParametersBase(connection, host.getId()));
StorageDomainManagementParameter tempVar2 = new StorageDomainManagementParameter(storageDomain);
tempVar2.setVdsId(host.getId());
parameters.add(tempVar2);
IFrontendActionAsyncCallback callback1 = new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
StorageListModel storageListModel = (StorageListModel) result.getState();
storageListModel.removeConnection = true;
VdcReturnValueBase vdcReturnValueBase = result.getReturnValue();
storageListModel.storageDomain.setStorage((String) vdcReturnValueBase.getActionReturnValue());
storageListModel.connection.setid((String)vdcReturnValueBase.getActionReturnValue());
}
};
IFrontendActionAsyncCallback callback2 = new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
StorageListModel storageListModel = (StorageListModel) result.getState();
storageListModel.removeConnection = false;
storageListModel.onFinish(storageListModel.context, true, storageListModel.storageModel);
}
};
IFrontendActionAsyncCallback failureCallback = new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
StorageListModel storageListModel = (StorageListModel) result.getState();
if (storageListModel.removeConnection)
{
storageListModel.cleanConnection(storageListModel.connection, storageListModel.hostId);
storageListModel.removeConnection = false;
}
storageListModel.onFinish(storageListModel.context, false, storageListModel.storageModel);
}
};
Frontend.RunMultipleActions(actionTypes,
parameters,
new ArrayList<IFrontendActionAsyncCallback>(Arrays.asList(new IFrontendActionAsyncCallback[] {
callback1, callback2 })),
failureCallback,
this);
}
public void onFinish(TaskContext context, boolean isSucceeded, IStorageModel model)
{
onFinish(context, isSucceeded, model, null);
}
public void onFinish(TaskContext context, boolean isSucceeded, IStorageModel model, String message)
{
context.InvokeUIThread(this,
new ArrayList<Object>(Arrays.asList(new Object[] { "Finish", isSucceeded, model, //$NON-NLS-1$
message })));
}
private void saveSanStorage(TaskContext context)
{
this.context = context;
StorageModel model = (StorageModel) getWindow();
SanStorageModel sanModel = (SanStorageModel) model.getSelectedItem();
StorageDomain storage = (StorageDomain) getSelectedItem();
boolean isNew = model.getStorage() == null;
storageDomain =
isNew ? new StorageDomainStatic()
: (StorageDomainStatic) Cloner.clone(storage.getStorageStaticData());
storageDomain.setStorageType(isNew ? sanModel.getType() : storageDomain.getStorageType());
storageDomain.setStorageDomainType(isNew ? sanModel.getRole() : storageDomain.getStorageDomainType());
storageDomain.setStorageFormat(isNew ? (StorageFormatType) sanModel.getContainer()
.getFormat()
.getSelectedItem() : storageDomain.getStorageFormat());
storageDomain.setStorageName((String) model.getName().getEntity());
storageDomain.setDescription((String) model.getDescription().getEntity());
storageDomain.setComment((String) model.getComment().getEntity());
if (isNew)
{
saveNewSanStorage();
}
else
{
Frontend.RunAction(VdcActionType.UpdateStorageDomain, new StorageDomainManagementParameter(storageDomain), new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
StorageListModel storageListModel = (StorageListModel) result.getState();
StorageModel storageModel = (StorageModel) getWindow();
SanStorageModel sanStorageModel = (SanStorageModel) storageModel.getSelectedItem();
boolean force = sanStorageModel.isForce();
StorageDomain storageDomain1 = (StorageDomain) storageListModel.getSelectedItem();
ArrayList<String> lunIds = new ArrayList<String>();
for (LunModel lun : sanStorageModel.getAddedLuns()) {
lunIds.add(lun.getLunId());
}
if (lunIds.size() > 0) {
Frontend.RunAction(VdcActionType.ExtendSANStorageDomain,
new ExtendSANStorageDomainParameters(storageDomain1.getId(), lunIds, force),
null, this);
}
storageListModel.onFinish(storageListModel.context, true, storageListModel.storageModel);
}
}, this);
}
}
private void attachStorageToDataCenter(Guid storageId, Guid dataCenterId)
{
Frontend.RunAction(VdcActionType.AttachStorageDomainToPool, new StorageDomainPoolParametersBase(storageId,
dataCenterId), null, this);
}
private void importFileStorage(TaskContext context)
{
this.context = context;
ArrayList<Object> data = (ArrayList<Object>) context.getState();
StorageModel model = (StorageModel) getWindow();
storageModel = model.getSelectedItem();
hostId = (Guid) data.get(1);
path = (String) data.get(2);
domainType = (StorageDomainType) data.get(3);
storageType = (StorageType) data.get(4);
importFileStorageInit();
}
public void importFileStorageInit()
{
if (fileConnection != null)
{
// Clean nfs connection
Frontend.RunAction(VdcActionType.DisconnectStorageServerConnection,
new StorageServerConnectionParametersBase(fileConnection, hostId),
new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
StorageListModel storageListModel = (StorageListModel) result.getState();
VdcReturnValueBase returnVal = result.getReturnValue();
boolean success = returnVal != null && returnVal.getSucceeded();
if (success) {
storageListModel.fileConnection = null;
}
storageListModel.importFileStoragePostInit();
}
},
this);
}
else
{
importFileStoragePostInit();
}
}
public void importFileStoragePostInit()
{
// Check storage domain existence
AsyncDataProvider.getStorageDomainsByConnection(new AsyncQuery(this, new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
StorageListModel storageListModel = (StorageListModel) target;
ArrayList<StorageDomain> storages = (ArrayList<StorageDomain>) returnValue;
if (storages != null && storages.size() > 0) {
String storageName = storages.get(0).getStorageName();
onFinish(storageListModel.context,
false,
storageListModel.storageModel,
ConstantsManager.getInstance().getMessages().importFailedDomainAlreadyExistStorageMsg(storageName));
} else {
StorageServerConnections tempVar = new StorageServerConnections();
storageModel = storageListModel.storageModel;
tempVar.setconnection(storageListModel.path);
tempVar.setstorage_type(storageListModel.storageType);
if (storageModel instanceof NfsStorageModel) {
NfsStorageModel nfsModel = (NfsStorageModel) storageModel;
if ((Boolean) nfsModel.getOverride().getEntity()) {
tempVar.setNfsVersion((NfsVersion) ((EntityModel) nfsModel.getVersion().getSelectedItem()).getEntity());
tempVar.setNfsRetrans(nfsModel.getRetransmissions().asConvertible().nullableShort());
tempVar.setNfsTimeo(nfsModel.getTimeout().asConvertible().nullableShort());
}
}
if (storageModel instanceof PosixStorageModel) {
PosixStorageModel posixModel = (PosixStorageModel) storageModel;
tempVar.setVfsType((String) posixModel.getVfsType().getEntity());
tempVar.setMountOptions((String) posixModel.getMountOptions().getEntity());
}
storageListModel.fileConnection = tempVar;
storageListModel.importFileStorageConnect();
}
}
}), null, path);
}
public void importFileStorageConnect()
{
Frontend.RunAction(VdcActionType.AddStorageServerConnection, new StorageServerConnectionParametersBase(fileConnection, hostId),
new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
StorageListModel storageListModel = (StorageListModel) result.getState();
VdcReturnValueBase returnVal = result.getReturnValue();
boolean success = returnVal != null && returnVal.getSucceeded();
if (success)
{
AsyncDataProvider.getExistingStorageDomainList(new AsyncQuery(storageListModel,
new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
StorageListModel storageListModel1 = (StorageListModel) target;
ArrayList<StorageDomain> domains = (ArrayList<StorageDomain>) returnValue;
if (domains != null)
{
if (domains.isEmpty())
{
postImportFileStorage(storageListModel1.context,
false,
storageListModel1.storageModel,
ConstantsManager.getInstance()
.getConstants()
.thereIsNoStorageDomainUnderTheSpecifiedPathMsg());
}
else
{
storageListModel1.importFileStorageAddDomain(domains);
}
}
else
{
postImportFileStorage(storageListModel1.context,
false,
storageListModel1.storageModel,
ConstantsManager.getInstance()
.getConstants()
.failedToRetrieveExistingStorageDomainInformationMsg());
}
}
}),
hostId,
domainType,
storageType,
path);
}
else
{
postImportFileStorage(storageListModel.context,
false,
storageListModel.storageModel,
ConstantsManager.getInstance()
.getConstants()
.failedToRetrieveExistingStorageDomainInformationMsg());
}
}
},
this);
}
public void importFileStorageAddDomain(ArrayList<StorageDomain> domains)
{
StorageDomain sdToAdd = Linq.firstOrDefault(domains);
StorageDomainStatic sdsToAdd = sdToAdd.getStorageStaticData();
StorageDomainManagementParameter params = new StorageDomainManagementParameter(sdsToAdd);
params.setVdsId(hostId);
Frontend.RunAction(VdcActionType.AddExistingFileStorageDomain, params, new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
Object[] array = (Object[]) result.getState();
StorageListModel storageListModel = (StorageListModel) array[0];
StorageDomain sdToAdd1 = (StorageDomain) array[1];
VdcReturnValueBase returnVal = result.getReturnValue();
boolean success = returnVal != null && returnVal.getSucceeded();
if (success) {
StorageModel model = (StorageModel) storageListModel.getWindow();
StoragePool dataCenter = (StoragePool) model.getDataCenter().getSelectedItem();
if (!dataCenter.getId().equals(StorageModel.UnassignedDataCenterId)) {
storageListModel.attachStorageToDataCenter(sdToAdd1.getId(), dataCenter.getId());
}
postImportFileStorage(storageListModel.context, true, storageListModel.storageModel, null);
} else {
postImportFileStorage(storageListModel.context, false, storageListModel.storageModel, ""); //$NON-NLS-1$
}
}
}, new Object[] {this, sdToAdd});
}
public void postImportFileStorage(TaskContext context, boolean isSucceeded, IStorageModel model, String message)
{
Frontend.RunAction(VdcActionType.DisconnectStorageServerConnection,
new StorageServerConnectionParametersBase(fileConnection, hostId),
new IFrontendActionAsyncCallback() {
@Override
public void executed(FrontendActionAsyncResult result) {
VdcReturnValueBase returnValue = result.getReturnValue();
boolean success = returnValue != null && returnValue.getSucceeded();
if (success) {
fileConnection = null;
}
Object[] array = (Object[]) result.getState();
onFinish((TaskContext) array[0],
(Boolean) array[1],
(IStorageModel) array[2],
(String) array[3]);
}
},
new Object[] {context, isSucceeded, model, message});
}
@Override
public void run(TaskContext context)
{
ArrayList<Object> data = (ArrayList<Object>) context.getState();
String key = (String) data.get(0);
if (StringHelper.stringsEqual(key, "SaveNfs")) //$NON-NLS-1$
{
saveNfsStorage(context);
}
else if (StringHelper.stringsEqual(key, "SaveLocal")) //$NON-NLS-1$
{
saveLocalStorage(context);
}
else if (StringHelper.stringsEqual(key, "SavePosix")) //$NON-NLS-1$
{
savePosixStorage(context);
}
else if (StringHelper.stringsEqual(key, "SaveGluster")) //$NON-NLS-1$
{
saveGlusterStorage(context);
}
else if (StringHelper.stringsEqual(key, "SaveSan")) //$NON-NLS-1$
{
saveSanStorage(context);
}
else if (StringHelper.stringsEqual(key, "ImportFile")) //$NON-NLS-1$
{
importFileStorage(context);
}
else if (StringHelper.stringsEqual(key, "Finish")) //$NON-NLS-1$
{
getWindow().stopProgress();
if ((Boolean) data.get(1))
{
cancel();
}
else
{
((Model) data.get(2)).setMessage((String) data.get(3));
}
}
}
private SystemTreeItemModel systemTreeSelectedItem;
@Override
public SystemTreeItemModel getSystemTreeSelectedItem()
{
return systemTreeSelectedItem;
}
@Override
public void setSystemTreeSelectedItem(SystemTreeItemModel value)
{
if (systemTreeSelectedItem != value)
{
systemTreeSelectedItem = value;
onSystemTreeSelectedItemChanged();
}
}
private void onSystemTreeSelectedItemChanged()
{
updateActionAvailability();
}
@Override
protected String getListName() {
return "StorageListModel"; //$NON-NLS-1$
}
@Override
protected void openReport() {
final ReportModel reportModel = super.createReportModel();
List<StorageDomain> items =
getSelectedItems() != null && getSelectedItem() != null ? getSelectedItems()
: new ArrayList<StorageDomain>();
StorageDomain storage = items.iterator().next();
AsyncDataProvider.getDataCentersByStorageDomain(new AsyncQuery(this, new INewAsyncCallback() {
@Override
public void onSuccess(Object target, Object returnValue) {
List<StoragePool> dataCenters = (List<StoragePool>) returnValue;
for (StoragePool dataCenter : dataCenters) {
reportModel.addDataCenterID(dataCenter.getId().toString());
}
if (reportModel == null) {
return;
}
setWidgetModel(reportModel);
}
}), storage.getId());
}
@Override
protected void setReportModelResourceId(ReportModel reportModel, String idParamName, boolean isMultiple) {
ArrayList<StorageDomain> items =
getSelectedItems() != null ? Linq.<StorageDomain> cast(getSelectedItems())
: new ArrayList<StorageDomain>();
if (idParamName != null) {
for (StorageDomain item : items) {
if (isMultiple) {
reportModel.addResourceId(idParamName, item.getId().toString());
} else {
reportModel.setResourceId(idParamName, item.getId().toString());
}
}
}
}
private UICommand createCancelCommand(String commandName) {
UICommand command;
command = new UICommand(commandName, this);
command.setTitle(ConstantsManager.getInstance().getConstants().cancel());
command.setIsCancel(true);
return command;
}
private UICommand createOKCommand(String commandName) {
UICommand command = new UICommand(commandName, this);
command.setTitle(ConstantsManager.getInstance().getConstants().ok());
command.setIsDefault(true);
return command;
}
} |
package org.ovirt.engine.ui.webadmin.section.main.view.tab;
import org.ovirt.engine.core.common.businessentities.Disk;
import org.ovirt.engine.core.common.businessentities.Disk.DiskStorageType;
import org.ovirt.engine.core.compat.Event;
import org.ovirt.engine.core.compat.EventArgs;
import org.ovirt.engine.core.compat.IEventListener;
import org.ovirt.engine.ui.common.idhandler.ElementIdHandler;
import org.ovirt.engine.ui.common.uicommon.model.CommonModelManager;
import org.ovirt.engine.ui.common.uicommon.model.MainModelProvider;
import org.ovirt.engine.ui.common.widget.uicommon.disks.DisksViewColumns;
import org.ovirt.engine.ui.common.widget.uicommon.disks.DisksViewRadioGroup;
import org.ovirt.engine.ui.uicommonweb.UICommand;
import org.ovirt.engine.ui.uicommonweb.models.CommonModel;
import org.ovirt.engine.ui.uicommonweb.models.EntityModel;
import org.ovirt.engine.ui.uicommonweb.models.disks.DiskListModel;
import org.ovirt.engine.ui.webadmin.ApplicationConstants;
import org.ovirt.engine.ui.webadmin.section.main.presenter.tab.MainTabDiskPresenter;
import org.ovirt.engine.ui.webadmin.section.main.view.AbstractMainTabWithDetailsTableView;
import org.ovirt.engine.ui.webadmin.widget.action.WebAdminButtonDefinition;
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.inject.Inject;
public class MainTabDiskView extends AbstractMainTabWithDetailsTableView<Disk, DiskListModel> implements MainTabDiskPresenter.ViewDef {
interface ViewIdHandler extends ElementIdHandler<MainTabDiskView> {
ViewIdHandler idHandler = GWT.create(ViewIdHandler.class);
}
@UiField
SimplePanel tablePanel;
private final ApplicationConstants constants;
private final CommonModel commonModel;
private DisksViewRadioGroup disksViewRadioGroup;
@Inject
public MainTabDiskView(MainModelProvider<Disk, DiskListModel> modelProvider, ApplicationConstants constants) {
super(modelProvider);
this.constants = constants;
this.commonModel = CommonModelManager.instance();
ViewIdHandler.idHandler.generateAndSetIds(this);
initTableColumns();
initTableButtons();
initTableOverhead();
initWidget(getTable());
modelProvider.getModel().getDiskViewType().getEntityChangedEvent().addListener(new IEventListener() {
@Override
public void eventRaised(Event ev, Object sender, EventArgs args) {
EntityModel diskViewType = (EntityModel) sender;
disksViewRadioGroup.setDiskStorageType((DiskStorageType) diskViewType.getEntity());
onDiskViewTypeChanged();
}
});
}
final ClickHandler clickHandler = new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if (((RadioButton) event.getSource()).getValue()) {
getMainModel().getDiskViewType().setEntity(disksViewRadioGroup.getDiskStorageType());
}
}
};
void onDiskViewTypeChanged() {
boolean all = disksViewRadioGroup.getAllButton().getValue();
boolean images = disksViewRadioGroup.getImagesButton().getValue();
boolean luns = disksViewRadioGroup.getLunsButton().getValue();
searchByDiskViewType(disksViewRadioGroup.getDiskStorageType());
getTable().ensureColumnPresent(
DisksViewColumns.aliasColumn, constants.aliasDisk(), all || images || luns,
"150px"); //$NON-NLS-1$
getTable().ensureColumnPresent(
DisksViewColumns.idColumn, constants.idDisk(), all || images || luns,
"150px"); //$NON-NLS-1$
getTable().ensureColumnPresent(
DisksViewColumns.bootableDiskColumn,
DisksViewColumns.bootableDiskColumn.getHeaderHtml(), all || images || luns, "30px"); //$NON-NLS-1$
getTable().ensureColumnPresent(
DisksViewColumns.shareableDiskColumn,
DisksViewColumns.shareableDiskColumn.getHeaderHtml(), all || images || luns, "30px"); //$NON-NLS-1$
getTable().ensureColumnPresent(
DisksViewColumns.lunDiskColumn,
DisksViewColumns.lunDiskColumn.getHeaderHtml(), all, "30px"); //$NON-NLS-1$
getTable().ensureColumnPresent(
DisksViewColumns.diskContainersIconColumn, "", all || images || luns, //$NON-NLS-1$
"30px"); //$NON-NLS-1$
getTable().ensureColumnPresent(
DisksViewColumns.diskContainersColumn, constants.attachedToDisk(), all || images || luns,
"125px"); //$NON-NLS-1$
getTable().ensureColumnPresent(
DisksViewColumns.storageDomainsColumn, constants.storageDomainsDisk(), images,
"125px"); //$NON-NLS-1$
getTable().ensureColumnPresent(
DisksViewColumns.sizeColumn, constants.provisionedSizeDisk(), all || images || luns,
"110px"); //$NON-NLS-1$
getTable().ensureColumnPresent(
DisksViewColumns.allocationColumn, constants.allocationDisk(), images,
"100px"); //$NON-NLS-1$
getTable().ensureColumnPresent(
DisksViewColumns.dateCreatedColumn, constants.creationDateDisk(), images,
"150px"); //$NON-NLS-1$
getTable().ensureColumnPresent(
DisksViewColumns.statusColumn, constants.statusDisk(), images,
"80px"); //$NON-NLS-1$
getTable().ensureColumnPresent(
DisksViewColumns.lunIdColumn, constants.lunIdSanStorage(), luns,
"100px"); //$NON-NLS-1$
getTable().ensureColumnPresent(
DisksViewColumns.lunSerialColumn, constants.serialSanStorage(), luns,
"100px"); //$NON-NLS-1$
getTable().ensureColumnPresent(
DisksViewColumns.lunVendorIdColumn, constants.vendorIdSanStorage(), luns,
"100px"); //$NON-NLS-1$
getTable().ensureColumnPresent(
DisksViewColumns.lunProductIdColumn, constants.productIdSanStorage(), luns,
"100px"); //$NON-NLS-1$
getTable().ensureColumnPresent(
DisksViewColumns.descriptionColumn, constants.descriptionDisk(), all || images || luns,
"100px"); //$NON-NLS-1$
}
void initTableColumns() {
getTable().enableColumnResizing();
}
void initTableOverhead() {
disksViewRadioGroup = new DisksViewRadioGroup();
disksViewRadioGroup.setClickHandler(clickHandler);
getTable().setTableOverhead(disksViewRadioGroup);
getTable().setTableTopMargin(20);
}
void initTableButtons() {
getTable().addActionButton(new WebAdminButtonDefinition<Disk>(constants.addDisk()) {
@Override
protected UICommand resolveCommand() {
return getMainModel().getNewCommand();
}
});
getTable().addActionButton(new WebAdminButtonDefinition<Disk>(constants.removeDisk()) {
@Override
protected UICommand resolveCommand() {
return getMainModel().getRemoveCommand();
}
});
getTable().addActionButton(new WebAdminButtonDefinition<Disk>(constants.moveDisk()) {
@Override
protected UICommand resolveCommand() {
return getMainModel().getMoveCommand();
}
});
getTable().addActionButton(new WebAdminButtonDefinition<Disk>(constants.copyDisk()) {
@Override
protected UICommand resolveCommand() {
return getMainModel().getCopyCommand();
}
});
getTable().addActionButton(new WebAdminButtonDefinition<Disk>(constants.assignQuota()) {
@Override
protected UICommand resolveCommand() {
return getMainModel().getChangeQuotaCommand();
}
});
}
void searchByDiskViewType(Object diskViewType) {
final String disksSearchPrefix = "Disks:"; //$NON-NLS-1$
final String diskTypeSearchPrefix = "disk_type = "; //$NON-NLS-1$
final String searchConjunctionAnd = "and "; //$NON-NLS-1$
final String searchRegexDisksSearchPrefix = "^\\s*(disk(s)?\\s*(:)+)+\\s*"; //$NON-NLS-1$
final String searchRegexDiskTypeClause = "\\s*((and|or)\\s+)?disk_type\\s*=\\s*\\S+"; //$NON-NLS-1$
final String searchRegexStartConjunction = "^\\s*(and|or)\\s*"; //$NON-NLS-1$
final String searchRegexFlags = "ig"; //$NON-NLS-1$
final String space = " "; //$NON-NLS-1$
final String empty = ""; //$NON-NLS-1$
final String colon = ":"; //$NON-NLS-1$
RegExp searchPatternDisksSearchPrefix = RegExp.compile(searchRegexDisksSearchPrefix, searchRegexFlags);
RegExp searchPatternDiskTypeClause = RegExp.compile(searchRegexDiskTypeClause, searchRegexFlags);
RegExp searchPatternStartConjunction = RegExp.compile(searchRegexStartConjunction, searchRegexFlags);
String diskTypePostfix = diskViewType != null ?
((DiskStorageType) diskViewType).name().toLowerCase() + space : null;
String diskTypeClause = diskTypePostfix != null ?
diskTypeSearchPrefix + diskTypePostfix : empty;
String inputSearchString = commonModel.getSearchString().trim();
String inputSearchStringPrefix = commonModel.getSearchStringPrefix().trim();
if (!inputSearchString.isEmpty() && inputSearchStringPrefix.isEmpty()) {
int indexOfColon = inputSearchString.indexOf(colon);
inputSearchStringPrefix = inputSearchString.substring(0, indexOfColon + 1).trim();
inputSearchString = inputSearchString.substring(indexOfColon + 1).trim();
}
if (inputSearchStringPrefix.isEmpty()) {
inputSearchStringPrefix = disksSearchPrefix;
inputSearchString = empty;
}
String searchStringPrefixRaw = searchPatternDiskTypeClause
.replace(inputSearchStringPrefix, empty).trim();
String searchStringPrefix;
if (diskTypeClause.equals(empty)) {
searchStringPrefix = searchStringPrefixRaw + space;
}
else {
searchStringPrefix = searchStringPrefixRaw + space
+ (searchPatternDisksSearchPrefix.test(searchStringPrefixRaw) ? empty : searchConjunctionAnd)
+ diskTypeClause;
}
inputSearchString = searchPatternDiskTypeClause
.replace(inputSearchString, empty);
inputSearchString = searchPatternStartConjunction
.replace(inputSearchString, empty);
String searchString;
if (searchPatternDisksSearchPrefix.test(searchStringPrefix) || inputSearchString.isEmpty()) {
searchString = inputSearchString;
}
else {
searchString = searchConjunctionAnd + inputSearchString;
}
commonModel.setSearchStringPrefix(searchStringPrefix);
commonModel.setSearchString(searchString);
getTable().getSelectionModel().clear();
getMainModel().setItems(null);
getMainModel().setSearchString(commonModel.getEffectiveSearchString());
getMainModel().Search();
}
} |
package jkind.solvers.smtlib2;
import static java.util.stream.Collectors.toList;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.RecognitionException;
import jkind.JKindException;
import jkind.lustre.Function;
import jkind.lustre.NamedType;
import jkind.lustre.Type;
import jkind.lustre.VarDecl;
import jkind.sexp.Cons;
import jkind.sexp.Sexp;
import jkind.sexp.Symbol;
import jkind.solvers.Model;
import jkind.solvers.ProcessBasedSolver;
import jkind.solvers.Result;
import jkind.solvers.SatResult;
import jkind.solvers.SolverParserErrorListener;
import jkind.solvers.UnknownResult;
import jkind.solvers.UnsatResult;
import jkind.solvers.smtlib2.SmtLib2Parser.ModelContext;
import jkind.translation.Relation;
import jkind.util.SexpUtil;
import jkind.util.Util;
public abstract class SmtLib2Solver extends ProcessBasedSolver {
public SmtLib2Solver(String scratchBase) {
super(scratchBase);
}
@Override
public void assertSexp(Sexp sexp) {
send(new Cons("assert", sexp));
}
protected void send(Sexp sexp) {
send(Quoting.quoteSexp(sexp).toString());
}
protected void send(String str) {
scratch(str);
try {
toSolver.append(str);
toSolver.newLine();
toSolver.flush();
} catch (IOException e) {
throw new JKindException("Unable to write to " + getSolverName() + ", "
+ "probably due to internal JKind error", e);
}
}
public Symbol type(Type type) {
return new Symbol(Util.capitalize(Util.getName(type)));
}
@Override
public void define(VarDecl decl) {
varTypes.put(decl.id, decl.type);
send(new Cons("declare-fun", new Symbol(decl.id), new Symbol("()"), type(decl.type)));
}
@Override
public void declare(Function function) {
functions.add(function);
Symbol name = new Symbol(SexpUtil.encodeFunction(function.id));
List<Sexp> inputTypes = function.inputs.stream().map(vd -> type(vd.type)).collect(toList());
Sexp inputTypesDecl = inputTypes.isEmpty() ? new Symbol("()") : new Cons(inputTypes);
Symbol outputType = type(function.outputs.get(0).type);
send(new Cons("declare-fun", name, inputTypesDecl, outputType));
}
@Override
public void define(Relation relation) {
send(new Cons("define-fun", new Symbol(relation.getName()), inputs(relation.getInputs()), type(NamedType.BOOL),
relation.getBody()));
}
private Sexp inputs(List<VarDecl> inputs) {
List<Sexp> args = new ArrayList<>();
for (VarDecl vd : inputs) {
args.add(new Cons(vd.id, type(vd.type)));
}
return new Cons(args);
}
@Override
public Result query(Sexp sexp) {
Result result = null;
push();
assertSexp(new Cons("not", sexp));
send("(check-sat)");
String status = readFromSolver();
if (isSat(status)) {
send("(get-model)");
result = new SatResult(parseModel(readFromSolver()));
} else if (isUnsat(status)) {
result = new UnsatResult();
} else {
throw new IllegalArgumentException("Unknown result: " + result);
}
pop();
return result;
}
@Override
protected Result quickCheckSat(List<Symbol> activationLiterals) {
push();
for (Symbol actLit : activationLiterals) {
String name = "_" + actLit.str;
assertSexp(new Cons("!", actLit, new Symbol(":named"), new Symbol(name)));
}
send("(check-sat)");
String status = readFromSolver();
Result result;
if (isSat(status)) {
result = new SatResult();
} else if (isUnsat(status)) {
result = new UnsatResult(getUnsatCore(activationLiterals));
} else {
result = new UnknownResult();
}
pop();
return result;
}
protected abstract List<Symbol> getUnsatCore(List<Symbol> activationLiterals);
protected boolean isSat(String output) {
// Only check prefix, Z3 outputs content after 'sat' for max-sat style
// queries
return output.trim().startsWith("sat");
}
protected boolean isUnsat(String output) {
return output.trim().equals("unsat");
}
protected String readFromSolver() {
send("(echo \"" + DONE + "\")");
try {
String line;
StringBuilder content = new StringBuilder();
while (true) {
line = fromSolver.readLine();
comment(getSolverName() + ": " + line);
if (line == null) {
throw new JKindException(getSolverName() + " terminated unexpectedly");
} else if (line.contains("define-fun " + Relation.T + " ")) {
// No need to parse the transition relation
} else if (isDone(line)) {
break;
} else if (line.contains("model is not available")) {
flushSolver();
return null;
} else if (line.contains(" |-> ")) {
// Ignore Z3 optimization information
} else if (line.contains("out of memory")) {
throw new SolverOutOfMemoryException();
} else if (line.contains("error \"") || line.contains("Error:")) {
// Flush the output since errors span multiple lines
flushSolver();
throw new JKindException(getSolverName() + " error (see scratch file for details)");
} else {
content.append(line);
content.append("\n");
}
}
return content.toString();
} catch (RecognitionException e) {
throw new JKindException("Error parsing " + getSolverName() + " output", e);
} catch (IOException e) {
throw new JKindException("Unable to read from " + getSolverName(), e);
}
}
protected void flushSolver() throws IOException {
String line;
while ((line = fromSolver.readLine()) != null) {
comment(getSolverName() + ": " + line);
if (isDone(line)) {
return;
}
}
}
protected boolean isDone(String line) {
return line.contains(DONE);
}
protected Model parseModel(String modelStr) {
return parseSmtLib2Model(modelStr, varTypes, functions);
}
public static SmtLib2Model parseSmtLib2Model(String modelStr, Map<String, Type> varTypes, List<Function> functions) {
CharStream stream = new ANTLRInputStream(modelStr);
SmtLib2Lexer lexer = new SmtLib2Lexer(stream);
CommonTokenStream tokens = new CommonTokenStream(lexer);
SmtLib2Parser parser = new SmtLib2Parser(tokens);
parser.removeErrorListeners();
parser.addErrorListener(new SolverParserErrorListener());
ModelContext ctx = parser.model();
if (parser.getNumberOfSyntaxErrors() > 0) {
throw new JKindException("Error parsing solver output: " + modelStr);
}
return ModelExtractor.getModel(ctx, varTypes, functions);
}
@Override
public void push() {
send("(push 1)");
}
@Override
public void pop() {
send("(pop 1)");
}
@Override
public String getSolverExtension() {
return "smt2";
}
} |
package com.jme3.font;
import com.jme3.font.BitmapFont.Align;
import com.jme3.font.BitmapFont.VAlign;
import com.jme3.font.ColorTags.Range;
import com.jme3.math.ColorRGBA;
import java.util.LinkedList;
/**
* Manage and align LetterQuads
* @author YongHoon
*/
class Letters {
private final LetterQuad head;
private final LetterQuad tail;
private final BitmapFont font;
private LetterQuad current;
private StringBlock block;
private float totalWidth;
private float totalHeight;
private ColorTags colorTags = new ColorTags();
private ColorRGBA baseColor = null;
private float baseAlpha = -1;
private String plainText;
Letters(BitmapFont font, StringBlock bound, boolean rightToLeft) {
final String text = bound.getText();
this.block = bound;
this.font = font;
head = new LetterQuad(font, rightToLeft);
tail = new LetterQuad(font, rightToLeft);
setText(text);
}
void setText(final String text) {
colorTags.setText(text);
plainText = colorTags.getPlainText();
head.setNext(tail);
tail.setPrevious(head);
current = head;
if (text != null && plainText.length() > 0) {
LetterQuad l = head;
for (int i = 0; i < plainText.length(); i++) {
l = l.addNextCharacter(plainText.charAt(i));
if (baseColor != null) {
// Give the letter a default color if
// one has been provided.
l.setColor( baseColor );
}
}
}
LinkedList<Range> ranges = colorTags.getTags();
if (!ranges.isEmpty()) {
for (int i = 0; i < ranges.size()-1; i++) {
Range start = ranges.get(i);
Range end = ranges.get(i+1);
setColor(start.start, end.start, start.color);
}
Range end = ranges.getLast();
setColor(end.start, plainText.length(), end.color);
}
invalidate();
}
LetterQuad getHead() {
return head;
}
LetterQuad getTail() {
return tail;
}
void update() {
LetterQuad l = head;
int lineCount = 1;
BitmapCharacter ellipsis = font.getCharSet().getCharacter(block.getEllipsisChar());
float ellipsisWidth = ellipsis!=null? ellipsis.getWidth()*getScale(): 0;
while (!l.isTail()) {
if (l.isInvalid()) {
l.update(block);
if (l.isInvalid(block)) {
switch (block.getLineWrapMode()) {
case Character:
lineWrap(l);
lineCount++;
break;
case Word:
if (!l.isBlank()) {
// search last blank character before this word
LetterQuad blank = l;
while (!blank.isBlank()) {
if (blank.isLineStart() || blank.isHead()) {
lineWrap(l);
lineCount++;
blank = null;
break;
}
blank = blank.getPrevious();
}
if (blank != null) {
blank.setEndOfLine();
lineCount++;
while (blank != l) {
blank = blank.getNext();
blank.invalidate();
blank.update(block);
}
}
}
break;
case NoWrap:
LetterQuad cursor = l.getPrevious();
while (cursor.isInvalid(block, ellipsisWidth) && !cursor.isLineStart()) {
cursor = cursor.getPrevious();
}
cursor.setBitmapChar(ellipsis);
cursor.update(block);
cursor = cursor.getNext();
while (!cursor.isTail() && !cursor.isLineFeed()) {
cursor.setBitmapChar(null);
cursor.update(block);
cursor = cursor.getNext();
}
break;
case Clip:
// Clip the character that falls out of bounds
l.clip(block);
// Clear the rest up to the next line feed.
for( LetterQuad q = l.getNext(); !q.isTail() && !q.isLineFeed(); q = q.getNext() ) {
q.setBitmapChar(null);
q.update(block);
}
break;
}
}
} else if (current.isInvalid(block)) {
invalidate(current);
}
if (l.isEndOfLine()) {
lineCount++;
}
l = l.getNext();
}
align();
block.setLineCount(lineCount);
rewind();
}
private void align() {
final Align alignment = block.getAlignment();
final VAlign valignment = block.getVerticalAlignment();
if (block.getTextBox() == null || (alignment == Align.Left && valignment == VAlign.Top))
return;
LetterQuad cursor = tail.getPrevious();
cursor.setEndOfLine();
final float width = block.getTextBox().width;
final float height = block.getTextBox().height;
float lineWidth = 0;
float gapX = 0;
float gapY = 0;
validateSize();
if (totalHeight < height) { // align vertically only for no overflow
switch (valignment) {
case Top:
gapY = 0;
break;
case Center:
gapY = (height-totalHeight)*0.5f;
break;
case Bottom:
gapY = height-totalHeight;
break;
}
}
while (!cursor.isHead()) {
if (cursor.isEndOfLine()) {
lineWidth = cursor.getX1()-block.getTextBox().x;
if (alignment == Align.Center) {
gapX = (width-lineWidth)/2;
} else if (alignment == Align.Right) {
gapX = width-lineWidth;
} else {
gapX = 0;
}
}
cursor.setAlignment(gapX, gapY);
cursor = cursor.getPrevious();
}
}
private void lineWrap(LetterQuad l) {
if (l.isHead() || l.isBlank())
return;
l.getPrevious().setEndOfLine();
l.invalidate();
l.update(block); // TODO: update from l
}
float getCharacterX0() {
return current.getX0();
}
float getCharacterY0() {
return current.getY0();
}
float getCharacterX1() {
return current.getX1();
}
float getCharacterY1() {
return current.getY1();
}
float getCharacterAlignX() {
return current.getAlignX();
}
float getCharacterAlignY() {
return current.getAlignY();
}
float getCharacterWidth() {
return current.getWidth();
}
float getCharacterHeight() {
return current.getHeight();
}
public boolean nextCharacter() {
if (current.isTail())
return false;
current = current.getNext();
return true;
}
public int getCharacterSetPage() {
return current.getBitmapChar().getPage();
}
public LetterQuad getQuad() {
return current;
}
public void rewind() {
current = head;
}
public void invalidate() {
invalidate(head);
}
public void invalidate(LetterQuad cursor) {
totalWidth = -1;
totalHeight = -1;
while (!cursor.isTail() && !cursor.isInvalid()) {
cursor.invalidate();
cursor = cursor.getNext();
}
}
float getScale() {
return block.getSize() / font.getCharSet().getRenderedSize();
}
public boolean isPrintable() {
return current.getBitmapChar() != null;
}
float getTotalWidth() {
validateSize();
return totalWidth;
}
float getTotalHeight() {
validateSize();
return totalHeight;
}
void validateSize() {
if (totalWidth < 0) {
totalWidth = Math.abs(head.getX1() - tail.getPrevious().getX1());
LetterQuad l = head;
while (!l.isTail()) {
l = l.getNext();
totalHeight = Math.max(totalHeight, -l.getY1());
}
}
}
/**
* @param start start index to set style. inclusive.
* @param end end index to set style. EXCLUSIVE.
* @param style
*/
void setStyle(int start, int end, int style) {
LetterQuad cursor = head.getNext();
while (!cursor.isTail()) {
if (cursor.getIndex() >= start && cursor.getIndex() < end) {
cursor.setStyle(style);
}
cursor = cursor.getNext();
}
}
/**
* Sets the base color for all new letter quads and resets
* the color of existing letter quads.
*/
void setColor( ColorRGBA color ) {
baseColor = color;
colorTags.setBaseColor(color);
setColor( 0, block.getText().length(), color );
}
ColorRGBA getBaseColor() {
return baseColor;
}
/**
* @param start start index to set style. inclusive.
* @param end end index to set style. EXCLUSIVE.
* @param color
*/
void setColor(int start, int end, ColorRGBA color) {
LetterQuad cursor = head.getNext();
while (!cursor.isTail()) {
if (cursor.getIndex() >= start && cursor.getIndex() < end) {
cursor.setColor(color);
}
cursor = cursor.getNext();
}
}
float getBaseAlpha() {
return baseAlpha;
}
void setBaseAlpha( float alpha ) { this.baseAlpha = alpha;
colorTags.setBaseAlpha(alpha);
if (alpha == -1) {
alpha = baseColor != null ? baseColor.a : 1;
}
// Forward the new alpha to the letter quads
LetterQuad cursor = head.getNext();
while (!cursor.isTail()) {
cursor.setAlpha(alpha);
cursor = cursor.getNext();
}
// If the alpha was reset to "default", ie: -1
// then the color tags are potentially reset and
// we need to reapply them. This has to be done
// second since it may override any alpha values
// set above... but you still need to do the above
// since non-color tagged text is treated differently
// even if part of a color tagged string.
if (baseAlpha == -1) {
LinkedList<Range> ranges = colorTags.getTags();
if (!ranges.isEmpty()) {
for (int i = 0; i < ranges.size()-1; i++) {
Range start = ranges.get(i);
Range end = ranges.get(i+1);
setColor(start.start, end.start, start.color);
}
Range end = ranges.getLast();
setColor(end.start, plainText.length(), end.color);
}
}
invalidate();
}
} |
package com.proofpoint.jmx;
import com.google.inject.Inject;
import com.proofpoint.log.Logger;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.management.MBeanServer;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
import java.io.IOException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.rmi.registry.LocateRegistry;
import java.util.Collections;
public class JMXAgent
{
private final String host;
private final int registryPort;
private final int serverPort;
private final JMXConnectorServer connectorServer;
private static Logger log = Logger.get(JMXAgent.class);
private final JMXServiceURL url;
@Inject
public JMXAgent(MBeanServer server, JMXConfig config)
throws IOException
{
if (config.getHostname() == null) {
host = InetAddress.getLocalHost().getHostAddress();
}
else {
host = config.getHostname();
}
if (config.getRmiRegistryPort() == null) {
registryPort = NetUtils.findUnusedPort();
}
else {
registryPort = config.getRmiRegistryPort();
}
if (config.getRmiServerPort() == null) {
serverPort = NetUtils.findUnusedPort();
}
else {
serverPort = config.getRmiServerPort();
}
try {
url = new JMXServiceURL(String.format("service:jmx:rmi://%s:%d/jndi/rmi://%s:%d/jmxrmi",
host, serverPort, host, registryPort));
}
catch (MalformedURLException e) {
// should not happen...
throw new AssertionError(e);
}
connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, Collections.<String, Object>emptyMap(), server);
}
public JMXServiceURL getURL()
{
return url;
}
@PostConstruct
public void start()
throws IOException
{
System.setProperty("java.rmi.server.randomIDs", "true");
System.setProperty("java.rmi.server.hostname", host);
LocateRegistry.createRegistry(registryPort);
connectorServer.start();
log.info("JMX Agent listening on %s:%s", host, registryPort);
}
@PreDestroy
public void stop()
throws IOException
{
connectorServer.stop();
}
} |
package com.evolveum.midpoint.web.page.admin.configuration.component;
import com.evolveum.midpoint.gui.api.page.PageBase;
import com.evolveum.midpoint.gui.api.util.WebComponentUtil;
import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils;
import com.evolveum.midpoint.model.api.ModelService;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.schema.GetOperationOptions;
import com.evolveum.midpoint.schema.ResultHandler;
import com.evolveum.midpoint.schema.SchemaConstantsGenerated;
import com.evolveum.midpoint.schema.SelectorOptions;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.exception.SystemException;
import com.evolveum.midpoint.util.logging.LoggingUtils;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
import com.evolveum.midpoint.web.component.AjaxDownloadBehaviorFromFile;
import com.evolveum.midpoint.web.page.error.PageError;
import com.evolveum.midpoint.web.security.MidPointApplication;
import com.evolveum.midpoint.web.security.WebApplicationConfiguration;
import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.util.file.File;
import org.apache.wicket.util.file.Files;
import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static com.evolveum.midpoint.prism.SerializationOptions.createSerializeForExport;
/**
* @author lazyman
*/
public class PageDebugDownloadBehaviour extends AjaxDownloadBehaviorFromFile {
private static final Trace LOGGER = TraceManager.getTrace(PageDebugDownloadBehaviour.class);
private static final String DOT_CLASS = PageDebugDownloadBehaviour.class.getName() + ".";
private static final String OPERATION_SEARCH_OBJECT = DOT_CLASS + "loadObjects";
private static final String OPERATION_CREATE_DOWNLOAD_FILE = DOT_CLASS + "createDownloadFile";
private boolean exportAll;
private Class<? extends ObjectType> type;
private boolean useZip;
private ObjectQuery query;
public boolean isExportAll() {
return exportAll;
}
public void setExportAll(boolean exportAll) {
this.exportAll = exportAll;
}
public Class<? extends ObjectType> getType() {
if (type == null) {
return ObjectType.class;
}
return type;
}
public void setType(Class<? extends ObjectType> type) {
this.type = type;
}
public ObjectQuery getQuery() {
return query;
}
public void setQuery(ObjectQuery query) {
this.query = query;
}
public boolean isUseZip() {
return useZip;
}
public void setUseZip(boolean useZip) {
this.useZip = useZip;
}
@Override
protected File initFile() {
PageBase page = getPage();
OperationResult result = new OperationResult(OPERATION_CREATE_DOWNLOAD_FILE);
MidPointApplication application = page.getMidpointApplication();
WebApplicationConfiguration config = application.getWebApplicationConfiguration();
File folder = new File(config.getExportFolder());
if (!folder.exists() || !folder.isDirectory()) {
folder.mkdir();
}
String suffix = isUseZip() ? "zip" : "xml";
String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_m_s"));
String fileName = "ExportedData_" + getType().getSimpleName() + "_" + currentTime + "." + suffix;
File file = new File(folder, fileName);
Writer writer = null;
try {
LOGGER.debug("Creating file '{}'.", file.getAbsolutePath());
writer = createWriter(file);
LOGGER.debug("Exporting objects.");
dumpHeader(writer);
dumpObjectsToStream(writer, result);
dumpFooter(writer);
LOGGER.debug("Export finished.");
result.recomputeStatus();
} catch (Exception ex) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't init download link", ex);
result.recordFatalError("Couldn't init download link", ex);
} finally {
if (writer != null) {
IOUtils.closeQuietly(writer);
}
}
if (!WebComponentUtil.isSuccessOrHandledError(result)) {
page.showResult(result);
page.getSession().error(page.getString("pageDebugList.message.createFileException"));
LOGGER.debug("Removing file '{}'.", new Object[]{file.getAbsolutePath()});
Files.remove(file);
throw new RestartResponseException(PageError.class);
}
return file;
}
private Writer createWriter(File file) throws IOException {
OutputStream stream;
if (isUseZip()) {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(file));
String fileName = file.getName();
if (StringUtils.isNotEmpty(file.getExtension())) {
fileName = fileName.replaceAll(file.getExtension() + "$", "xml");
}
ZipEntry entry = new ZipEntry(fileName);
out.putNextEntry(entry);
stream = out;
} else {
stream = new FileOutputStream(file);
}
return new OutputStreamWriter(stream);
}
private <T extends ObjectType> void dumpObjectsToStream(final Writer writer, OperationResult result) throws Exception {
final PageBase page = getPage();
ResultHandler handler = (object, parentResult) -> {
try {
String xml = page.getPrismContext().xmlSerializer().options(createSerializeForExport()).serialize(object);
writer.write('\t');
writer.write(xml);
writer.write('\n');
} catch (IOException|SchemaException ex) {
throw new SystemException(ex.getMessage(), ex);
}
return true;
};
ModelService service = page.getModelService();
GetOperationOptions options = GetOperationOptions.createRaw();
options.setResolveNames(true);
Collection<SelectorOptions<GetOperationOptions>> optionsCollection = SelectorOptions.createCollection(options);
WebModelServiceUtils.addIncludeOptionsForExportOrView(optionsCollection, type);
service.searchObjectsIterative(type, query, handler, optionsCollection,
page.createSimpleTask(OPERATION_SEARCH_OBJECT), result);
}
private PageBase getPage() {
return (PageBase) getComponent().getPage();
}
private void dumpFooter(Writer writer) throws IOException {
writer.write("</objects>");
}
private void dumpHeader(Writer writer) throws IOException {
writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
writer.write("<objects xmlns=\"");
writer.write(SchemaConstantsGenerated.NS_COMMON);
writer.write("\"\n");
writer.write("\txmlns:c=\"");
writer.write(SchemaConstantsGenerated.NS_COMMON);
writer.write("\"\n");
writer.write("\txmlns:org=\"");
writer.write(SchemaConstants.NS_ORG);
writer.write("\">\n");
}
} |
package joliex.mail;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import jolie.net.CommMessage;
import jolie.runtime.AndJarDeps;
import jolie.runtime.FaultException;
import jolie.runtime.JavaService;
import jolie.runtime.Value;
@AndJarDeps({"mailapi.jar","smtp.jar"})
public class SMTPService extends JavaService
{
private class SimpleAuthenticator extends Authenticator
{
final private String username, password;
public SimpleAuthenticator( String username, String password )
{
this.username = username;
this.password = password;
}
@Override
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication( username, password );
}
}
public CommMessage sendMail( CommMessage requestMessage )
throws FaultException
{
Value request = requestMessage.value();
Authenticator authenticator = null;
Properties props = new Properties();
props.put( "mail.smtp.host", request.getFirstChild( "host" ).strValue() );
if ( request.getFirstChild( "authenticate" ).intValue() == 1 ) {
props.put( "mail.smtp.auth", "true" );
authenticator = new SimpleAuthenticator(
request.getFirstChild( "username" ).strValue(),
request.getFirstChild( "password" ).strValue()
);
}
Session session = Session.getDefaultInstance( props, authenticator );
Message msg = new MimeMessage( session );
try {
msg.setFrom( new InternetAddress( request.getFirstChild( "from" ).strValue() ) );
for( Value v : request.getChildren( "to" ) ) {
msg.addRecipient( Message.RecipientType.TO, new InternetAddress( v.strValue() ) );
}
for( Value v : request.getChildren( "cc" ) ) {
msg.addRecipient( Message.RecipientType.CC, new InternetAddress( v.strValue() ) );
}
for( Value v : request.getChildren( "bcc" ) ) {
msg.addRecipient( Message.RecipientType.BCC, new InternetAddress( v.strValue() ) );
}
msg.setSubject( request.getFirstChild( "subject" ).strValue() );
final String content = request.getFirstChild( "content" ).strValue();
DataHandler dh = new DataHandler( new DataSource() {
public InputStream getInputStream() throws IOException
{
return new ByteArrayInputStream( content.getBytes() );
}
public OutputStream getOutputStream() throws IOException
{
throw new IOException( "Operation not supported" );
}
public String getContentType()
{
return "text/plain";
}
public String getName()
{
return "mail_content";
}
} );
msg.setDataHandler( dh );
Transport.send( msg );
} catch( MessagingException e ) {
throw new FaultException( "SMTPFault", e );
}
return CommMessage.createResponse( requestMessage, Value.create() );
}
} |
package com.peterphi.std.guice.web.rest.service.servicedescription.freemarker;
import com.peterphi.std.util.DOMUtils;
import com.peterphi.std.util.jaxb.JAXBSerialiser;
import com.peterphi.std.util.jaxb.MultiXSDGenerator;
import com.peterphi.std.util.jaxb.type.MultiXSDSchemaFiles;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import java.io.IOException;
import java.util.Arrays;
public class SchemaGenerateUtil
{
public String generate(JAXBSerialiser serialiser) throws IOException
{
final MultiXSDSchemaFiles schemas = new MultiXSDGenerator().withLoosenXmlAnyConstraints(true).generate(serialiser);
if (schemas.files.size() == 1)
{
// Single schema, can be serialised as a simple XSD
return DOMUtils.serialise(schemas.files.get(0).schemaElement());
}
else
{
// Complex schema, needs to be represented with multi-xsd schema
return JAXBSerialiser.getInstance(MultiXSDSchemaFiles.class).serialise(schemas);
}
}
/**
* Retrieve a schema description for a type
*
* @param clazz
*
* @return
*/
public String getSchema(Class<?> clazz)
{
if (clazz == Integer.class || clazz == Integer.TYPE)
{
return "integer [" + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE + "]";
}
else if (clazz == Long.class || clazz == Long.TYPE)
{
return "long [" + Long.MIN_VALUE + " to " + Long.MAX_VALUE + "]";
}
else if (clazz == Double.class || clazz == Double.TYPE)
{
return "double [" + Double.MIN_VALUE + " to " + Double.MAX_VALUE + "]";
}
else if (clazz == Boolean.class || clazz == Boolean.TYPE)
{
return "boolean [true, false]";
}
else if (clazz == Void.class)
{
return "void";
}
else if (clazz == Byte[].class || clazz == byte[].class)
{
return "binary stream";
}
else if (clazz.isEnum())
{
return "enum " + Arrays.asList(clazz.getEnumConstants());
}
else if (clazz.isAnnotationPresent(XmlRootElement.class))
{
try
{
final JAXBSerialiser serialiser = JAXBSerialiser.getMoxy(clazz);
return generate(serialiser);
}
catch (Exception e)
{
// Ignore
return "error generating schema for " + clazz + ": " + e.getMessage();
}
}
else if (clazz.isAnnotationPresent(XmlType.class) || clazz.isAnnotationPresent(XmlEnum.class))
{
// Class generated by JAXB XSD To Java (as a result we have to emit the entire schema rather than being able to provide a specific sub-schema for the type in question because XmlRootElement is not specified)
try
{
final JAXBSerialiser serialiser = JAXBSerialiser.getMoxy(clazz.getPackage().getName());
return generate(serialiser);
}
catch (Exception e)
{
// Ignore
return "error generating schema for XSD-To-Java package schema for class " + clazz + ": " + e.getMessage();
}
}
else
{
return clazz.toString();
}
}
public static void print(final Class<?> clazz)
{
try
{
System.out.println(new SchemaGenerateUtil().generate(JAXBSerialiser.getInstance(clazz)));
}
catch (Throwable t)
{
throw new RuntimeException("Error generating XSD for " + clazz + ": " + t.getMessage(), t);
}
}
} |
package org.jpos.iso.header;
import org.jpos.iso.*;
/*
* BASE1 Header
* <pre>
* 0 hlen; Fld 1: Header Length 1B (Byte 0)
* 1 hformat; Fld 2: Header Format 8N,bit (Byte 1)
* 2 format; Fld 3: Text Format 1B (Byte 2)
* 3 len[2]; Fld 4: Total Message Length 2B (Byte 3- 4)
* 5 dstId[3]; Fld 5: Destination Id 6N,BCD (Byte 5- 7)
* 8 srcId[3]; Fld 6: Source Id 6N,BCD (Byte 8-10)
* 11 rtCtl; Fld 7: Round-Trip Ctrl Info 8N,bit (Byte 11)
* 12 flags[2]; Fld 8: BASE I Flags 16N,bit (Byte 12-13)
* 14 status[3]; Fld 9: Message Status Flags 24bits (Byte 14-16)
* 17 batchNbr; Fld 10: Batch Number 1B (Byte 17)
* 18 reserved[3]; Fld 11: Reserved 3B (Byte 18-20)
* 21 userInfo; Fld 12: User Info 1B (Byte 21)
* </pre>
*
*/
public class BASE1Header extends BaseHeader {
public static final int LENGTH = 22;
public BASE1Header() {
this("000000", "000000");
}
public BASE1Header(String source, String destination) {
super();
header = new byte[LENGTH];
header[0] = LENGTH; // hlen
setHFormat(1);
setFormat(2);
setSource(source);
setDestination(destination);
}
public BASE1Header(byte[] header) {
super (header);
}
public int unpack (byte[] header) {
this.header = new byte[LENGTH];
System.arraycopy (header, 0, this.header, 0, LENGTH);
return LENGTH;
}
public int getHLen() {
return (int) (header[0] & 0xFF);
}
public void setHFormat(int hformat) {
header[1] = (byte) hformat;
}
public void setRtCtl(int i) {
header[11] = (byte) i;
}
public void setFlags(int i) {
header[12] = (byte) ((i >> 8) & 0xFF);
header[13] = (byte) (i & 0xFF);
}
public void setStatus(int i) {
header[14] = (byte) ((i >> 16) & 0xFF);
header[15] = (byte) ((i >> 8) & 0xFF);
header[16] = (byte) (i & 0xFF);
}
public void setBatchNumber(int i) {
header[17] = (byte) (i & 0xFF);
}
public void setFormat(int format) {
header[2] = (byte) format;
}
public void setLen(int len) {
len += LENGTH;
header[3] = (byte) ((len >> 8) & 0xff);
header[4] = (byte) (len & 0xff);
}
public void setDestination(String dest) {
byte[] d = ISOUtil.str2bcd(dest, true);
System.arraycopy(d, 0, header, 5, 3);
}
public void setSource(String src) {
byte[] d = ISOUtil.str2bcd(src, true);
System.arraycopy(d, 0, header, 8, 3);
}
public String getSource() {
return ISOUtil.bcd2str (this.header, 8, 6, false);
}
public String getDestination() {
return ISOUtil.bcd2str (this.header, 5, 6, false);
}
public void swapDirection() {
if (header != null && header.length >= LENGTH) {
byte[] source = new byte[3];
System.arraycopy(header, 8, source, 0, 3);
System.arraycopy(header, 5, header, 8, 3);
System.arraycopy(source, 0, header, 5, 3);
}
}
public boolean isRejected() {
return (header[16] & 0x80) == 0x80;
}
// first bit of fld 13 of header == 1 && len >=26
// indica un nuevo header de 22 (Pagina 4-2 Vol-1 VIP System
// Technical Reference General Requirements
}; |
package it.com.atlassian.jira.plugins.dvcs.missingCommits;
import com.atlassian.jira.plugins.dvcs.pageobjects.page.GithubConfigureOrganizationsPage;
import com.atlassian.jira.plugins.dvcs.remoterestpoint.GithubRepositoriesRemoteRestpoint;
import com.atlassian.plugin.util.zip.FileUnzipper;
import it.restart.com.atlassian.jira.plugins.dvcs.common.MagicVisitor;
import it.restart.com.atlassian.jira.plugins.dvcs.common.OAuth;
import it.restart.com.atlassian.jira.plugins.dvcs.github.GithubLoginPage;
import it.restart.com.atlassian.jira.plugins.dvcs.github.GithubOAuthPage;
import org.apache.commons.io.FileUtils;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
/**
* @author Miroslav Stencel
*/
@Test
public class MissingCommitsGithubTest extends AbstractMissingCommitsTest<GithubConfigureOrganizationsPage>
{
private static final String GITHUB_URL = "api.github.com";
private static final String USER_AGENT = "DVCS Connector Test/X.x";
private static final String _1ST_GIT_REPO_ZIP_TO_PUSH = "missingCommits/git/git_1st_push.zip";
private static final String _2ND_GIT_REPO_ZIP_TO_PUSH = "missingCommits/git/git_2nd_push_after_merge.zip";
private static GithubRepositoriesRemoteRestpoint githubRepositoriesREST;
@BeforeClass
public static void initializeGithubRepositoriesREST()
{
GitHubClient gitHubClient = new GitHubClient(GITHUB_URL);
gitHubClient.setUserAgent(USER_AGENT);
gitHubClient.setCredentials(DVCS_REPO_OWNER, DVCS_REPO_PASSWORD);
githubRepositoriesREST = new GithubRepositoriesRemoteRestpoint(gitHubClient);
}
@Override
void removeRemoteDvcsRepository()
{
githubRepositoriesREST.removeExistingRepository(MISSING_COMMITS_REPOSITORY_NAME, DVCS_REPO_OWNER);
}
@Override
void createRemoteDvcsRepository()
{
githubRepositoriesREST.createGithubRepository(MISSING_COMMITS_REPOSITORY_NAME);
}
@Override
OAuth loginToDvcsAndGetJiraOAuthCredentials()
{
// log in to github
new MagicVisitor(jira).visit(GithubLoginPage.class).doLogin(DVCS_REPO_OWNER, DVCS_REPO_PASSWORD);
// setup up OAuth from github
return new MagicVisitor(jira).visit(GithubOAuthPage.class).addConsumer(jira.getProductInstance().getBaseUrl());
}
@Override
void pushToRemoteDvcsRepository(String pathToRepoZip) throws Exception
{
File extractedRepoDir = extractRepoZipIntoTempDir(pathToRepoZip);
String gitPushUrl = String.format("https://%1$s:%2$s@github.com/%1$s/%3$s.git", DVCS_REPO_OWNER,
DVCS_REPO_PASSWORD, MISSING_COMMITS_REPOSITORY_NAME);
String gitCommand = getGitCommand();
executeCommand(extractedRepoDir, gitCommand, "remote", "rm", "origin");
executeCommand(extractedRepoDir, gitCommand, "remote", "add", "origin", gitPushUrl);
executeCommand(extractedRepoDir, gitCommand, "push", "-u", "origin", "master");
FileUtils.deleteDirectory(extractedRepoDir);
}
private File extractRepoZipIntoTempDir(String pathToRepoZip) throws IOException, URISyntaxException
{
URL repoZipResource = getClass().getClassLoader().getResource(pathToRepoZip);
File tempDir = new File(System.getProperty("java.io.tmpdir"), "" + System.currentTimeMillis());
tempDir.mkdir();
FileUnzipper fileUnzipper = new FileUnzipper(new File(repoZipResource.toURI()), tempDir);
fileUnzipper.unzip();
return tempDir;
}
@Override
String getFirstDvcsZipRepoPathToPush()
{
// repository after the 1st push in following state:
// | Author | Commit | Message |
// | Miroslav Stencel | 9d08182535 | MC-1 5th commit + 2nd push {user1} [14:26] |
// | Miroslav Stencel | f6ffeee87f | MC-1 2nd commit + 1st push {user1} [14:18] |
// | Miroslav Stencel | db26d59a1f | MC-1 1st commit {user1} [14:16] |
return _1ST_GIT_REPO_ZIP_TO_PUSH;
}
@Override
String getSecondDvcsZipRepoPathToPush()
{
// repository after the 2nd push in following state:
// | Author | Commit | Message |
// | Miroslav Stencel | f59cc8a7b7 | merge + 3rd push {user2} [14:44] |
// | Miroslav Stencel | 9d08182535 | MC-1 5th commit + 2nd push {user1} [14:26] |
// | Miroslav Stencel | cc2ac8c703 | MC-1 4th commit {user2} [14:25] |
// | Miroslav Stencel | d5d190c12c | MC-1 3rd commit {user2} [14:24] |
// | Miroslav Stencel | f6ffeee87f | MC-1 2nd commit + 1st push {user1} [14:18] |
// | Miroslav Stencel | db26d59a1f | MC-1 1st commit {user1} [14:16] |
return _2ND_GIT_REPO_ZIP_TO_PUSH;
}
@Override
protected Class<GithubConfigureOrganizationsPage> getConfigureOrganizationsPageClass()
{
return GithubConfigureOrganizationsPage.class;
}
@Override
void removeOAuth()
{
// remove OAuth in github
try
{
new MagicVisitor(jira).visit(oAuth.applicationId, GithubOAuthPage.class).removeConsumer();
} catch (Exception e)
{
// deliberately ignoring the exception
//FIXME should be fixed to remove OAuth correctly
}
// log out from github
new MagicVisitor(jira).visit(GithubLoginPage.class).doLogout();
}
} |
package org.eclipse.persistence.testing.jaxb.xmlmarshaller;
import javax.xml.bind.ValidationEventHandler;
import javax.xml.bind.ValidationEvent;
public class CustomErrorValidationEventHandler implements ValidationEventHandler {
private int errorCount = 0;
public boolean handleEvent(ValidationEvent event) {
if (event.getSeverity() != ValidationEvent.ERROR) {
return false;
}
errorCount++;
if (errorCount == 1) {
return true;
}
return false;
}
} |
package org.opencb.opencga.storage.core.variant.query;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.opencb.biodata.models.variant.Genotype;
import org.opencb.biodata.models.variant.Variant;
import org.opencb.biodata.models.variant.avro.ClinicalSignificance;
import org.opencb.biodata.models.variant.avro.VariantType;
import org.opencb.biodata.models.variant.metadata.VariantFileHeaderComplexLine;
import org.opencb.cellbase.core.variant.annotation.VariantAnnotationUtils;
import org.opencb.commons.datastore.core.Query;
import org.opencb.commons.datastore.core.QueryOptions;
import org.opencb.commons.datastore.core.QueryParam;
import org.opencb.opencga.storage.core.metadata.VariantStorageMetadataManager;
import org.opencb.opencga.storage.core.metadata.models.SampleMetadata;
import org.opencb.opencga.storage.core.metadata.models.StudyMetadata;
import org.opencb.opencga.storage.core.metadata.models.TaskMetadata;
import org.opencb.opencga.storage.core.metadata.models.VariantScoreMetadata;
import org.opencb.opencga.storage.core.utils.CellBaseUtils;
import org.opencb.opencga.storage.core.variant.adaptors.GenotypeClass;
import org.opencb.opencga.storage.core.variant.adaptors.VariantQueryException;
import org.opencb.opencga.storage.core.variant.adaptors.VariantQueryParam;
import org.opencb.opencga.storage.core.variant.query.projection.VariantQueryProjection;
import org.opencb.opencga.storage.core.variant.query.projection.VariantQueryProjectionParser;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static org.opencb.opencga.storage.core.variant.VariantStorageOptions.EXCLUDE_GENOTYPES;
import static org.opencb.opencga.storage.core.variant.VariantStorageOptions.LOADED_GENOTYPES;
import static org.opencb.opencga.storage.core.variant.adaptors.VariantQueryParam.*;
import static org.opencb.opencga.storage.core.variant.query.VariantQueryUtils.*;
public class VariantQueryParser {
protected final CellBaseUtils cellBaseUtils;
protected final VariantStorageMetadataManager metadataManager;
protected final VariantQueryProjectionParser projectionParser;
public VariantQueryParser(CellBaseUtils cellBaseUtils, VariantStorageMetadataManager metadataManager) {
this.cellBaseUtils = cellBaseUtils;
this.metadataManager = metadataManager;
this.projectionParser = new VariantQueryProjectionParser(metadataManager);
}
public ParsedVariantQuery parseQuery(Query query, QueryOptions options) {
return parseQuery(query, options, false);
}
public ParsedVariantQuery parseQuery(Query query, QueryOptions options, boolean skipPreProcess) {
if (query == null) {
query = new Query();
}
if (options == null) {
options = new QueryOptions();
}
ParsedVariantQuery variantQuery = new ParsedVariantQuery(new Query(query), new QueryOptions(options));
if (!skipPreProcess) {
query = preProcessQuery(query, options);
}
variantQuery.setQuery(query);
variantQuery.setProjection(projectionParser.parseVariantQueryProjection(query, options));
ParsedVariantQuery.VariantStudyQuery studyQuery = variantQuery.getStudyQuery();
StudyMetadata defaultStudy = getDefaultStudy(query);
studyQuery.setDefaultStudy(defaultStudy);
if (isValidParam(query, STUDY)) {
studyQuery.setStudies(VariantQueryUtils.splitValue(query, STUDY));
}
if (isValidParam(query, GENOTYPE)) {
HashMap<Object, List<String>> map = new HashMap<>();
QueryOperation op = VariantQueryUtils.parseGenotypeFilter(query.getString(GENOTYPE.key()), map);
if (defaultStudy == null) {
List<String> studyNames = metadataManager.getStudyNames();
throw VariantQueryException.missingStudyForSamples(map.keySet()
.stream().map(Object::toString).collect(Collectors.toSet()), studyNames);
}
List<KeyOpValue<SampleMetadata, List<String>>> values = new ArrayList<>();
for (Map.Entry<Object, List<String>> entry : map.entrySet()) {
Integer sampleId = metadataManager.getSampleId(defaultStudy.getId(), entry.getKey());
if (sampleId == null) {
throw VariantQueryException.sampleNotFound(entry.getKey(), defaultStudy.getName());
}
values.add(new KeyOpValue<>(metadataManager.getSampleMetadata(defaultStudy.getId(), sampleId), "=", entry.getValue()));
}
studyQuery.setGenotypes(new ParsedQuery<>(GENOTYPE, op, values));
}
return variantQuery;
}
public Query preProcessQuery(Query originalQuery, QueryOptions options) {
// Copy input query! Do not modify original query!
Query query = originalQuery == null ? new Query() : new Query(originalQuery);
preProcessAnnotationParams(query);
preProcessStudyParams(query, options);
if (options != null && options.getLong(QueryOptions.LIMIT) < 0) {
throw VariantQueryException.malformedParam(QueryOptions.LIMIT, options.getString(QueryOptions.LIMIT),
"Invalid negative limit");
}
if (options != null && options.getLong(QueryOptions.SKIP) < 0) {
throw VariantQueryException.malformedParam(QueryOptions.SKIP, options.getString(QueryOptions.SKIP),
"Invalid negative skip");
}
return query;
}
protected void preProcessAnnotationParams(Query query) {
convertGoToGeneQuery(query, cellBaseUtils);
convertExpressionToGeneQuery(query, cellBaseUtils);
ParsedVariantQuery.VariantQueryXref xrefs = parseXrefs(query);
List<String> allIds = new ArrayList<>(xrefs.getIds().size() + xrefs.getVariants().size());
allIds.addAll(xrefs.getIds());
for (Variant variant : xrefs.getVariants()) {
allIds.add(variant.toString());
}
query.put(ID.key(), allIds);
query.put(GENE.key(), xrefs.getGenes());
query.put(ANNOT_XREF.key(), xrefs.getOtherXrefs());
query.remove(ANNOT_CLINVAR.key());
query.remove(ANNOT_COSMIC.key());
if (VariantQueryUtils.isValidParam(query, TYPE)) {
Set<String> types = new HashSet<>();
if (query.getString(TYPE.key()).contains(NOT)) {
// Invert negations
for (VariantType value : VariantType.values()) {
types.add(value.name());
}
for (String type : query.getAsStringList(TYPE.key())) {
if (isNegated(type)) {
type = removeNegation(type);
} else {
throw VariantQueryException.malformedParam(TYPE, "Can not mix negated and no negated values");
}
// Expand types to subtypes
type = type.toUpperCase();
Set<VariantType> subTypes = Variant.subTypes(VariantType.valueOf(type));
types.remove(type);
subTypes.forEach(subType -> types.remove(subType.toString()));
}
} else {
// Expand types to subtypes
for (String type : query.getAsStringList(TYPE.key())) {
type = type.toUpperCase();
Set<VariantType> subTypes = Variant.subTypes(VariantType.valueOf(type));
types.add(type);
subTypes.forEach(subType -> types.add(subType.toString()));
}
}
query.put(TYPE.key(), new ArrayList<>(types));
}
if (VariantQueryUtils.isValidParam(query, ANNOT_CLINICAL_SIGNIFICANCE)) {
String v = query.getString(ANNOT_CLINICAL_SIGNIFICANCE.key());
QueryOperation operator = VariantQueryUtils.checkOperator(v);
List<String> values = VariantQueryUtils.splitValue(v, operator);
List<String> clinicalSignificanceList = new ArrayList<>(values.size());
for (String clinicalSignificance : values) {
ClinicalSignificance enumValue = EnumUtils.getEnum(ClinicalSignificance.class, clinicalSignificance);
if (enumValue == null) {
String key = clinicalSignificance.toLowerCase().replace(' ', '_');
enumValue = EnumUtils.getEnum(ClinicalSignificance.class, key);
}
if (enumValue == null) {
String key = clinicalSignificance.toLowerCase();
if (VariantAnnotationUtils.CLINVAR_CLINSIG_TO_ACMG.containsKey(key)) {
// No value set
enumValue = VariantAnnotationUtils.CLINVAR_CLINSIG_TO_ACMG.get(key);
}
}
if (enumValue != null) {
clinicalSignificance = enumValue.toString();
} // else should throw exception?
clinicalSignificanceList.add(clinicalSignificance);
}
query.put(ANNOT_CLINICAL_SIGNIFICANCE.key(),
String.join(operator == null ? "" : operator.separator(), clinicalSignificanceList));
}
if (isValidParam(query, ANNOT_SIFT)) {
String sift = query.getString(ANNOT_SIFT.key());
String[] split = splitOperator(sift);
if (StringUtils.isNotEmpty(split[0])) {
throw VariantQueryException.malformedParam(ANNOT_SIFT, sift);
}
if (isValidParam(query, ANNOT_PROTEIN_SUBSTITUTION)) {
String proteinSubstitution = query.getString(ANNOT_PROTEIN_SUBSTITUTION.key());
if (proteinSubstitution.contains("sift")) {
throw VariantQueryException.malformedParam(ANNOT_SIFT,
"Conflict with parameter \"" + ANNOT_PROTEIN_SUBSTITUTION.key() + "\"");
}
query.put(ANNOT_PROTEIN_SUBSTITUTION.key(), proteinSubstitution + AND + "sift" + split[1] + split[2]);
} else {
query.put(ANNOT_PROTEIN_SUBSTITUTION.key(), "sift" + split[1] + split[2]);
}
query.remove(ANNOT_SIFT.key());
}
if (isValidParam(query, ANNOT_POLYPHEN)) {
String polyphen = query.getString(ANNOT_POLYPHEN.key());
String[] split = splitOperator(polyphen);
if (StringUtils.isNotEmpty(split[0])) {
throw VariantQueryException.malformedParam(ANNOT_POLYPHEN, polyphen);
}
if (isValidParam(query, ANNOT_PROTEIN_SUBSTITUTION)) {
String proteinSubstitution = query.getString(ANNOT_PROTEIN_SUBSTITUTION.key());
if (proteinSubstitution.contains("sift")) {
throw VariantQueryException.malformedParam(ANNOT_SIFT,
"Conflict with parameter \"" + ANNOT_PROTEIN_SUBSTITUTION.key() + "\"");
}
query.put(ANNOT_PROTEIN_SUBSTITUTION.key(), proteinSubstitution + AND + "polyphen" + split[1] + split[2]);
} else {
query.put(ANNOT_PROTEIN_SUBSTITUTION.key(), "polyphen" + split[1] + split[2]);
}
query.remove(ANNOT_POLYPHEN.key());
}
if (isValidParam(query, ANNOT_CONSEQUENCE_TYPE)) {
Pair<QueryOperation, List<String>> pair = VariantQueryUtils.splitValue(query.getString(ANNOT_CONSEQUENCE_TYPE.key()));
QueryOperation op = pair.getLeft();
List<String> cts = pair.getRight();
List<String> parsedCts = parseConsequenceTypes(cts);
query.put(ANNOT_CONSEQUENCE_TYPE.key(), op == null ? parsedCts : String.join(op.separator(), parsedCts));
}
}
protected void preProcessStudyParams(Query query, QueryOptions options) {
StudyMetadata defaultStudy = getDefaultStudy(query);
QueryOperation formatOperator = null;
if (isValidParam(query, SAMPLE_DATA)) {
extractGenotypeFromFormatFilter(query);
Pair<QueryOperation, Map<String, String>> pair = parseFormat(query);
formatOperator = pair.getKey();
for (Map.Entry<String, String> entry : pair.getValue().entrySet()) {
String sampleName = entry.getKey();
if (defaultStudy == null) {
throw VariantQueryException.missingStudyForSample(sampleName, metadataManager.getStudyNames());
}
Integer sampleId = metadataManager.getSampleId(defaultStudy.getId(), sampleName, true);
if (sampleId == null) {
throw VariantQueryException.sampleNotFound(sampleName, defaultStudy.getName());
}
List<String> formats = splitValue(entry.getValue()).getValue();
for (String format : formats) {
String[] split = splitOperator(format);
VariantFileHeaderComplexLine line = defaultStudy.getVariantHeaderLine("FORMAT", split[0]);
if (line == null) {
throw VariantQueryException.malformedParam(SAMPLE_DATA, query.getString(SAMPLE_DATA.key()),
"FORMAT field \"" + split[0] + "\" not found. Available keys in study: "
+ defaultStudy.getVariantHeaderLines("FORMAT").keySet());
}
}
}
}
if (isValidParam(query, FILE_DATA)) {
Pair<QueryOperation, Map<String, String>> pair = parseInfo(query);
if (isValidParam(query, FILE) && pair.getKey() != null) {
QueryOperation fileOperator = checkOperator(query.getString(FILE.key()));
if (fileOperator != null && pair.getKey() != fileOperator) {
throw VariantQueryException.mixedAndOrOperators(FILE, FILE_DATA);
}
}
for (Map.Entry<String, String> entry : pair.getValue().entrySet()) {
String fileName = entry.getKey();
if (defaultStudy == null) {
throw VariantQueryException.missingStudyForFile(fileName, metadataManager.getStudyNames());
}
Integer fileId = metadataManager.getFileId(defaultStudy.getId(), fileName, true);
if (fileId == null) {
throw VariantQueryException.fileNotFound(fileName, defaultStudy.getName());
}
List<String> infos = splitValue(entry.getValue()).getValue();
for (String info : infos) {
String[] split = splitOperator(info);
VariantFileHeaderComplexLine line = defaultStudy.getVariantHeaderLine("INFO", split[0]);
if (line == null) {
throw VariantQueryException.malformedParam(FILE_DATA, query.getString(FILE_DATA.key()),
"INFO field \"" + split[0] + "\" not found. Available keys in study: "
+ defaultStudy.getVariantHeaderLines("INFO").keySet());
}
}
}
}
QueryOperation genotypeOperator = null;
VariantQueryParam genotypeParam = null;
List<QueryParam> sampleParamsList = new LinkedList<>();
if (isValidParam(query, SAMPLE)) {
sampleParamsList.add(SAMPLE);
}
if (isValidParam(query, GENOTYPE)) {
sampleParamsList.add(GENOTYPE);
}
if (isValidParam(query, SAMPLE_DE_NOVO)) {
sampleParamsList.add(SAMPLE_DE_NOVO);
}
if (isValidParam(query, SAMPLE_MENDELIAN_ERROR)) {
sampleParamsList.add(SAMPLE_MENDELIAN_ERROR);
}
if (isValidParam(query, SAMPLE_COMPOUND_HETEROZYGOUS)) {
sampleParamsList.add(SAMPLE_COMPOUND_HETEROZYGOUS);
}
if (sampleParamsList.size() > 1) {
throw VariantQueryException.unsupportedParamsCombination(sampleParamsList);
}
if (isValidParam(query, SAMPLE)) {
String sampleValue = query.getString(SAMPLE.key());
if (sampleValue.contains(IS)) {
QueryParam newSampleParam;
String expectedValue = null;
if (sampleValue.toLowerCase().contains(IS + "denovo")) {
newSampleParam = SAMPLE_DE_NOVO;
expectedValue = "denovo";
} else if (sampleValue.toLowerCase().contains(IS + "mendelianerror")) {
newSampleParam = SAMPLE_MENDELIAN_ERROR;
expectedValue = "mendelianerror";
} else if (sampleValue.toLowerCase().contains(IS + "compoundheterozygous")) {
newSampleParam = SAMPLE_COMPOUND_HETEROZYGOUS;
expectedValue = "compoundheterozygous";
} else {
newSampleParam = GENOTYPE;
query.remove(SAMPLE.key());
query.put(newSampleParam.key(), sampleValue);
}
if (newSampleParam != GENOTYPE) {
ParsedQuery<String> parsedQuery = splitValue(query, SAMPLE);
if (QueryOperation.AND.equals(parsedQuery.getOperation())) {
throw VariantQueryException.malformedParam(SAMPLE, sampleValue, "Unsupported AND operator");
}
List<String> samples = new ArrayList<>(parsedQuery.getValues().size());
for (String value : parsedQuery.getValues()) {
if (!value.contains(IS)) {
throw VariantQueryException.malformedParam(SAMPLE, value);
}
String[] split = value.split(IS, 2);
if (!split[1].equalsIgnoreCase(expectedValue)) {
throw VariantQueryException.malformedParam(SAMPLE, sampleValue,
"Unable to mix " + expectedValue + " and " + split[1] + " filters.");
}
samples.add(split[0]);
}
query.remove(SAMPLE.key());
query.put(newSampleParam.key(), samples);
}
}
}
if (isValidParam(query, SAMPLE)) {
genotypeParam = SAMPLE;
if (defaultStudy == null) {
throw VariantQueryException.missingStudyForSamples(query.getAsStringList(SAMPLE.key()),
metadataManager.getStudyNames());
}
List<String> loadedGenotypes = defaultStudy.getAttributes().getAsStringList(LOADED_GENOTYPES.key());
if (CollectionUtils.isEmpty(loadedGenotypes)) {
loadedGenotypes = Arrays.asList(
"0/0", "0|0",
"0/1", "1/0", "1/1", "./.",
"0|1", "1|0", "1|1", ".|.",
"0|2", "2|0", "2|1", "1|2", "2|2",
"0/2", "2/0", "2/1", "1/2", "2/2",
GenotypeClass.UNKNOWN_GENOTYPE);
}
String genotypes;
List<String> mainGts = GenotypeClass.MAIN_ALT.filter(loadedGenotypes);
if (loadedGenotypes.contains(GenotypeClass.NA_GT_VALUE)
|| defaultStudy.getAttributes().getBoolean(EXCLUDE_GENOTYPES.key(), EXCLUDE_GENOTYPES.defaultValue())) {
mainGts.add(GenotypeClass.NA_GT_VALUE);
}
genotypes = String.join(",", mainGts);
Pair<QueryOperation, List<String>> pair = VariantQueryUtils.splitValue(query.getString(SAMPLE.key()));
genotypeOperator = pair.getLeft();
StringBuilder sb = new StringBuilder();
for (String sample : pair.getValue()) {
if (sb.length() > 0) {
sb.append(genotypeOperator.separator());
}
sb.append(sample).append(IS).append(genotypes);
}
query.remove(SAMPLE.key());
query.put(GENOTYPE.key(), sb.toString());
}
if (isValidParam(query, GENOTYPE)) {
genotypeParam = GENOTYPE;
List<String> loadedGenotypes = defaultStudy.getAttributes().getAsStringList(LOADED_GENOTYPES.key());
if (CollectionUtils.isEmpty(loadedGenotypes)) {
loadedGenotypes = Arrays.asList(
"0/0", "0|0",
"0/1", "1/0", "1/1", "./.",
"0|1", "1|0", "1|1", ".|.",
"0|2", "2|0", "2|1", "1|2", "2|2",
"0/2", "2/0", "2/1", "1/2", "2/2",
GenotypeClass.UNKNOWN_GENOTYPE);
}
Map<Object, List<String>> map = new LinkedHashMap<>();
genotypeOperator = VariantQueryUtils.parseGenotypeFilter(query.getString(GENOTYPE.key()), map);
String filter = preProcessGenotypesFilter(map, genotypeOperator, loadedGenotypes);
query.put(GENOTYPE.key(), filter);
}
if (formatOperator != null && genotypeOperator != null && formatOperator != genotypeOperator) {
throw VariantQueryException.mixedAndOrOperators(SAMPLE_DATA, genotypeParam);
}
if (isValidParam(query, SAMPLE_MENDELIAN_ERROR) || isValidParam(query, SAMPLE_DE_NOVO)) {
QueryParam param;
if (isValidParam(query, SAMPLE_MENDELIAN_ERROR) && isValidParam(query, SAMPLE_DE_NOVO)) {
throw VariantQueryException.unsupportedParamsCombination(
SAMPLE_MENDELIAN_ERROR, query.getString(SAMPLE_MENDELIAN_ERROR.key()),
SAMPLE_DE_NOVO, query.getString(SAMPLE_DE_NOVO.key()));
} else if (isValidParam(query, SAMPLE_MENDELIAN_ERROR)) {
param = SAMPLE_MENDELIAN_ERROR;
} else {
param = SAMPLE_DE_NOVO;
}
if (defaultStudy == null) {
throw VariantQueryException.missingStudyForSamples(query.getAsStringList(param.key()),
metadataManager.getStudyNames());
}
// Check no other samples filter is being used, and all samples are precomputed
if (genotypeParam != null) {
throw VariantQueryException.unsupportedParamsCombination(
param, query.getString(param.key()),
genotypeParam, query.getString(genotypeParam.key())
);
}
for (String sample : query.getAsStringList(param.key())) {
Integer sampleId = metadataManager.getSampleId(defaultStudy.getId(), sample);
if (sampleId == null) {
throw VariantQueryException.sampleNotFound(sample, defaultStudy.getName());
}
SampleMetadata sampleMetadata = metadataManager.getSampleMetadata(defaultStudy.getId(), sampleId);
if (!TaskMetadata.Status.READY.equals(sampleMetadata.getMendelianErrorStatus())) {
throw VariantQueryException.malformedParam(param, "Sample \"" + sampleMetadata.getName()
+ "\" does not have the Mendelian Errors precomputed yet");
}
}
}
if (isValidParam(query, SCORE)) {
String value = query.getString(SCORE.key());
List<String> values = splitValue(value).getValue();
for (String scoreFilter : values) {
String variantScore = splitOperator(scoreFilter)[0];
VariantScoreMetadata variantScoreMetadata;
String[] studyScore = splitStudyResource(variantScore);
if (studyScore.length == 2) {
int studyId = metadataManager.getStudyId(studyScore[0]);
variantScoreMetadata = metadataManager.getVariantScoreMetadata(studyId, studyScore[1]);
} else {
if (defaultStudy == null) {
throw VariantQueryException.missingStudyFor("score", variantScore, metadataManager.getStudyNames());
} else {
variantScoreMetadata = metadataManager.getVariantScoreMetadata(defaultStudy, variantScore);
}
}
if (variantScoreMetadata == null) {
throw VariantQueryException.scoreNotFound(variantScore, defaultStudy.getName());
}
}
}
if (!isValidParam(query, INCLUDE_STUDY)
|| !isValidParam(query, INCLUDE_SAMPLE)
|| !isValidParam(query, INCLUDE_FILE)
|| !isValidParam(query, SAMPLE_SKIP)
|| !isValidParam(query, SAMPLE_LIMIT)
) {
VariantQueryProjection selectVariantElements =
VariantQueryProjectionParser.parseVariantQueryFields(query, options, metadataManager);
// Apply the sample pagination.
// Remove the sampleLimit and sampleSkip to avoid applying the pagination twice
query.remove(SAMPLE_SKIP.key());
query.remove(SAMPLE_LIMIT.key());
query.put(NUM_TOTAL_SAMPLES.key(), selectVariantElements.getNumTotalSamples());
query.put(NUM_SAMPLES.key(), selectVariantElements.getNumSamples());
if (!isValidParam(query, INCLUDE_STUDY)) {
List<String> includeStudy = new ArrayList<>();
for (Integer studyId : selectVariantElements.getStudyIds()) {
includeStudy.add(selectVariantElements.getStudy(studyId).getStudyMetadata().getName());
}
if (includeStudy.isEmpty()) {
query.put(INCLUDE_STUDY.key(), NONE);
} else {
query.put(INCLUDE_STUDY.key(), includeStudy);
}
}
if (!isValidParam(query, INCLUDE_SAMPLE) || selectVariantElements.getSamplePagination()) {
List<String> includeSample = selectVariantElements.getSamples()
.entrySet()
.stream()
.flatMap(e -> e.getValue()
.stream()
.map(s -> metadataManager.getSampleName(e.getKey(), s)))
.collect(Collectors.toList());
if (includeSample.isEmpty()) {
query.put(INCLUDE_SAMPLE.key(), NONE);
} else {
query.put(INCLUDE_SAMPLE.key(), includeSample);
}
}
if (!isValidParam(query, INCLUDE_FILE) || selectVariantElements.getSamplePagination()) {
List<String> includeFile = selectVariantElements.getFiles()
.entrySet()
.stream()
.flatMap(e -> e.getValue()
.stream()
.map(f -> metadataManager.getFileName(e.getKey(), f)))
.collect(Collectors.toList());
if (includeFile.isEmpty()) {
query.put(INCLUDE_FILE.key(), NONE);
} else {
query.put(INCLUDE_FILE.key(), includeFile);
}
}
}
List<String> formats = getIncludeSampleData(query);
if (formats == null) {
formats = Collections.singletonList(ALL);
} else if (formats.isEmpty()) {
formats = Collections.singletonList(NONE);
}
query.put(INCLUDE_SAMPLE_DATA.key(), formats);
query.remove(INCLUDE_GENOTYPE.key(), formats);
}
public static String preProcessGenotypesFilter(Map<Object, List<String>> map, QueryOperation op, List<String> loadedGenotypes) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<Object, List<String>> entry : map.entrySet()) {
List<String> genotypes = preProcessGenotypesFilter(entry.getValue(), loadedGenotypes);
if (sb.length() > 0) {
sb.append(op.separator());
}
sb.append(entry.getKey()).append(IS);
for (int i = 0; i < genotypes.size(); i++) {
if (i > 0) {
sb.append(OR);
}
sb.append(genotypes.get(i));
}
}
return sb.toString();
}
public static List<String> preProcessGenotypesFilter(List<String> genotypesInput, List<String> loadedGenotypes) {
List<String> genotypes = new ArrayList<>(genotypesInput);
// Loop for multi-allelic values genotypes
// Iterate on genotypesInput, as this loop may add new values to List<String> genotypes
for (String genotypeStr : genotypesInput) {
boolean negated = isNegated(genotypeStr);
if (negated) {
genotypeStr = removeNegation(genotypeStr);
}
if (GenotypeClass.from(genotypeStr) != null) {
// Discard GenotypeClass
continue;
}
if (genotypeStr.equals(GenotypeClass.NA_GT_VALUE)) {
// Discard special genotypes
continue;
}
Genotype genotype;
try {
genotype = new Genotype(genotypeStr);
} catch (RuntimeException e) {
throw new VariantQueryException("Malformed genotype '" + genotypeStr + "'", e);
}
int[] allelesIdx = genotype.getAllelesIdx();
boolean multiallelic = false;
for (int i = 0; i < allelesIdx.length; i++) {
if (allelesIdx[i] > 1) {
allelesIdx[i] = 2;
multiallelic = true;
}
}
if (multiallelic) {
String regex = genotype.toString()
.replace(".", "\\.")
.replace("2", "([2-9]|[0-9][0-9])"); // Replace allele "2" with "any number >= 2")
Pattern pattern = Pattern.compile(regex);
for (String loadedGenotype : loadedGenotypes) {
if (pattern.matcher(loadedGenotype).matches()) {
genotypes.add((negated ? NOT : "") + loadedGenotype);
}
}
}
}
genotypes = GenotypeClass.filter(genotypes, loadedGenotypes);
if (genotypes.stream().anyMatch(VariantQueryUtils::isNegated) && !genotypes.stream().allMatch(VariantQueryUtils::isNegated)) {
throw VariantQueryException.malformedParam(GENOTYPE, genotypesInput.toString(),
"Can not mix negated and not negated genotypes");
}
// If empty, should find none. Add non-existing genotype
if (genotypes.isEmpty()) {
// TODO: Do fast fail, NO RESULTS!
genotypes = Collections.singletonList(GenotypeClass.NONE_GT_VALUE);
}
return genotypes;
}
/**
* Parses XREFS related filters, and sorts in different lists.
*
* - {@link VariantQueryParam#ID}
* - {@link VariantQueryParam#GENE}
* - {@link VariantQueryParam#ANNOT_XREF}
* - {@link VariantQueryParam#ANNOT_CLINVAR}
* - {@link VariantQueryParam#ANNOT_COSMIC}
*
* @param query Query to parse
* @return VariantQueryXref with all VariantIds, ids, genes and xrefs
*/
public static ParsedVariantQuery.VariantQueryXref parseXrefs(Query query) {
ParsedVariantQuery.VariantQueryXref xrefs = new ParsedVariantQuery.VariantQueryXref();
if (query == null) {
return xrefs;
}
xrefs.getGenes().addAll(query.getAsStringList(GENE.key(), OR));
if (isValidParam(query, ID)) {
List<String> idsList = query.getAsStringList(ID.key(), OR);
for (String value : idsList) {
Variant variant = toVariant(value);
if (variant != null) {
xrefs.getVariants().add(variant);
} else {
xrefs.getIds().add(value);
}
}
}
if (isValidParam(query, ANNOT_XREF)) {
List<String> xrefsList = query.getAsStringList(ANNOT_XREF.key(), OR);
for (String value : xrefsList) {
Variant variant = toVariant(value);
if (variant != null) {
xrefs.getVariants().add(variant);
} else {
if (isVariantAccession(value) || isClinicalAccession(value) || isGeneAccession(value)) {
xrefs.getOtherXrefs().add(value);
} else {
xrefs.getGenes().add(value);
}
}
}
}
// xrefs.getOtherXrefs().addAll(query.getAsStringList(ANNOT_HPO.key(), OR));
xrefs.getOtherXrefs().addAll(query.getAsStringList(ANNOT_COSMIC.key(), OR));
xrefs.getOtherXrefs().addAll(query.getAsStringList(ANNOT_CLINVAR.key(), OR));
return xrefs;
}
@Deprecated
public static StudyMetadata getDefaultStudy(Query query, VariantStorageMetadataManager metadataManager) {
return new VariantQueryParser(null, metadataManager).getDefaultStudy(query);
}
public StudyMetadata getDefaultStudy(Query query) {
final StudyMetadata defaultStudy;
if (isValidParam(query, STUDY)) {
String value = query.getString(STUDY.key());
// Check that the study exists
QueryOperation studiesOperation = checkOperator(value);
List<String> studiesNames = splitValue(value, studiesOperation);
List<Integer> studyIds = metadataManager.getStudyIds(studiesNames); // Non negated studyIds
if (studyIds.size() == 1) {
defaultStudy = metadataManager.getStudyMetadata(studyIds.get(0));
} else {
defaultStudy = null;
}
} else {
List<String> studyNames = metadataManager.getStudyNames();
if (studyNames != null && studyNames.size() == 1) {
defaultStudy = metadataManager.getStudyMetadata(studyNames.get(0));
} else {
defaultStudy = null;
}
}
return defaultStudy;
}
} |
package cgeo.geocaching.utils;
import cgeo.org.kxml2.io.KXmlSerializer;
import org.apache.commons.lang3.CharEncoding;
import org.xmlpull.v1.XmlSerializer;
import java.io.IOException;
import java.io.StringWriter;
import junit.framework.TestCase;
public class XmlUtilsTest extends TestCase {
private XmlSerializer xml;
private StringWriter stringWriter;
@Override
protected void setUp() throws Exception {
super.setUp();
stringWriter = new StringWriter();
xml = new KXmlSerializer();
xml.setOutput(stringWriter);
xml.startDocument(CharEncoding.UTF_8, null);
}
public void testSimpleText() throws Exception {
XmlUtils.simpleText(xml, "", "tag", "text");
assertXmlEquals("<tag>text</tag>");
}
public void testSimpleTextWithPrefix() throws Exception {
XmlUtils.simpleText(xml, "prefix", "tag", "text");
assertXmlEquals("<n0:tag xmlns:n0=\"prefix\">text</n0:tag>");
}
private void assertXmlEquals(final String expected) throws IOException {
xml.endDocument();
xml.flush();
assertEquals("<?xml version='1.0' encoding='UTF-8' ?>" + expected, stringWriter.toString());
}
public void testMultipleTexts() throws Exception {
XmlUtils.multipleTexts(xml, "", "tag1", "text1", "tag2", "text2");
assertXmlEquals("<tag1>text1</tag1><tag2>text2</tag2>");
}
} |
package org.yakindu.sct.generator.core.filesystem;
import static org.yakindu.sct.generator.core.filesystem.ISCTFileSystemAccess.API_TARGET_FOLDER_OUTPUT;
import static org.yakindu.sct.generator.core.filesystem.ISCTFileSystemAccess.LIBRARY_TARGET_FOLDER_OUTPUT;
import static org.yakindu.sct.generator.core.library.ICoreLibraryConstants.OUTLET_FEATURE_TARGET_PROJECT;
import java.io.File;
import org.eclipse.emf.common.util.URI;
import org.eclipse.xtext.generator.IFileSystemAccess;
import org.eclipse.xtext.generator.OutputConfiguration;
import org.yakindu.sct.generator.core.console.IConsoleLogger;
import org.yakindu.sct.generator.core.library.ICoreLibraryHelper;
import org.yakindu.sct.model.sgen.FeatureParameterValue;
import org.yakindu.sct.model.sgen.GeneratorEntry;
import com.google.inject.Inject;
import com.google.inject.Provider;
/**
* @author andreas muelder - Initial contribution and API
*
*/
public class DefaultFileSystemAccessFactory {
@Inject
protected IConsoleLogger logger;
@Inject
protected Provider<ISCTFileSystemAccess> fileSystemProvider;
@Inject
protected ICoreLibraryHelper helper;
public ISCTFileSystemAccess create(GeneratorEntry entry) {
ISCTFileSystemAccess result = fileSystemProvider.get();
initTargetProject(result, entry);
initDefaultOutput(result, entry);
initLibraryTargetFolder(result, entry);
initApiTargetFolder(result, entry);
return result;
}
protected void initTargetProject(ISCTFileSystemAccess access, GeneratorEntry entry) {
String targetProjectName = helper.getTargetProjectValue(entry).getStringValue();
access.setContext(targetProjectName);
access.setOutputPath(OUTLET_FEATURE_TARGET_PROJECT, targetProjectName);
}
protected void initDefaultOutput(ISCTFileSystemAccess access, GeneratorEntry entry) {
String folderName = helper.getTargetFolderValue(entry).getStringValue();
access.setOutputPath(IFileSystemAccess.DEFAULT_OUTPUT, folderName);
access.getOutputConfigurations().get(IFileSystemAccess.DEFAULT_OUTPUT).setCreateOutputDirectory(true);
checkWriteAccess(access, IFileSystemAccess.DEFAULT_OUTPUT, folderName);
}
protected void initLibraryTargetFolder(ISCTFileSystemAccess access, GeneratorEntry entry) {
FeatureParameterValue libraryTargetFolderValue = helper.getLibraryTargetFolderValue(entry);
if (libraryTargetFolderValue != null) {
String folderName = libraryTargetFolderValue.getStringValue();
access.setOutputPath(LIBRARY_TARGET_FOLDER_OUTPUT, folderName);
OutputConfiguration output = access.getOutputConfigurations().get(LIBRARY_TARGET_FOLDER_OUTPUT);
checkWriteAccess(access, LIBRARY_TARGET_FOLDER_OUTPUT, folderName);
output.setCreateOutputDirectory(true);
output.setCanClearOutputDirectory(false);
output.setOverrideExistingResources(false);
}
}
protected void initApiTargetFolder(ISCTFileSystemAccess access, GeneratorEntry entry) {
FeatureParameterValue apiTargetFolderValue = helper.getApiTargetFolderValue(entry);
if (apiTargetFolderValue != null) {
String folderName = apiTargetFolderValue.getStringValue();
access.setOutputPath(API_TARGET_FOLDER_OUTPUT, folderName);
OutputConfiguration output = access.getOutputConfigurations().get(API_TARGET_FOLDER_OUTPUT);
checkWriteAccess(access, API_TARGET_FOLDER_OUTPUT, folderName);
output.setCreateOutputDirectory(true);
}
}
private void checkWriteAccess(ISCTFileSystemAccess access, String outputConfiguration, String folderName) {
URI uri = access.getURI("", outputConfiguration);
if (uri.isFile()) {
File file = new File(uri.path());
if (!file.exists()) return;
if (!file.canWrite()) {
logger.log(String.format("Can not generate files to read-only folder '%s'. ", folderName));
}
}
}
} |
package org.ow2.proactive_grid_cloud_portal.scheduler.client.view;
import java.util.Date;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.layout.LayoutSpacer;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.Job;
import org.ow2.proactive_grid_cloud_portal.scheduler.client.controller.TasksCentricNavigationController;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.RelativeDateItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
import com.smartgwt.client.widgets.layout.Layout;
public class TasksCentricNavigationView extends TasksNavigationView{
public TasksCentricNavigationView(TasksCentricNavigationController controller) {
super(controller);
}
Canvas datesCanvas;
RelativeDateItem fromDateItem;
RelativeDateItem toDateItem;
@Override
public Layout build() {
Layout layout = super.build();
fromDateItem = new RelativeDateItem("fromDate", "from");
fromDateItem.addChangedHandler(new ChangedHandler() {
@Override
public void onChanged(ChangedEvent event) {
fromDateChangedHandler(event);
}
});
toDateItem = new RelativeDateItem("toDate", "to");
toDateItem.addChangedHandler(new ChangedHandler() {
@Override
public void onChanged(ChangedEvent event) {
toDateChangedHandler(event);
}
});
DynamicForm form = new DynamicForm();
form.setNumCols(4);
form.setItems(fromDateItem, toDateItem);
//form.setStyleName("form");
layout.addMember(form);
datesCanvas = fromDateItem.getContainerWidget();
// The far right of the canvas border isn't visible
LayoutSpacer spacer = new LayoutSpacer(5,datesCanvas.getHeight());
layout.addMember(spacer);
return layout;
}
protected void fromDateChangedHandler(ChangedEvent event){
Date value = (Date) event.getValue();
long fromDate = value.getTime();
if (dateRangeIsValid()) {
resetDatesCanvasBGColor();
((TasksCentricNavigationController) this.controller).changeFromDate(fromDate);
}
else {
highlightDates();
}
}
protected void toDateChangedHandler(ChangedEvent event){
Date value = (Date) event.getValue();
long toDate = value.getTime();
if (dateRangeIsValid()) {
resetDatesCanvasBGColor();
((TasksCentricNavigationController) this.controller).changeToDate(toDate);
}
else {
highlightDates();
}
}
private boolean dateRangeIsValid() {
long fromDate = RelativeDateItem.getAbsoluteDate(fromDateItem.getRelativeDate()).getTime();
long toDate = RelativeDateItem.getAbsoluteDate(toDateItem.getRelativeDate()).getTime();
return fromDate < toDate;
}
private void resetDatesCanvasBGColor() {
datesCanvas.setBorder("");
}
private void highlightDates() {
datesCanvas.setBorder("2px solid red");
}
@Override
public void jobSelected(Job job) {
}
@Override
public void jobUnselected() {
}
} |
package com.azure.messaging.eventhubs;
import com.azure.core.util.IterableStream;
import com.azure.core.util.logging.ClientLogger;
import com.azure.messaging.eventhubs.implementation.IntegrationTestBase;
import com.azure.messaging.eventhubs.implementation.IntegrationTestEventData;
import com.azure.messaging.eventhubs.models.EventHubProducerOptions;
import com.azure.messaging.eventhubs.models.EventPosition;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import reactor.core.scheduler.Schedulers;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.stream.Collectors;
import static com.azure.messaging.eventhubs.EventHubAsyncClient.DEFAULT_CONSUMER_GROUP_NAME;
public class EventHubConsumerIntegrationTest extends IntegrationTestBase {
private static final String PARTITION_ID = "0";
private static final int NUMBER_OF_EVENTS = 10;
private static final AtomicBoolean HAS_PUSHED_EVENTS = new AtomicBoolean();
private static volatile IntegrationTestEventData testData = null;
private EventHubClient client;
private EventHubConsumer consumer;
// We use these values to keep track of the events we've pushed to the service and ensure the events we receive are
// our own.
public EventHubConsumerIntegrationTest() {
super(new ClientLogger(EventHubConsumerIntegrationTest.class));
}
@Rule
public TestName testName = new TestName();
@Override
protected String getTestName() {
return testName.getMethodName();
}
@Override
protected void beforeTest() {
super.beforeTest();
client = new EventHubClientBuilder()
.connectionString(getConnectionString())
.scheduler(Schedulers.single())
.retry(RETRY_OPTIONS)
.buildClient();
if (HAS_PUSHED_EVENTS.getAndSet(true)) {
logger.info("Already pushed events to partition. Skipping.");
} else {
final EventHubProducerOptions options = new EventHubProducerOptions().setPartitionId(PARTITION_ID);
testData = setupEventTestData(client, NUMBER_OF_EVENTS, options);
}
consumer = client.createConsumer(DEFAULT_CONSUMER_GROUP_NAME, PARTITION_ID,
EventPosition.fromEnqueuedTime(testData.getEnqueuedTime()));
}
@Override
protected void afterTest() {
dispose(consumer, client);
}
/**
* Verifies that we can receive events a single time that is up to the batch size.
*/
@Test
public void receiveEvents() {
// Arrange
final int numberOfEvents = 5;
// Act
final IterableStream<EventData> actual = consumer.receive(numberOfEvents, Duration.ofSeconds(10));
// Assert
final List<EventData> asList = actual.stream().collect(Collectors.toList());
Assert.assertEquals(numberOfEvents, asList.size());
}
/**
* Verifies that we can receive multiple times.
*/
@Test
public void receiveEventsMultipleTimes() {
// Arrange
final int numberOfEvents = 5;
final int secondNumberOfEvents = 2;
final Duration waitTime = Duration.ofSeconds(10);
// Act
final IterableStream<EventData> actual = consumer.receive(numberOfEvents, waitTime);
final IterableStream<EventData> actual2 = consumer.receive(secondNumberOfEvents, waitTime);
// Assert
final Map<Long, EventData> asList = actual.stream()
.collect(Collectors.toMap(EventData::getSequenceNumber, Function.identity()));
Assert.assertEquals(numberOfEvents, asList.size());
final Map<Long, EventData> asList2 = actual2.stream()
.collect(Collectors.toMap(EventData::getSequenceNumber, Function.identity()));
Assert.assertEquals(secondNumberOfEvents, asList2.size());
final Long maximumSequence = Collections.max(asList.keySet());
final Long minimumSequence = Collections.min(asList2.keySet());
Assert.assertTrue("The minimum in second receive should be less than first receive.",
maximumSequence < minimumSequence);
}
/**
* Verify that we can receive until the timeout.
*/
@Test
public void receiveUntilTimeout() {
// Arrange
final int numberOfEvents = 15;
final String partitionId = "1";
final List<EventData> events = getEventsAsList(numberOfEvents);
final EventPosition position = EventPosition.fromEnqueuedTime(Instant.now());
final EventHubConsumer consumer = client.createConsumer(DEFAULT_CONSUMER_GROUP_NAME, partitionId, position);
final EventHubProducer producer = client.createProducer(new EventHubProducerOptions().setPartitionId(partitionId));
try {
producer.send(events);
// Act
final IterableStream<EventData> receive = consumer.receive(100, Duration.ofSeconds(5));
// Assert
final List<EventData> asList = receive.stream().collect(Collectors.toList());
Assert.assertEquals(numberOfEvents, asList.size());
} finally {
dispose(producer, consumer);
}
}
/**
* Verify that we don't continue to fetch more events when there are no listeners.
*/
@Test
public void doesNotContinueToReceiveEvents() {
// Arrange
final int numberOfEvents = 15;
final int secondSetOfEvents = 25;
final int receiveNumber = 10;
final String partitionId = "1";
final List<EventData> events = getEventsAsList(numberOfEvents);
final List<EventData> events2 = getEventsAsList(secondSetOfEvents);
final EventHubConsumer consumer = client.createConsumer(DEFAULT_CONSUMER_GROUP_NAME, partitionId,
EventPosition.fromEnqueuedTime(Instant.now()));
final EventHubProducer producer = client.createProducer(new EventHubProducerOptions().setPartitionId(partitionId));
try {
producer.send(events);
// Act
final IterableStream<EventData> receive = consumer.receive(receiveNumber, Duration.ofSeconds(5));
// Assert
final List<EventData> asList = receive.stream().collect(Collectors.toList());
Assert.assertEquals(receiveNumber, asList.size());
producer.send(events2);
} finally {
dispose(consumer, producer);
}
}
/**
* Verify that we don't continue to fetch more events when there are no listeners.
*/
@Test
public void multipleConsumers() {
final int numberOfEvents = 15;
final int receiveNumber = 10;
final String partitionId = "1";
final List<EventData> events = getEventsAsList(numberOfEvents);
final EventPosition position = EventPosition.fromEnqueuedTime(Instant.now());
final EventHubConsumer consumer = client.createConsumer(DEFAULT_CONSUMER_GROUP_NAME, partitionId, position);
final EventHubConsumer consumer2 = client.createConsumer(DEFAULT_CONSUMER_GROUP_NAME, partitionId, position);
final EventHubProducer producer = client.createProducer(new EventHubProducerOptions().setPartitionId(partitionId));
try {
producer.send(events);
// Act
final IterableStream<EventData> receive = consumer.receive(receiveNumber, Duration.ofSeconds(5));
final IterableStream<EventData> receive2 = consumer2.receive(receiveNumber, Duration.ofSeconds(5));
// Assert
final List<Long> asList = receive.stream().map(EventData::getSequenceNumber).collect(Collectors.toList());
final List<Long> asList2 = receive2.stream().map(EventData::getSequenceNumber).collect(Collectors.toList());
Assert.assertEquals(receiveNumber, asList.size());
Assert.assertEquals(receiveNumber, asList2.size());
Collections.sort(asList);
Collections.sort(asList2);
final Long[] first = asList.toArray(new Long[0]);
final Long[] second = asList2.toArray(new Long[0]);
Assert.assertArrayEquals(first, second);
} finally {
dispose(consumer, producer);
}
}
private static List<EventData> getEventsAsList(int numberOfEvents) {
return TestUtils.getEvents(numberOfEvents, TestUtils.MESSAGE_TRACKING_ID).collectList().block();
}
} |
package org.collectionspace.services.client.test;
import java.util.List;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.collectionspace.services.client.CollectionObjectClient;
import org.collectionspace.services.collectionobject.CollectionobjectsCommon;
import org.collectionspace.services.collectionobject.domain.naturalhistory.CollectionObjectNaturalhistory;
import org.collectionspace.services.collectionobject.CollectionobjectsCommonList;
import org.jboss.resteasy.client.ClientResponse;
import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
import org.jboss.resteasy.plugins.providers.multipart.MultipartOutput;
import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
import org.testng.Assert;
import org.testng.annotations.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* CollectionObjectServiceTest, carries out tests against a
* deployed and running CollectionObject Service.
*
* $LastChangedRevision$
* $LastChangedDate$
*/
public class CollectionObjectServiceTest extends AbstractServiceTest {
private final Logger logger =
LoggerFactory.getLogger(CollectionObjectServiceTest.class);
// Instance variables specific to this test.
private CollectionObjectClient client = new CollectionObjectClient();
private String knownResourceId = null;
/*
* This method is called only by the parent class, AbstractServiceTest
*/
@Override
protected String getServicePathComponent() {
return client.getServicePathComponent();
}
// CRUD tests : CREATE tests
// Success outcomes
@Override
@Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class)
public void create(String testName) throws Exception {
// Perform setup, such as initializing the type of service request
// (e.g. CREATE, DELETE), its valid and expected status codes, and
// its associated HTTP method name (e.g. POST, DELETE).
setupCreate(testName);
// Submit the request to the service and store the response.
String identifier = createIdentifier();
MultipartOutput multipart =
createCollectionObjectInstance(client.getCommonPartName(), identifier);
ClientResponse<Response> res = client.create(multipart);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
// Specifically:
// Does it fall within the set of valid status codes?
// Does it exactly match the expected status code?
if(logger.isDebugEnabled()){
logger.debug(testName + ": status = " + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
// Store the ID returned from this create operation
// for additional tests below.
knownResourceId = extractId(res);
if(logger.isDebugEnabled()){
logger.debug(testName + ": knownResourceId=" + knownResourceId);
}
}
/* (non-Javadoc)
* @see org.collectionspace.services.client.test.ServiceTest#createList()
*/
@Override
@Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class,
dependsOnMethods = {"create"})
public void createList(String testName) throws Exception {
for(int i = 0; i < 3; i++){
create(testName);
}
}
// Failure outcomes
// Placeholders until the three tests below can be uncommented.
// See Issue CSPACE-401.
@Override
public void createWithEmptyEntityBody(String testName) throws Exception {}
@Override
public void createWithMalformedXml(String testName) throws Exception {}
@Override
public void createWithWrongXmlSchema(String testName) throws Exception {}
/*
@Override
@Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class,
dependsOnMethods = {"create", "testSubmitRequest"})
public void createWithEmptyEntityBody(String testName) throwsException {
// Perform setup.
setupCreateWithEmptyEntityBody(testName);
// Submit the request to the service and store the response.
String method = REQUEST_TYPE.httpMethodName();
String url = getServiceRootURL();
String mediaType = MediaType.APPLICATION_XML;
final String entity = "";
int statusCode = submitRequest(method, url, mediaType, entity);
// Check the status code of the response: does it match
// the expected response(s)?
if(logger.isDebugEnabled()){
logger.debug(testName + ": url=" + url +
" status=" + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
@Override
@Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class,
dependsOnMethods = {"create", "testSubmitRequest"})
public void createWithMalformedXml(String testName) throws Exception {
// Perform setup.
setupCreateWithMalformedXml(testName);
// Submit the request to the service and store the response.
String method = REQUEST_TYPE.httpMethodName();
String url = getServiceRootURL();
String mediaType = MediaType.APPLICATION_XML;
final String entity = MALFORMED_XML_DATA; // Constant from base class.
int statusCode = submitRequest(method, url, mediaType, entity);
// Check the status code of the response: does it match
// the expected response(s)?
if(logger.isDebugEnabled()){
logger.debug(testName + ": url=" + url +
" status=" + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
@Override
@Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class,
dependsOnMethods = {"create", "testSubmitRequest"})
public void createWithWrongXmlSchema(String testName) throws Exception {
// Perform setup.
setupCreateWithWrongXmlSchema(testName);
// Submit the request to the service and store the response.
String method = REQUEST_TYPE.httpMethodName();
String url = getServiceRootURL();
String mediaType = MediaType.APPLICATION_XML;
final String entity = WRONG_XML_SCHEMA_DATA;
int statusCode = submitRequest(method, url, mediaType, entity);
// Check the status code of the response: does it match
// the expected response(s)?
if(logger.isDebugEnabled()){
logger.debug(testName + ": url=" + url +
" status=" + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
*/
// CRUD tests : READ tests
// Success outcomes
@Override
@Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class,
dependsOnMethods = {"create"})
public void read(String testName) throws Exception {
// Perform setup.
setupRead(testName);
// Submit the request to the service and store the response.
ClientResponse<MultipartInput> res = client.read(knownResourceId);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
if(logger.isDebugEnabled()){
logger.debug(testName + ": status = " + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
MultipartInput input = (MultipartInput) res.getEntity();
CollectionobjectsCommon collectionObject =
(CollectionobjectsCommon) extractPart(input,
client.getCommonPartName(), CollectionobjectsCommon.class);
Assert.assertNotNull(collectionObject);
}
// Failure outcomes
@Override
@Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class,
dependsOnMethods = {"read"})
public void readNonExistent(String testName) throws Exception {
// Perform setup.
setupReadNonExistent(testName);
// Submit the request to the service and store the response.
ClientResponse<MultipartInput> res = client.read(NON_EXISTENT_ID);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
if(logger.isDebugEnabled()){
logger.debug(testName + ": status = " + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
// CRUD tests : READ_LIST tests
// Success outcomes
@Override
@Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class,
dependsOnMethods = {"createList", "read"})
public void readList(String testName) throws Exception {
// Perform setup.
setupReadList(testName);
// Submit the request to the service and store the response.
ClientResponse<CollectionobjectsCommonList> res = client.readList();
CollectionobjectsCommonList list = res.getEntity();
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
if(logger.isDebugEnabled()){
logger.debug(testName + ": status = " + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
// Optionally output additional data about list members for debugging.
boolean iterateThroughList = false;
if (iterateThroughList && logger.isDebugEnabled()) {
List<CollectionobjectsCommonList.CollectionObjectListItem> items =
list.getCollectionObjectListItem();
int i = 0;
for(CollectionobjectsCommonList.CollectionObjectListItem item : items){
logger.debug(testName + ": list-item[" + i + "] csid=" +
item.getCsid());
logger.debug(testName + ": list-item[" + i + "] objectNumber=" +
item.getObjectNumber());
logger.debug(testName + ": list-item[" + i + "] URI=" +
item.getUri());
i++;
}
}
}
// Failure outcomes
// None at present.
// CRUD tests : UPDATE tests
// Success outcomes
@Override
@Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class,
dependsOnMethods = {"read"})
public void update(String testName) throws Exception {
// Perform setup.
setupUpdate(testName);
ClientResponse<MultipartInput> res =
client.read(knownResourceId);
if(logger.isDebugEnabled()){
logger.debug(testName + ": read status = " + res.getStatus());
}
Assert.assertEquals(res.getStatus(), EXPECTED_STATUS_CODE);
if(logger.isDebugEnabled()){
logger.debug("got object to update with ID: " + knownResourceId);
}
MultipartInput input = (MultipartInput) res.getEntity();
CollectionobjectsCommon collectionObject =
(CollectionobjectsCommon) extractPart(input,
client.getCommonPartName(), CollectionobjectsCommon.class);
Assert.assertNotNull(collectionObject);
// Update the content of this resource.
collectionObject.setObjectNumber("updated-" + collectionObject.getObjectNumber());
collectionObject.setObjectName("updated-" + collectionObject.getObjectName());
if(logger.isDebugEnabled()){
verbose("updated object", collectionObject,
CollectionobjectsCommon.class);
}
// Submit the request to the service and store the response.
MultipartOutput output = new MultipartOutput();
OutputPart commonPart = output.addPart(collectionObject, MediaType.APPLICATION_XML_TYPE);
commonPart.getHeaders().add("label", client.getCommonPartName());
res = client.update(knownResourceId, output);
int statusCode = res.getStatus();
// Check the status code of the response: does it match the expected response(s)?
if(logger.isDebugEnabled()){
logger.debug(testName + ": status = " + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
input = (MultipartInput) res.getEntity();
CollectionobjectsCommon updatedCollectionObject =
(CollectionobjectsCommon) extractPart(input,
client.getCommonPartName(), CollectionobjectsCommon.class);
Assert.assertNotNull(updatedCollectionObject);
Assert.assertEquals(updatedCollectionObject.getObjectName(),
collectionObject.getObjectName(),
"Data in updated object did not match submitted data.");
}
// Failure outcomes
// Placeholders until the three tests below can be uncommented.
// See Issue CSPACE-401.
@Override
public void updateWithEmptyEntityBody(String testName) throws Exception {}
@Override
public void updateWithMalformedXml(String testName) throws Exception {}
@Override
public void updateWithWrongXmlSchema(String testName) throws Exception {}
/*
@Override
@Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class,
dependsOnMethods = {"create", "update", "testSubmitRequest"})
public void updateWithEmptyEntityBody(String testName) throws Exception {
// Perform setup.
setupUpdateWithEmptyEntityBody(testName);
// Submit the request to the service and store the response.
String method = REQUEST_TYPE.httpMethodName();
String url = getResourceURL(knownResourceId);
String mediaType = MediaType.APPLICATION_XML;
final String entity = "";
int statusCode = submitRequest(method, url, mediaType, entity);
// Check the status code of the response: does it match
// the expected response(s)?
if(logger.isDebugEnabled()){
logger.debug(testName + ": url=" + url +
" status=" + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
@Override
@Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class,
dependsOnMethods = {"create", "update", "testSubmitRequest"})
public void updateWithMalformedXml() throws Exception {
// Perform setup.
setupUpdateWithMalformedXml(testName);
// Submit the request to the service and store the response.
String method = REQUEST_TYPE.httpMethodName();
String url = getResourceURL(knownResourceId);
final String entity = MALFORMED_XML_DATA;
String mediaType = MediaType.APPLICATION_XML;
int statusCode = submitRequest(method, url, mediaType, entity);
// Check the status code of the response: does it match
// the expected response(s)?
if(logger.isDebugEnabled()){
logger.debug(testName + ": url=" + url +
" status=" + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
@Override
@Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class,
dependsOnMethods = {"create", "update", "testSubmitRequest"})
public void updateWithWrongXmlSchema(String testName) throws Exception {
// Perform setup.
setupUpdateWithWrongXmlSchema(String testName);
// Submit the request to the service and store the response.
String method = REQUEST_TYPE.httpMethodName();
String url = getResourceURL(knownResourceId);
String mediaType = MediaType.APPLICATION_XML;
final String entity = WRONG_XML_SCHEMA_DATA;
int statusCode = submitRequest(method, url, mediaType, entity);
// Check the status code of the response: does it match
// the expected response(s)?
if(logger.isDebugEnabled()){
logger.debug(testName + ": url=" + url +
" status=" + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
*/
@Override
@Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class,
dependsOnMethods = {"update", "testSubmitRequest"})
public void updateNonExistent(String testName) throws Exception {
// Perform setup.
setupUpdateNonExistent(testName);
// Submit the request to the service and store the response.
// Note: The ID used in this 'create' call may be arbitrary.
// The only relevant ID may be the one used in updateCollectionObject(), below.
MultipartOutput multipart =
createCollectionObjectInstance(client.getCommonPartName(),
NON_EXISTENT_ID);
ClientResponse<MultipartInput> res =
client.update(NON_EXISTENT_ID, multipart);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
if(logger.isDebugEnabled()){
logger.debug(testName + ": status = " + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
// CRUD tests : DELETE tests
// Success outcomes
@Override
@Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class,
dependsOnMethods = {"create", "readList", "testSubmitRequest", "update"})
public void delete(String testName) throws Exception {
// Perform setup.
setupDelete(testName);
// Submit the request to the service and store the response.
ClientResponse<Response> res = client.delete(knownResourceId);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
if(logger.isDebugEnabled()){
logger.debug(testName + ": status = " + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
// Failure outcomes
@Override
@Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class,
dependsOnMethods = {"delete"})
public void deleteNonExistent(String testName) throws Exception {
// Perform setup.
setupDeleteNonExistent(testName);
// Submit the request to the service and store the response.
ClientResponse<Response> res = client.delete(NON_EXISTENT_ID);
int statusCode = res.getStatus();
// Check the status code of the response: does it match
// the expected response(s)?
if(logger.isDebugEnabled()){
logger.debug(testName + ": status = " + statusCode);
}
Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode),
invalidStatusCodeMessage(REQUEST_TYPE, statusCode));
Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE);
}
// Utility tests : tests of code used in tests above
/**
* Tests the code for manually submitting data that is used by several
* of the methods above.
*/
@Test(dependsOnMethods = {"create", "read"})
public void testSubmitRequest() throws Exception {
// Expected status code: 200 OK
final int EXPECTED_STATUS = Response.Status.OK.getStatusCode();
// Submit the request to the service and store the response.
String method = ServiceRequestType.READ.httpMethodName();
String url = getResourceURL(knownResourceId);
int statusCode = submitRequest(method, url);
// Check the status code of the response: does it match
// the expected response(s)?
if(logger.isDebugEnabled()){
logger.debug("testSubmitRequest: url=" + url +
" status=" + statusCode);
}
Assert.assertEquals(statusCode, EXPECTED_STATUS);
}
// Utility methods used by tests above
private MultipartOutput createCollectionObjectInstance(String commonPartName,
String identifier) {
return createCollectionObjectInstance(commonPartName,
"objectNumber-" + identifier,
"objectName-" + identifier);
}
private MultipartOutput createCollectionObjectInstance(String commonPartName,
String objectNumber, String objectName) {
CollectionobjectsCommon collectionObject = new CollectionobjectsCommon();
collectionObject.setObjectNumber(objectNumber);
collectionObject.setObjectName(objectName);
collectionObject.setAge(""); //test for null string
collectionObject.setBriefDescription("Papier mache bird mask with horns, " +
"painted red with black and yellow spots. " +
"Puerto Rico. ca. 8" high, 6" wide, projects 10" (with horns).");
MultipartOutput multipart = new MultipartOutput();
OutputPart commonPart = multipart.addPart(collectionObject,
MediaType.APPLICATION_XML_TYPE);
commonPart.getHeaders().add("label", commonPartName);
if(logger.isDebugEnabled()){
verbose("to be created, collectionobject common ",
collectionObject, CollectionobjectsCommon.class);
}
CollectionObjectNaturalhistory conh = new CollectionObjectNaturalhistory();
conh.setNhString("test-string");
conh.setNhInt(999);
conh.setNhLong(9999);
OutputPart nhPart = multipart.addPart(conh, MediaType.APPLICATION_XML_TYPE);
nhPart.getHeaders().add("label", getNHPartName());
if(logger.isDebugEnabled()){
verbose("to be created, collectionobject nhistory",
conh, CollectionObjectNaturalhistory.class);
}
return multipart;
}
private String getNHPartName() {
return "collectionobjects-naturalhistory";
}
} |
package com.health;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsIterableWithSize.iterableWithSize;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
import java.time.LocalDate;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
/**
* Unit test for Record.
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Column.class, Table.class })
public class RecordTest {
private static final String value1 = "abc";
private static final Double value2 = 1.5;
private static final LocalDate value3 = LocalDate.of(1970, 1, 1);
private Column column1;
private Column column2;
private Column column3;
private Record record;
private Table table;
/**
* Sets up mocks and default values used during tests.
*/
@Before
public void setUp() {
// Create mock columns
column1 = mock(Column.class);
when(column1.getIndex()).thenReturn(0);
when(column1.getName()).thenReturn("column1");
when(column1.getType()).thenReturn(ValueType.String);
when(column1.isFrequencyColumn()).thenReturn(false);
column2 = mock(Column.class);
when(column2.getIndex()).thenReturn(1);
when(column2.getName()).thenReturn("column2");
when(column2.getType()).thenReturn(ValueType.Number);
when(column2.isFrequencyColumn()).thenReturn(false);
column3 = mock(Column.class);
when(column3.getIndex()).thenReturn(2);
when(column3.getName()).thenReturn("column3");
when(column3.getType()).thenReturn(ValueType.Date);
when(column3.isFrequencyColumn()).thenReturn(false);
// Create mock table
table = mock(Table.class);
when(table.getColumn(anyString())).thenReturn(null);
when(table.getColumn(column1.getIndex())).thenReturn(column1);
when(table.getColumn(column2.getIndex())).thenReturn(column2);
when(table.getColumn(column3.getIndex())).thenReturn(column3);
when(table.getColumn(column1.getName())).thenReturn(column1);
when(table.getColumn(column2.getName())).thenReturn(column2);
when(table.getColumn(column3.getName())).thenReturn(column3);
when(table.getColumns()).thenReturn(Arrays.asList(column1, column2, column3));
when(table.getDateColumn()).thenReturn(column3);
// Create mock record
record = new Record(table);
record.setValue(column1.getName(), value1);
record.setValue(column2.getName(), value2);
record.setValue(column3.getName(), value3);
}
/**
* Tests whether {@link Record#Record(Table)} throws a
* {@link NullPointerException} when given a null reference.
*/
@Test(expected = NullPointerException.class)
public void constructor_givenTableNull_throwsNullPointerException() {
new Record((Table) null);
}
/**
* Tests whether {@link Record#Record(Table)} sets the record's table.
*/
@Test
public void constructor_givenTable_setsTable() {
Record record = new Record(table);
Table expected = table;
Table actual = record.getTable();
assertSame(expected, actual);
}
/**
* Tests whether {@link Record#Record(Table)} allocates an iterable for the
* record's values that has a length matching the number of columns of the
* given table.
*/
@Test
public void constructor_givenTable_setsValues() {
Record record = new Record(table);
assertThat(record.getValues(), iterableWithSize(3));
}
/**
* Tests whether {@link Record#Record(Table)} calls
* {@link Table#addRecord(Record)} to add itself to the given table.
*/
@Test
public void constructor_givenTable_callsAddRecord() {
Record record = new Record(table);
verify(table).addRecord(record);
}
@Test
public void getValue_givenIndexOfNonexistentColumn_returnsNull() {
assertNull(record.getValue(-1));
}
@Test
public void getValue_givenIndexOfColumn_returnsValueOfColumn() {
Object expected = value1;
Object actual = record.getValue(column1.getIndex());
assertEquals(expected, actual);
}
/**
* Tests whether {@link Record#getValue(String)} returns null when given a
* null reference.
*/
@Test
public void getValue_givenNameNull_returnsNull() {
assertNull(record.getValue(null));
}
/**
* Tests whether {@link Record#getValue(String)} returns null when given a
* name of a nonexistent column.
*/
@Test
public void getValue_givenNameOfNonexistentColumn_returnsNull() {
assertNull(record.getValue("null"));
}
/**
* Tests whether {@link Record#getValue(String)} returns the value of the
* right column given the name of the column.
*/
@Test
public void getValue_givenNameOfColumn_returnsValueOfColumn() {
Object expected = value1;
Object actual = record.getValue(column1.getName());
assertEquals(expected, actual);
}
@Test
public void getNumberValue_givenNameOfColumnWithNumberNull_returnsZero() {
record.setValue(column2.getName(), (Double) null);
Double expected = (Double) 0.0;
Double actual = record.getNumberValue(column2.getName());
assertEquals(expected, actual);
}
/**
* Tests whether {@link Record#getNumberValue(String)} returns the correct
* {@link Double} when given the name of a column that contains Doubles.
*/
@Test
public void getNumberValue_givenNameOfColumnWithNumber_returnsNumber() {
Double expected = (Double) value2;
Double actual = record.getNumberValue(column2.getName());
assertEquals(expected, actual);
}
@Test(expected = IllegalStateException.class)
public void getNumberValue_givenNameOfColumnWithString_throwsIllegalStateException() {
record.getNumberValue(column1.getName());
}
@Test(expected = IllegalStateException.class)
public void getNumberValue_givenNameOfColumnWithDate_throwsIllegalStateException() {
record.getNumberValue(column3.getName());
}
/**
* Tests whether {@link Record#getStringValue(String)} returns the correct
* {@link String} when given the name of a column that contains Strings.
*/
@Test
public void getStringValue_givenNameOfColumnWithString_returnsString() {
String expected = (String) value1;
String actual = record.getStringValue(column1.getName());
assertEquals(expected, actual);
}
@Test(expected = IllegalStateException.class)
public void getStringValue_givenNameOfColumnWithNumber_throwsIllegalStateException() {
record.getStringValue(column2.getName());
}
@Test(expected = IllegalStateException.class)
public void getStringValue_givenNameOfColumnWithDate_throwsIllegalStateException() {
record.getStringValue(column3.getName());
}
/**
* Tests whether {@link Record#getDateValue(String)} returns the correct
* {@link LocalDate} when given the name of a column that contains Strings.
*/
@Test
public void getDateValue_givenNameOfColumnWithDate_returnsDate() {
LocalDate expected = (LocalDate) value3;
LocalDate actual = record.getDateValue(column3.getName());
assertEquals(expected, actual);
}
@Test(expected = IllegalStateException.class)
public void getDateValue_givenNameOfColumnWithNumber_throwsIllegalStateException() {
record.getDateValue(column2.getName());
}
@Test(expected = IllegalStateException.class)
public void getDateValue_givenNameOfColumnWithString_throwsIllegalStateException() {
record.getDateValue(column1.getName());
}
@Test(expected = IllegalArgumentException.class)
public void setValue_givenIndexOfNonExistingColumn_throwsIllegalArgumentException() {
record.setValue(-1, null);
}
/**
* Tests whether {@link Record#setValue(int, Double)} updates the value of
* the correct column when given a {@link Double} value and the name of a
* column that contains {@link Double}s.
*/
@Test
public void setValueDouble_givenIndexOfColumnWithNumber_updatesValue() {
Double value = -1.0;
record.setValue(column2.getIndex(), value);
Double expected = value;
Double actual = record.getNumberValue(column2.getName());
assertSame(expected, actual);
}
@Test(expected = IllegalArgumentException.class)
public void setValue_givenNameNull_throwsIllegalArgumentException() {
record.setValue((String) null, value2);
}
@Test(expected = IllegalArgumentException.class)
public void setValue_givenNameOfNonexistentColumn_throwsIllegalArgumentException() {
record.setValue("null", value2);
}
@Test(expected = IllegalArgumentException.class)
public void setValue_givenValueOfInvalidType_throwsIllegalArgumentException() {
record.setValue(column1.getName(), new Object());
}
@Test(expected = IllegalStateException.class)
public void setValueDouble_givenNameOfColumnWithString_throwsIllegalStateException() {
record.setValue(column1.getName(), value2);
}
@Test(expected = IllegalStateException.class)
public void setValueDouble_givenNameOfColumnWithDate_throwsIllegalStateException() {
record.setValue(column3.getName(), value2);
}
/**
* Tests whether {@link Record#setValue(String, Double)} updates the value
* of the correct column when given a {@link Double} value and the name of a
* column that contains {@link Double}s.
*/
@Test
public void setValueDouble_givenNameOfColumn_updatesValue() {
Double value = -1.0;
record.setValue(column2.getName(), value);
Double expected = value;
Double actual = record.getNumberValue(column2.getName());
assertSame(expected, actual);
}
@Test(expected = IllegalStateException.class)
public void setValueString_givenNameOfColumnWithNumber_throwsIllegalStateException() {
record.setValue(column2.getName(), value1);
}
@Test(expected = IllegalStateException.class)
public void setValueString_givenNameOfColumnWithDate_throwsIllegalStateException() {
record.setValue(column3.getName(), value1);
}
/**
* Tests whether {@link Record#setValue(String, Object)} updates the value
* of the correct column when given a {@link String} value and the name of a
* column that contains {@link String}s.
*/
@Test
public void setValueString_givenNameOfColumn_updatesValue() {
String value = "def";
record.setValue(column1.getName(), value);
String expected = value;
String actual = record.getStringValue(column1.getName());
assertSame(expected, actual);
}
@Test(expected = IllegalStateException.class)
public void setValueDate_givenNameOfColumnWithNumber_throwsIllegalStateException() {
record.setValue(column2.getName(), value3);
}
@Test(expected = IllegalStateException.class)
public void setValueDate_givenNameOfColumnWithString_throwsIllegalStateException() {
record.setValue(column1.getName(), value3);
}
/**
* Tests whether {@link Record#setValue(String, Object)} updates the value
* of the correct column when given {@link LocalDate} value and the name of
* a column that contains {@link LocalDate}s.
*/
@Test
public void setValueDate_givenNameOfColumn_updatesValue() {
LocalDate value = LocalDate.of(1971, 1, 1);
record.setValue(column3.getName(), value);
LocalDate expected = value;
LocalDate actual = record.getDateValue(column3.getName());
assertSame(expected, actual);
}
@Test(expected = NullPointerException.class)
public void copyTo_givenTableNull_throwsNullPointerException() {
record.copyTo(null);
}
@Test(expected = IllegalArgumentException.class)
public void copyTo_givenTableWithDifferentNumberOfColumns_throwsIllegalArgumentException() {
Table table2 = mock(Table.class);
when(table2.getColumns()).thenReturn(Arrays.asList(column1, column2));
record.copyTo(table2);
}
@Test(expected = IllegalArgumentException.class)
public void copyTo_givenTableWithDifferentColumns_throwsIllegalArgumentException() {
Table table2 = mock(Table.class);
when(table2.getColumns()).thenReturn(Arrays.asList(column1, column3, column2));
record.copyTo(table2);
}
@Test
public void copyTo_givenTableWithIdenticalColumns_copiesRecord() {
Table table2 = mock(Table.class);
when(table2.getColumns()).thenReturn(Arrays.asList(column1, column2, column3));
record.copyTo(table2);
ArgumentCaptor<Record> recordCaptur = ArgumentCaptor.forClass(Record.class);
verify(table2).addRecord(recordCaptur.capture());
Record copy = recordCaptur.getValue();
assertEquals(record.getValues(), copy.getValues());
}
} |
package org.jboss.as.test.smoke.embedded.deployment.rar.AS7_1452;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.*;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.api.spec.ResourceAdapterArchive;
import org.junit.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.jboss.dmr.*;
import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.*;
import org.jboss.as.controller.client.ModelControllerClient;
import java.net.*;
import org.jboss.arquillian.container.test.api.*;
import org.jboss.shrinkwrap.api.asset.StringAsset;
/**
* @author <a href="vrastsel@redhat.com">Vladimir Rastseluev</a>
* @author <a href="stefano.maestri@redhat.com">Stefano Maestri</a>
* Test casae for AS7-1452: Resource Adapter config-property value passed incorrectly
*/
@RunWith(Arquillian.class)
@Ignore("AS7-1415")
public class AS7_1452TestCase {
private static ModelControllerClient client;
//@BeforeClass - called from @Deployment
public static void setUp() throws Exception{
final ModelNode address = new ModelNode();
address.add("subsystem", "resource-adapters");
address.add("resource-adapter","as7_1452.rar");
address.protect();
final ModelNode operation = new ModelNode();
operation.get(OP).set("add");
operation.get(OP_ADDR).set(address);
operation.get("archive").set("as7_1452.rar");
operation.get("transaction-support").set("NoTransaction");
final ModelNode result = getModelControllerClient().execute(operation);
Assert.assertEquals(SUCCESS, result.get(OUTCOME).asString());
final ModelNode addressConfigRes = address.clone();
addressConfigRes.add("config-properties","Property");
addressConfigRes.protect();
final ModelNode operationConfigRes = new ModelNode();
operationConfigRes.get(OP).set("add");
operationConfigRes.get(OP_ADDR).set(addressConfigRes);
operationConfigRes.get("value").set("A");
final ModelNode result1 = getModelControllerClient().execute(operationConfigRes);
Assert.assertEquals(SUCCESS, result1.get(OUTCOME).asString());
final ModelNode addressAdmin = address.clone();
addressAdmin.add("admin-objects","java:jboss/ConfigPropertyAdminObjectInterface1");
addressAdmin.protect();
final ModelNode operationAdmin = new ModelNode();
operationAdmin.get(OP).set("add");
operationAdmin.get(OP_ADDR).set(addressAdmin);
operationAdmin.get("class-name").set("org.jboss.as.test.smoke.embedded.deployment.rar.AS7_1452.ConfigPropertyAdminObjectImpl");
operationAdmin.get("jndi-name").set(AO_JNDI_NAME);
final ModelNode result2 = getModelControllerClient().execute(operationAdmin);
Assert.assertEquals(SUCCESS, result2.get(OUTCOME).asString());
final ModelNode addressConfigAdm = addressAdmin.clone();
addressConfigAdm.add("config-properties","Property");
addressConfigAdm.protect();
final ModelNode operationConfigAdm = new ModelNode();
operationConfigAdm.get(OP).set("add");
operationConfigAdm.get(OP_ADDR).set(addressConfigAdm);
operationConfigAdm.get("value").set("C");
final ModelNode result3 = getModelControllerClient().execute(operationConfigAdm);
Assert.assertEquals(SUCCESS, result3.get(OUTCOME).asString());
final ModelNode addressConn = address.clone();
addressConn.add("connection-definitions","java:jboss/ConfigPropertyConnectionFactory1");
addressConn.protect();
final ModelNode operationConn = new ModelNode();
operationConn.get(OP).set("add");
operationConn.get(OP_ADDR).set(addressConn);
operationConn.get("class-name").set("org.jboss.as.test.smoke.embedded.deployment.rar.AS7_1452.ConfigPropertyManagedConnectionFactory");
operationConn.get("jndi-name").set(CF_JNDI_NAME);
operationConn.get("pool-name").set("ConfigPropertyConnectionFactory");
final ModelNode result4 = getModelControllerClient().execute(operationConn);
Assert.assertEquals(SUCCESS, result4.get(OUTCOME).asString());
final ModelNode addressConfigConn = addressConn.clone();
addressConfigConn.add("config-properties","Property");
addressConfigConn.protect();
final ModelNode operationConfigConn = new ModelNode();
operationConfigConn.get(OP).set("add");
operationConfigConn.get(OP_ADDR).set(addressConfigConn);
operationConfigConn.get("value").set("B");
final ModelNode result5 = getModelControllerClient().execute(operationConfigConn);
Assert.assertEquals(SUCCESS, result5.get(OUTCOME).asString());
final ModelNode operationReload = new ModelNode();
operationReload.get(OP).set("reload");
final ModelNode result6 = getModelControllerClient().execute(operationReload);
Assert.assertEquals(SUCCESS, result6.get(OUTCOME).asString());
// add delay to let server restart
// temporary, until JIRA AS7-1415 is not resolved
Thread.sleep(10000);
}
@AfterClass
public static void tearDown() throws Exception{
final ModelNode address = new ModelNode();
address.add("subsystem", "resource-adapters");
address.add("resource-adapter","as7_1452.rar");
address.protect();
final ModelNode operation = new ModelNode();
operation.get(OP).set("remove");
operation.get(OP_ADDR).set(address);
final ModelNode result = getModelControllerClient().execute(operation);
Assert.assertEquals(SUCCESS, result.get(OUTCOME).asString());
// StreamUtils.safeClose(client);
}
private static ModelControllerClient getModelControllerClient() throws UnknownHostException {
if (client == null) {
client = ModelControllerClient.Factory.create(InetAddress.getByName("localhost"), 9999);
}
return client;
}
/**
* Define the deployment
*
* @return The deployment archive
*/
@Deployment
public static ResourceAdapterArchive createDeployment() throws Exception{
setUp();
String deploymentName = "as7_1452.rar";
ResourceAdapterArchive raa =
ShrinkWrap.create(ResourceAdapterArchive.class, deploymentName);
JavaArchive ja = ShrinkWrap.create(JavaArchive.class, "as7_1452.jar");
ja.addClasses(ConfigPropertyResourceAdapter.class, ConfigPropertyManagedConnectionFactory.class,
ConfigPropertyManagedConnection.class, ConfigPropertyConnectionFactory.class,
ConfigPropertyManagedConnectionMetaData.class,
ConfigPropertyConnectionFactoryImpl.class, ConfigPropertyConnection.class,
ConfigPropertyConnectionImpl.class, ConfigPropertyAdminObjectImpl.class,
ConfigPropertyAdminObjectInterface.class, AS7_1452TestCase.class);
raa.addAsLibrary(ja);
raa.addAsManifestResource("rar/" + deploymentName + "/META-INF/ra.xml", "ra.xml")
.addAsManifestResource(new StringAsset("Dependencies: org.apache.httpcomponents,org.jboss.as.controller-client,org.jboss.dmr\n"),"MANIFEST.MF");;
return raa;
}
private static final String CF_JNDI_NAME = "java:jboss/ConfigPropertyConnectionFactory1";
private static final String AO_JNDI_NAME = "java:jboss/ConfigPropertyAdminObjectInterface1";
/**
* Test config properties
*
* @throws Throwable Thrown if case of an error
*/
@Test
public void testConfigProperties() throws Throwable {
Context ctx = new InitialContext();
ConfigPropertyConnectionFactory connectionFactory = (ConfigPropertyConnectionFactory) ctx.lookup(CF_JNDI_NAME);
assertNotNull(connectionFactory);
ConfigPropertyAdminObjectInterface adminObject = (ConfigPropertyAdminObjectInterface) ctx.lookup(AO_JNDI_NAME);
assertNotNull(adminObject);
ConfigPropertyConnection connection = connectionFactory.getConnection();
assertNotNull(connection);
assertEquals("A", connection.getResourceAdapterProperty());
assertEquals("B", connection.getManagedConnectionFactoryProperty());
assertEquals("C", adminObject.getProperty());
connection.close();
}
} |
package org.xwiki.webjars.internal;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.tika.Tika;
import org.xwiki.component.annotation.Component;
import org.xwiki.container.Container;
import org.xwiki.container.Request;
import org.xwiki.container.Response;
import org.xwiki.container.servlet.ServletRequest;
import org.xwiki.container.servlet.ServletResponse;
import org.xwiki.resource.AbstractResourceReferenceHandler;
import org.xwiki.resource.ResourceReference;
import org.xwiki.resource.ResourceReferenceHandlerChain;
import org.xwiki.resource.ResourceReferenceHandlerException;
import org.xwiki.resource.entity.EntityResourceAction;
import org.xwiki.velocity.VelocityManager;
@Component
@Named("webjars")
@Singleton
public class WebJarsResourceReferenceHandler extends AbstractResourceReferenceHandler<EntityResourceAction>
{
/**
* The WebJars Action.
*/
public static final EntityResourceAction ACTION = new EntityResourceAction("webjars");
/**
* Prefix for locating resource files (JavaScript, CSS) in the classloader.
*/
private static final String WEBJARS_RESOURCE_PREFIX = "META-INF/resources/webjars/";
/**
* The encoding used when evaluating WebJar (text) resources.
*/
private static final String UTF8 = "UTF-8";
@Inject
private Container container;
/**
* Used to evaluate the Velocity code from the WebJar resources.
*/
@Inject
private VelocityManager velocityManager;
/**
* Used to determine the Content Type of the requested resource files.
*/
private Tika tika = new Tika();
@Override
public List<EntityResourceAction> getSupportedResourceReferences()
{
return Arrays.asList(ACTION);
}
@Override
public void handle(ResourceReference reference, ResourceReferenceHandlerChain chain)
throws ResourceReferenceHandlerException
{
if (!shouldBrowserUseCachedContent(reference)) {
String resourceName = reference.getParameterValue("value");
String resourcePath = String.format("%s%s", WEBJARS_RESOURCE_PREFIX, resourceName);
InputStream resourceStream = getClassLoader().getResourceAsStream(resourcePath);
if (resourceStream != null) {
if (shouldEvaluateResource(reference)) {
resourceStream = evaluate(resourceName, resourceStream);
}
// Make sure the resource stream supports mark & reset which is needed in order be able to detect the
// content type without affecting the stream (Tika may need to read a few bytes from the start of the
// stream, in which case it will mark & reset the stream).
if (!resourceStream.markSupported()) {
resourceStream = new BufferedInputStream(resourceStream);
}
try {
Response response = this.container.getResponse();
setResponseHeaders(response, reference);
response.setContentType(tika.detect(resourceStream, resourceName));
IOUtils.copy(resourceStream, this.container.getResponse().getOutputStream());
} catch (Exception e) {
throw new ResourceReferenceHandlerException(
String.format("Failed to read resource [%s]", resourceName), e);
} finally {
IOUtils.closeQuietly(resourceStream);
}
}
}
// Be a good citizen, continue the chain, in case some lower-priority Handler has something to do for this
// Resource Reference.
chain.handleNext(reference);
}
private void setResponseHeaders(Response response, ResourceReference reference)
{
// If the resource contains Velocity code then this code must be evaluated on each request and so the resource
// must not be cached. Otherwise, if the resource is static we need to send back the "Last-Modified" header in
// the response so that the browser will send us an "If-Modified-Since" request for any subsequent call for this
// static resource. When this happens we return a 304 to tell the browser to use its cached version.
if (response instanceof ServletResponse && !shouldEvaluateResource(reference)) {
HttpServletResponse httpResponse = ((ServletResponse) response).getHttpServletResponse();
httpResponse.setDateHeader("Last-Modified", new Date().getTime() / 1000 * 1000);
}
}
private boolean shouldBrowserUseCachedContent(ResourceReference reference)
{
// If the request contains a "If-Modified-Since" and the referenced resource is not supposed to be evaluated
// (i.e. no Velocity code) then return a 304 so to tell the browser to use its cached version.
Request request = this.container.getRequest();
if (request instanceof ServletRequest && !shouldEvaluateResource(reference)) {
HttpServletRequest httpRequest = ((ServletRequest) request).getHttpServletRequest();
if (httpRequest.getHeader("If-Modified-Since") != null) {
// Return the 304
Response response = this.container.getResponse();
if (response instanceof ServletResponse) {
HttpServletResponse httpResponse = ((ServletResponse) response).getHttpServletResponse();
httpResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return true;
}
}
}
return false;
}
/**
* @param reference a resource reference
* @return {@code true} if the resource should be evaluated (e.g. if the resource has Velocity code), {@code false}
* otherwise
*/
private boolean shouldEvaluateResource(ResourceReference reference)
{
return Boolean.valueOf(reference.getParameterValue("evaluate"));
}
private InputStream evaluate(String resourceName, InputStream resourceStream)
throws ResourceReferenceHandlerException
{
try {
StringWriter writer = new StringWriter();
this.velocityManager.getVelocityEngine().evaluate(this.velocityManager.getVelocityContext(), writer,
resourceName, new InputStreamReader(resourceStream, UTF8));
return new ByteArrayInputStream(writer.toString().getBytes(UTF8));
} catch (Exception e) {
throw new ResourceReferenceHandlerException("Faild to evaluate the Velocity code from WebJar resource ["
+ resourceName + "]", e);
}
}
/**
* @return the Class Loader from which to look for WebJars resources
*/
protected ClassLoader getClassLoader()
{
// Load the resource from the context class loader in order to support webjars located in XWiki Extensions
// loaded by the Extension Manager.
return Thread.currentThread().getContextClassLoader();
}
} |
package org.eclipse.birt.report.designer.data.ui.dataset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.birt.report.designer.data.ui.property.AbstractDescriptionPropertyPage;
import org.eclipse.birt.report.designer.internal.ui.dialogs.FormatAdapter;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.views.attributes.providers.ChoiceSetFactory;
import org.eclipse.birt.report.model.api.DataSetHandle;
import org.eclipse.birt.report.model.api.OdaDataSetHandle;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.elements.ReportDesignConstants;
import org.eclipse.birt.report.model.api.metadata.IChoice;
import org.eclipse.birt.report.model.api.metadata.IChoiceSet;
import org.eclipse.birt.report.model.elements.interfaces.IOdaDataSetModel;
import org.eclipse.birt.report.model.metadata.MetaDataDictionary;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import com.ibm.icu.util.ULocale;
public class DataSetSettingsPage extends AbstractDescriptionPropertyPage
{
private static String DEFAULT_MESSAGE = Messages.getString( "dataset.editor.settings" ); //$NON-NLS-1$
private transient Button fetchAllDataCheckBox = null;
private transient Button selectResultSetCheckBox = null;
private transient Button resultSetName = null;
private transient Button resultSetNumber = null;
private String numberText = null;
private String nameText = null;
boolean changed = false;
private static String STORED_PROCEDURE_EXTENSION_ID = "org.eclipse.birt.report.data.oda.jdbc.SPSelectDataSet"; //$NON-NLS-1$
private static IChoiceSet nullOrderingChoiceSet = MetaDataDictionary.getInstance( )
.getElement( ReportDesignConstants.DATA_SET_ELEMENT )
.getProperty( DesignChoiceConstants.CHOICE_NULLS_ORDERING )
.getAllowedChoices( );
private Combo localeCombo;
private Combo nullOrderingCombo;
public Control createContents( Composite parent )
{
Composite composite = new Composite( parent, SWT.NONE );
GridLayout layout = new GridLayout( );
layout.numColumns = 1;
composite.setLayout( layout );
composite.setLayoutData( new GridData( GridData.HORIZONTAL_ALIGN_FILL
| GridData.VERTICAL_ALIGN_FILL ) );
Object handle = ( (DataSetEditor) getContainer( ) ).getHandle( );
if ( handle instanceof OdaDataSetHandle )
{
addDataFetchSettingGroup( composite );
String extensionID = ( (OdaDataSetHandle) handle ).getExtensionID( );
if ( extensionID != null
&& extensionID.equalsIgnoreCase( STORED_PROCEDURE_EXTENSION_ID ) )
{
addResultSetGroup( composite );
}
}
addDataComparisonGroup( composite );
return composite;
}
private void addDataComparisonGroup( Composite composite )
{
Group group = new Group( composite, SWT.NONE );
group.setLayoutData( new GridData( GridData.FILL_HORIZONTAL ) );
group.setText( Messages.getString("DataSetSettingsPage.DataGroup.Title") ); //$NON-NLS-1$
GridLayout groupGridLayout = new GridLayout( );
groupGridLayout.numColumns = 2;
group.setLayout( groupGridLayout );
Label localeLabel = new Label( group, SWT.NONE );
localeLabel.setText( Messages.getString("DataSetSettingsPage.Locale.Label") ); //$NON-NLS-1$
localeCombo = new Combo( group, SWT.READ_ONLY | SWT.BORDER );
localeCombo.setVisibleItemCount( 30 );
GridData gd = new GridData( );
gd.widthHint = 200;
localeCombo.setLayoutData( gd );
localeCombo.setVisibleItemCount( 30 );
List<String> localeNames = new ArrayList<String>( );
localeNames.add( Messages.getString( "SortkeyBuilder.Locale.Auto" ) ); //$NON-NLS-1$
localeNames.addAll( FormatAdapter.LOCALE_TABLE.keySet( ) );
localeCombo.setItems( localeNames.toArray( new String[]{} ) );
localeCombo.select( 0 );
DataSetHandle dataset = (DataSetHandle) ( (DataSetEditor) getContainer( ) ).getHandle( );
if ( dataset.getLocale( ) != null )
{
String locale = null;
for ( Map.Entry<String, ULocale> entry : FormatAdapter.LOCALE_TABLE.entrySet( ) )
{
if ( dataset.getLocale( ).equals( entry.getValue( ) ) )
{
locale = entry.getKey( );
}
}
if ( locale != null )
{
int index = localeCombo.indexOf( locale );
localeCombo.select( index < 0 ? 0 : index );
}
}
Label nullOrderingLabel = new Label( group, SWT.NONE );
nullOrderingLabel.setText( Messages.getString("DataSetSettingsPage.NullValueOrdering.Label") ); //$NON-NLS-1$
nullOrderingCombo = new Combo( group, SWT.READ_ONLY | SWT.BORDER );
gd = new GridData( );
gd.widthHint = 200;
nullOrderingCombo.setLayoutData( gd );
nullOrderingCombo.setItems( ChoiceSetFactory.getDisplayNamefromChoiceSet( nullOrderingChoiceSet ) );
nullOrderingCombo.setText( ChoiceSetFactory.getDisplayNameFromChoiceSet( DesignChoiceConstants.NULLS_ORDERING_NULLS_LOWEST,
nullOrderingChoiceSet ) );
if ( dataset.getNullsOrdering( ) != null )
{
nullOrderingCombo.setText( ChoiceSetFactory.getDisplayNameFromChoiceSet( dataset.getNullsOrdering( ),
nullOrderingChoiceSet ) );
}
}
/**
* Add row fetch limit control group.
*
* @param composite
*/
private void addDataFetchSettingGroup( Composite composite )
{
GridLayout groupGridLayout = new GridLayout( );
groupGridLayout.numColumns = 5;
GridData groupGridData = new GridData( GridData.FILL_HORIZONTAL );
Group dataFetchSettingGroup = new Group( composite, SWT.NONE );
dataFetchSettingGroup.setLayoutData( groupGridData );
dataFetchSettingGroup.setLayout( groupGridLayout );
dataFetchSettingGroup.setText( Messages.getString( "dataset.editor.settings.dataFetchSetting" ) ); //$NON-NLS-1$
fetchAllDataCheckBox = new Button( dataFetchSettingGroup, SWT.CHECK );
GridData data = new GridData( );
data.horizontalSpan = 5;
fetchAllDataCheckBox.setLayoutData( data );
fetchAllDataCheckBox.setText( Messages.getString( "dataset.editor.settings.dataFetchSetting.fetchAll" ) ); //$NON-NLS-1$
final Label dataFetchLabel = new Label( dataFetchSettingGroup, SWT.NONE );
dataFetchLabel.setText( Messages.getString( "SettingsPage.dataFetchSetting.label" ) ); //$NON-NLS-1$
final Text rowFetchLimitText = new Text( dataFetchSettingGroup,
SWT.BORDER );
GridData gData = new GridData( GridData.FILL_HORIZONTAL );
rowFetchLimitText.setLayoutData( gData );
if ( getDataSetRowFetchLimit( ) > 0 )
{
fetchAllDataCheckBox.setSelection( false );
rowFetchLimitText.setEnabled( true );
dataFetchLabel.setEnabled( true );
rowFetchLimitText.setText( Integer.toString( getDataSetRowFetchLimit( ) ) );
}
else
{
fetchAllDataCheckBox.setSelection( true );
rowFetchLimitText.setEnabled( false );
dataFetchLabel.setEnabled( false );
rowFetchLimitText.setText( "" ); //$NON-NLS-1$
}
fetchAllDataCheckBox.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
final boolean isSelection = fetchAllDataCheckBox.getSelection( );
dataFetchLabel.setEnabled( !isSelection );
rowFetchLimitText.setEnabled( !isSelection );
if ( isSelection )
{
rowFetchLimitText.setText( "" ); //$NON-NLS-1$
}
}
} );
rowFetchLimitText.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
int rowFetchLimit = 0;
try
{
if ( isNumber( rowFetchLimitText.getText( ) ) )
{
String rowLimitText = rowFetchLimitText.getText( );
if ( rowLimitText.trim( ).length( ) == 0 )
rowLimitText = "0"; //$NON-NLS-1$
rowFetchLimit = new Double( rowLimitText ).intValue( );
rowFetchLimit = rowFetchLimit < 0 ? 0 : rowFetchLimit;
setDataSetRowFetchLimit( rowFetchLimit );
getContainer( ).setMessage( DEFAULT_MESSAGE,
IMessageProvider.NONE );
}
else
{
getContainer( ).setMessage( Messages.getString( "dataset.editor.settings.dataFetchSetting.errorNumberFormat" ), //$NON-NLS-1$
IMessageProvider.ERROR );
}
}
catch ( SemanticException e1 )
{
getContainer( ).setMessage( Messages.getString( "dataset.editor.settings.dataFetchSetting.errorNumberFormat" ), //$NON-NLS-1$
IMessageProvider.ERROR );
}
}
} );
}
private void addResultSetGroup( Composite composite )
{
GridLayout groupGridLayout = new GridLayout( );
GridData groupGridData = new GridData( GridData.FILL_HORIZONTAL );
Group resultSetNumberGroup = new Group( composite, SWT.NONE );
resultSetNumberGroup.setLayoutData( groupGridData );
resultSetNumberGroup.setLayout( groupGridLayout );
resultSetNumberGroup.setText( Messages.getString( "dataset.editor.settings.resultsetselection.resultSetSelection" ) ); //$NON-NLS-1$
selectResultSetCheckBox = new Button( resultSetNumberGroup, SWT.CHECK );
GridData data = new GridData( );
selectResultSetCheckBox.setLayoutData( data );
selectResultSetCheckBox.setText( Messages.getString( "dataset.editor.settings.resultsetselection.enableResultSetSelection" ) ); //$NON-NLS-1$
Composite selectionComposite = new Composite( resultSetNumberGroup,
SWT.NONE );
GridLayout cmpLayout = new GridLayout( );
cmpLayout.numColumns = 5;
selectionComposite.setLayout( cmpLayout );
GridData cmpGridData = new GridData( GridData.FILL_HORIZONTAL );
selectionComposite.setLayoutData( cmpGridData );
resultSetName = new Button( selectionComposite, SWT.RADIO );
data = new GridData( );
data.horizontalSpan = 3;
resultSetName.setLayoutData( data );
resultSetName.setText( Messages.getString( "dataset.editor.settings.resultsetselection.selectResultSetByName" ) ); //$NON-NLS-1$
final Text nameText = new Text( selectionComposite, SWT.BORDER );
GridData gData = new GridData( GridData.FILL_HORIZONTAL );
/*
* gData.horizontalSpan = 2; gData.widthHint = 100;
*/
nameText.setLayoutData( gData );
resultSetNumber = new Button( selectionComposite, SWT.RADIO );
data = new GridData( );
data.horizontalSpan = 3;
resultSetNumber.setLayoutData( data );
resultSetNumber.setText( Messages.getString( "dataset.editor.settings.resultsetselection.selectResultSetByNumber" ) ); //$NON-NLS-1$
final Text numberText = new Text( selectionComposite, SWT.BORDER );
gData = new GridData( GridData.FILL_HORIZONTAL );
numberText.setLayoutData( gData );
selectResultSetCheckBox.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
final boolean selected = selectResultSetCheckBox.getSelection( );
resultSetName.setEnabled( selected );
resultSetNumber.setEnabled( selected );
if ( selected )
{
if ( resultSetName.getSelection( ) )
{
numberText.setEnabled( false );
nameText.setEnabled( true );
}
else if ( resultSetNumber.getSelection( ) )
{
nameText.setEnabled( false );
numberText.setEnabled( true );
}
else
{
nameText.setEnabled( selected );
numberText.setEnabled( selected );
}
}
else
{
nameText.setEnabled( selected );
numberText.setEnabled( selected );
}
changed = true;
}
} );
resultSetName.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
nameText.setEnabled( true );
numberText.setEnabled( false );
changed = true;
}
} );
resultSetNumber.addSelectionListener( new SelectionAdapter( ) {
public void widgetSelected( SelectionEvent e )
{
nameText.setEnabled( false );
numberText.setEnabled( true );
changed = true;
}
} );
nameText.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
DataSetSettingsPage.this.nameText = nameText.getText( );
changed = true;
}
} );
numberText.addModifyListener( new ModifyListener( ) {
public void modifyText( ModifyEvent e )
{
int rsNumber = 0;
if ( isNumber( numberText.getText( ) ) )
{
String number = numberText.getText( );
if ( number.trim( ).length( ) == 0 )
number = "0"; //$NON-NLS-1$
DataSetSettingsPage.this.numberText = numberText.getText( );
getContainer( ).setMessage( DEFAULT_MESSAGE,
IMessageProvider.NONE );
changed = true;
}
else
{
getContainer( ).setMessage( Messages.getString( "dataset.editor.settings.dataFetchSetting.errorNumberFormatForResultSet" ), //$NON-NLS-1$
IMessageProvider.ERROR );
}
}
} );
if ( ( (OdaDataSetHandle) ( (DataSetEditor) getContainer( ) ).getHandle( ) ).getResultSetName( ) != null )
{
resultSetName.setSelection( true );
nameText.setText( ( (OdaDataSetHandle) ( (DataSetEditor) getContainer( ) ).getHandle( ) ).getResultSetName( ) );
numberText.setEnabled( false );
selectResultSetCheckBox.setSelection( true );
}
else if ( ( (OdaDataSetHandle) ( (DataSetEditor) getContainer( ) ).getHandle( ) ).getPropertyHandle( IOdaDataSetModel.RESULT_SET_NUMBER_PROP )
.isSet( ) )
{
resultSetNumber.setSelection( true );
numberText.setText( String.valueOf( ( (OdaDataSetHandle) ( (DataSetEditor) getContainer( ) ).getHandle( ) ).getResultSetNumber( ) ) );
nameText.setEnabled( false );
selectResultSetCheckBox.setSelection( true );
}
else
{
selectResultSetCheckBox.setSelection( false );
resultSetName.setSelection( true );
resultSetName.setEnabled( false );
resultSetNumber.setEnabled( false );
nameText.setEnabled( false );
numberText.setEnabled( false );
}
}
/**
* Test the text to see if it can be parsed to an integer.
*
* @param text
* @return
*/
private boolean isNumber( String text )
{
if ( text == null )
{
return false;
}
if ( text.trim( ).length( ) == 0 )
{
return true;
}
return text.matches( "^[0-9]*[1-9][0-9]*$" ); //$NON-NLS-1$
}
/**
*
* @param count
* @throws SemanticException
*/
private void setDataSetRowFetchLimit( int count ) throws SemanticException
{
( (DataSetEditor) getContainer( ) ).getHandle( )
.setRowFetchLimit( count );
}
/**
*
* @return
*/
private int getDataSetRowFetchLimit( )
{
return ( (DataSetEditor) getContainer( ) ).getHandle( )
.getRowFetchLimit( );
}
public void pageActivated( )
{
getContainer( ).setMessage( DEFAULT_MESSAGE, IMessageProvider.NONE );
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.designer.ui.dialogs.properties.AbstractPropertyPage
* #performCancel()
*/
public boolean performCancel( )
{
// selectorImage.dispose( );
return super.performCancel( );
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.designer.ui.dialogs.properties.AbstractPropertyPage
* #canLeave()
*/
public boolean canLeave( )
{
try
{
( (OdaDataSetHandle) ( (DataSetEditor) getContainer( ) ).getHandle( ) ).setProperty( IOdaDataSetModel.RESULT_SET_NUMBER_PROP,
null );
( (OdaDataSetHandle) ( (DataSetEditor) getContainer( ) ).getHandle( ) ).setResultSetName( null );
dealDataSetLocale( );
dealDataSetNullOrdering( );
if ( !updateResultSetSetting( ) )
return true;
return canLeavePage( );
}
catch ( Exception e )
{
return true;
}
}
protected boolean canLeavePage( )
{
if ( canFinish( ) )
return super.performOk( );
else
return false;
}
protected boolean updateResultSetSetting( ) throws SemanticException
{
if ( selectResultSetCheckBox == null )
return false;
if ( selectResultSetCheckBox.getSelection( ) )
{
if ( resultSetNumber.getSelection( ) )
{
( (OdaDataSetHandle) ( (DataSetEditor) getContainer( ) ).getHandle( ) ).setResultSetNumber( new Integer( this.numberText ) );
}
else if ( resultSetName.getSelection( ) )
{
( (OdaDataSetHandle) ( (DataSetEditor) getContainer( ) ).getHandle( ) ).setResultSetName( this.nameText );
}
}
if ( changed )
{
Iterator it = ( (DataSetEditor) getContainer( ) ).getHandle( )
.resultSetIterator( );
while ( it.hasNext( ) )
{
it.next( );
it.remove( );
}
}
changed = false;
return true;
}
/**
* whether the page can be finished or leave.
*/
public boolean canFinish( )
{
return true;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.designer.ui.dialogs.properties.AbstractPropertyPage
* #performOk()
*/
public boolean performOk( )
{
if ( canLeave( ) )
{
return super.performOk( );
}
else
return false;
}
private void dealDataSetNullOrdering( )
{
if ( nullOrderingCombo != null && !nullOrderingCombo.isDisposed( ) )
{
for ( int i = 0; i < nullOrderingChoiceSet.getChoices( ).length; i++ )
{
IChoice choice = nullOrderingChoiceSet.getChoices( )[i];
if ( choice.getDisplayName( )
.equals( nullOrderingCombo.getText( ) ) )
{
try
{
( ( (DataSetHandle) ( (DataSetEditor) getContainer( ) ).getHandle( ) ) ).setNullsOrdering( choice.getName( ) );
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
}
}
}
private void dealDataSetLocale( )
{
if ( localeCombo != null && !localeCombo.isDisposed( ) )
{
String locale = localeCombo.getText( );
try
{
if ( FormatAdapter.LOCALE_TABLE.containsKey( locale ) )
{
( ( (DataSetHandle) ( (DataSetEditor) getContainer( ) ).getHandle( ) ) ).setLocale( FormatAdapter.LOCALE_TABLE.get( locale ) );
}
else
{
( ( (DataSetHandle) ( (DataSetEditor) getContainer( ) ).getHandle( ) ) ).setLocale( null );
}
}
catch ( SemanticException e )
{
ExceptionHandler.handle( e );
}
}
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.designer.data.ui.property.AbstractPropertyPage
* #getToolTip()
*/
public String getToolTip( )
{
return Messages.getString( "SettingsPage.CachePreference.Filter.Tooltip" ); //$NON-NLS-1$
}
} |
package org.eclipse.birt.report.designer.ui.editors;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.birt.core.preference.IPreferenceChangeListener;
import org.eclipse.birt.core.preference.IPreferences;
import org.eclipse.birt.core.preference.PreferenceChangeEvent;
import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter;
import org.eclipse.birt.report.designer.core.model.views.outline.ScriptObjectNode;
import org.eclipse.birt.report.designer.core.util.mediator.IColleague;
import org.eclipse.birt.report.designer.core.util.mediator.ReportMediator;
import org.eclipse.birt.report.designer.core.util.mediator.request.ReportRequest;
import org.eclipse.birt.report.designer.internal.ui.editors.FileReportProvider;
import org.eclipse.birt.report.designer.internal.ui.editors.IAdvanceReportEditorPage;
import org.eclipse.birt.report.designer.internal.ui.editors.IRelatedFileChangeResolve;
import org.eclipse.birt.report.designer.internal.ui.editors.IReportEditor;
import org.eclipse.birt.report.designer.internal.ui.editors.LibraryProvider;
import org.eclipse.birt.report.designer.internal.ui.editors.parts.GraphicalEditorWithFlyoutPalette;
import org.eclipse.birt.report.designer.internal.ui.editors.schematic.ReportMultiBookPage;
import org.eclipse.birt.report.designer.internal.ui.editors.schematic.editparts.IResourceEditPart;
import org.eclipse.birt.report.designer.internal.ui.extension.EditorContributorManager;
import org.eclipse.birt.report.designer.internal.ui.extension.FormPageDef;
import org.eclipse.birt.report.designer.internal.ui.util.Policy;
import org.eclipse.birt.report.designer.internal.ui.util.UIUtil;
import org.eclipse.birt.report.designer.internal.ui.views.ILibraryProvider;
import org.eclipse.birt.report.designer.internal.ui.views.actions.GlobalActionFactory;
import org.eclipse.birt.report.designer.internal.ui.views.data.DataViewPage;
import org.eclipse.birt.report.designer.internal.ui.views.data.DataViewTreeViewerPage;
import org.eclipse.birt.report.designer.internal.ui.views.outline.DesignerOutlinePage;
import org.eclipse.birt.report.designer.nls.Messages;
import org.eclipse.birt.report.designer.ui.ReportPlugin;
import org.eclipse.birt.report.designer.ui.preferences.PreferenceFactory;
import org.eclipse.birt.report.designer.ui.views.ElementAdapterManager;
import org.eclipse.birt.report.designer.ui.views.IReportResourceChangeEvent;
import org.eclipse.birt.report.designer.ui.views.IReportResourceChangeListener;
import org.eclipse.birt.report.designer.ui.views.IReportResourceSynchronizer;
import org.eclipse.birt.report.designer.ui.views.attributes.AttributeViewPage;
import org.eclipse.birt.report.designer.ui.widget.ITreeViewerBackup;
import org.eclipse.birt.report.designer.ui.widget.TreeViewerBackup;
import org.eclipse.birt.report.model.api.IVersionInfo;
import org.eclipse.birt.report.model.api.MasterPageHandle;
import org.eclipse.birt.report.model.api.ModuleHandle;
import org.eclipse.birt.report.model.api.ModuleUtil;
import org.eclipse.birt.report.model.api.PropertyHandle;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.GraphicalViewer;
import org.eclipse.gef.ui.views.palette.PalettePage;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IKeyBindingService;
import org.eclipse.ui.INestableKeyBindingService;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IWindowListener;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchPartConstants;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.editor.FormEditor;
import org.eclipse.ui.forms.editor.IFormPage;
import org.eclipse.ui.part.IPageBookViewPage;
import org.eclipse.ui.part.MultiPageSelectionProvider;
import org.eclipse.ui.part.PageBookView;
import org.eclipse.ui.views.contentoutline.ContentOutlinePage;
import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
/**
*
* Base multipage editor for report editors. Clients can subclass this class to
* create customize report editors. Report editor pages can contributed through
* Extendtion Point
* org.eclipse.birt.report.designer.ui.editors.multiPageEditorContributor.
*
* @see IReportEditorPage
*/
public class MultiPageReportEditor extends AbstractMultiPageEditor implements
IPartListener,
IReportEditor,
IColleague,
IReportResourceChangeListener
{
public static final String LayoutMasterPage_ID = "org.eclipse.birt.report.designer.ui.editors.masterpage"; //$NON-NLS-1$
public static final String LayoutEditor_ID = "org.eclipse.birt.report.designer.ui.editors.layout"; //$NON-NLS-1$
public static final String XMLSourcePage_ID = "org.eclipse.birt.report.designer.ui.editors.xmlsource"; //$NON-NLS-1$
public static final String ScriptForm_ID = "org.eclipse.birt.report.designer.ui.editors.script"; //$NON-NLS-1$
public static int PROP_SAVE = 1000;
private ReportMultiBookPage fPalettePage;
private ReportMultiBookPage outlinePage;
private ReportMultiBookPage dataPage;
private boolean fIsHandlingActivation;
private long fModificationStamp = -1;;
protected IReportProvider reportProvider;
private FormEditorSelectionProvider provider = new FormEditorSelectionProvider( this );
private boolean isChanging = false;
private ReportMultiBookPage attributePage;
private ITreeViewerBackup outlineBackup;
private ITreeViewerBackup dataBackup;
private boolean needReload = false;
private boolean needReset = false ;
private IWorkbenchPart fActivePart;
private boolean isClose = false;
private IRelatedFileChangeResolve resolve;
private IPreferences prefs;
IPreferenceChangeListener preferenceChangeListener = new IPreferenceChangeListener()
{
public void preferenceChange( PreferenceChangeEvent event )
{
if ( event.getKey( ).equals( PreferenceChangeEvent.SPECIALTODEFAULT )
|| ReportPlugin.RESOURCE_PREFERENCE.equals( event.getKey( ) ) )
{
SessionHandleAdapter.getInstance( )
.getSessionHandle( )
.setBirtResourcePath( ReportPlugin.getDefault( ).getResourcePreference( ) );
UIUtil.processSessionResourceFolder( getEditorInput( ),
UIUtil.getProjectFromInput( getEditorInput( ) ), getModel() );
refreshGraphicalEditor();
}
}
};
private IWindowListener windowListener = new IWindowListener()
{
public void windowActivated( IWorkbenchWindow window )
{
if (! (window == getEditorSite().getWorkbenchWindow()))
{
return;
}
if (fActivePart != MultiPageReportEditor.this)
{
return;
}
window.getShell().getDisplay().asyncExec( new Runnable( ) {
public void run( )
{
confirmSave( );
}
});
}
public void windowClosed( IWorkbenchWindow window )
{
}
public void windowDeactivated( IWorkbenchWindow window )
{
}
public void windowOpened( IWorkbenchWindow window )
{
}
};
private void confirmSave()
{
if (fIsHandlingActivation)
return;
if (!isExistModelFile( ) && !isClose)
{
//Thread.dumpStack( );
fIsHandlingActivation= true;
MessageDialog dialog= new MessageDialog(UIUtil.getDefaultShell( ), Messages.getString("MultiPageReportEditor.ConfirmTitle"), //$NON-NLS-1$
null, Messages.getString("MultiPageReportEditor.SaveConfirmMessage"), //$NON-NLS-1$
MessageDialog.QUESTION, new String[]{Messages.getString("MultiPageReportEditor.SaveButton"), Messages.getString("MultiPageReportEditor.CloseButton")}, 0); //$NON-NLS-1$ //$NON-NLS-2$
try
{
if (dialog.open() == 0)
{
doSave( null );
isClose = false;
} else
{
Display display= getSite().getShell().getDisplay();
display.asyncExec(new Runnable() {
public void run() {
closeEditor( false );
}
});
isClose = true;
}
}
finally
{
fIsHandlingActivation= false;
needReset = false;
needReload = false;
}
}
}
// this is a bug because the getActiveEditor() return null, we should change
// the getActivePage()
// return the correct current page index.we may delete this class
// TODO
private static class FormEditorSelectionProvider extends
MultiPageSelectionProvider
{
private ISelection globalSelection;
/**
* @param multiPageEditor
*/
public FormEditorSelectionProvider( FormEditor formEditor )
{
super( formEditor );
}
public ISelection getSelection( )
{
IEditorPart activeEditor = ( (FormEditor) getMultiPageEditor( ) ).getActivePageInstance( );
// IEditorPart activeEditor = getActivePageInstance( );
if ( activeEditor != null )
{
ISelectionProvider selectionProvider = activeEditor.getSite( )
.getSelectionProvider( );
if ( selectionProvider != null )
return selectionProvider.getSelection( );
}
return globalSelection;
}
/*
* (non-Javadoc) Method declared on <code> ISelectionProvider </code> .
*/
public void setSelection( ISelection selection )
{
IEditorPart activeEditor = ( (FormEditor) getMultiPageEditor( ) ).getActivePageInstance( );
if ( activeEditor != null )
{
ISelectionProvider selectionProvider = activeEditor.getSite( )
.getSelectionProvider( );
if ( selectionProvider != null )
selectionProvider.setSelection( selection );
}
else
{
this.globalSelection = selection;
fireSelectionChanged( new SelectionChangedEvent( this,
globalSelection ) );
}
}
}
/**
* Constructor
*/
public MultiPageReportEditor( )
{
super( );
outlineBackup = new TreeViewerBackup( );
dataBackup = new TreeViewerBackup( );
IReportResourceSynchronizer synchronizer = ReportPlugin.getDefault( )
.getResourceSynchronizerService( );
if ( synchronizer != null )
{
synchronizer.addListener(IReportResourceChangeEvent.LibraySaveChange|IReportResourceChangeEvent.ImageResourceChange|IReportResourceChangeEvent.DataDesignSaveChange, this );
}
PlatformUI.getWorkbench().addWindowListener(windowListener);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.forms.editor.FormEditor#init(org.eclipse.ui.IEditorSite,
* org.eclipse.ui.IEditorInput)
*/
public void init( IEditorSite site, IEditorInput input )
throws PartInitException
{
super.init( site, input );
// getSite( ).getWorkbenchWindow( )
// .getPartService( )
// .addPartListener( this );
site.setSelectionProvider( provider );
IReportProvider provider = getProvider( );
if ( provider != null && provider.getInputPath( input ) != null )
{
setPartName( provider.getInputPath( input ).lastSegment( ) );
firePropertyChange( IWorkbenchPartConstants.PROP_PART_NAME );
}
else
{
setPartName( input.getName( ) );
firePropertyChange( IWorkbenchPartConstants.PROP_PART_NAME );
}
// suport the mediator
ReportMediator.addGlobalColleague( this );
IProject project = UIUtil.getProjectFromInput( input );
prefs = PreferenceFactory.getInstance( )
.getPreferences( ReportPlugin.getDefault( ),
project );
prefs.addPreferenceChangeListener( preferenceChangeListener );
}
protected IReportProvider getProvider( )
{
if ( reportProvider == null )
{
reportProvider = new FileReportProvider( );
}
return reportProvider;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.forms.editor.FormEditor#addPages()
*/
protected void addPages( )
{
List formPageList = EditorContributorManager.getInstance( )
.getEditorContributor( getEditorSite( ).getId( ) ).formPageList;
boolean error = false;
// For back compatible only.
// Provide warning message to let user select if the auto convert needs
// See bugzilla bug 136536 for detail.
String fileName = getProvider( ).getInputPath( getEditorInput( ) )
.toOSString( );
List message = ModuleUtil.checkVersion( fileName );
if ( message.size( ) > 0 )
{
IVersionInfo info = (IVersionInfo) message.get( 0 );
if ( !MessageDialog.openConfirm( UIUtil.getDefaultShell( ),
Messages.getString( "MultiPageReportEditor.CheckVersion.Dialog.Title" ), //$NON-NLS-1$
info.getLocalizedMessage( ) ) )
{
for ( Iterator iter = formPageList.iterator( ); iter.hasNext( ); )
{
FormPageDef pagedef = (FormPageDef) iter.next( );
if ( XMLSourcePage_ID.equals( pagedef.id ) )
{
try
{
addPage( pagedef.createPage( ), pagedef.displayName );
break;
}
catch ( Exception e )
{
}
}
}
return;
}
}
UIUtil.processSessionResourceFolder( getEditorInput( ),
UIUtil.getProjectFromInput( getEditorInput( ) ), null );
// load the model first here, so consequent pages can directly use it without reloading
getProvider( ).getReportModuleHandle( getEditorInput( ) );
for ( Iterator iter = formPageList.iterator( ); iter.hasNext( ); )
{
FormPageDef pagedef = (FormPageDef) iter.next( );
try
{
addPage( pagedef.createPage( ), pagedef.displayName );
}
catch ( Exception e )
{
error = true;
}
}
if ( error )
{
setActivePage( XMLSourcePage_ID );
}
}
/**
* Add a IReportEditorPage to multipage editor.
*
* @param page
* @param title
* @return
* @throws PartInitException
*/
public int addPage( IReportEditorPage page, String title )
throws PartInitException
{
int index = super.addPage( page );
if ( title != null )
{
setPageText( index, title );
}
try
{
page.initialize( this );
page.init( createSite( page ), getEditorInput( ) );
}
catch ( Exception e )
{
// removePage( index );
throw new PartInitException( e.getMessage( ) );
}
return index;
}
/**
* Remove report editor page.
*
* @param id
* the page id.
*/
public void removePage( String id )
{
IFormPage page = findPage( id );
if ( page != null )
{
removePage( page.getIndex( ) );
}
}
/**
* Remove all report editor page.
*/
public void removeAllPages( )
{
for ( int i = pages.toArray( ).length - 1; i >= 0; i
{
if ( pages.get( i ) != null )
this.removePage( ( (IFormPage) pages.get( i ) ).getId( ) );
}
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.ui.part.EditorPart#doSave(org.eclipse.core.runtime.
* IProgressMonitor)
*/
public void doSave( IProgressMonitor monitor )
{
boolean isReselect = false;
if ( getModel( ) != null
&& ModuleUtil.compareReportVersion( ModuleUtil.getReportVersion( ),
getModel( ).getVersion( ) ) > 0 )
{
if ( !MessageDialog.openConfirm( UIUtil.getDefaultShell( ),
Messages.getString( "MultiPageReportEditor.ConfirmVersion.Dialog.Title" ), Messages.getString( "MultiPageReportEditor.ConfirmVersion.Dialog.Message" ) ) ) //$NON-NLS-1$ //$NON-NLS-2$
{
return;
}
else
{
isReselect = true;
}
}
getCurrentPageInstance( ).doSave( monitor );
fireDesignFileChangeEvent( );
if (isReselect)
{
Display.getCurrent( ).asyncExec( new Runnable( ) {
public void run( )
{
if ( getActivePageInstance( ) instanceof GraphicalEditorWithFlyoutPalette )
{
if ( ( (GraphicalEditorWithFlyoutPalette) getActivePageInstance( ) ).getGraphicalViewer( ) != null )
{
GraphicalEditorWithFlyoutPalette editor = (GraphicalEditorWithFlyoutPalette) getActivePageInstance( );
GraphicalViewer view = editor.getGraphicalViewer( );
UIUtil.resetViewSelection( view, true );
}
}
}
});
}
}
private void fireDesignFileChangeEvent( )
{
UIUtil.doFinishSave( getModel( ) );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.EditorPart#doSaveAs()
*/
public void doSaveAs( )
{
getActivePageInstance( ).doSaveAs( );
setInput( getActivePageInstance( ).getEditorInput( ) );
// update site name
IReportProvider provider = getProvider( );
if ( provider != null )
{
setPartName( provider.getInputPath( getEditorInput( ) )
.lastSegment( ) );
firePropertyChange( IWorkbenchPartConstants.PROP_PART_NAME );
getProvider( ).getReportModuleHandle( getEditorInput( ) )
.setFileName( getProvider( ).getInputPath( getEditorInput( ) )
.toOSString( ) );
}
updateRelatedViews( );
fireDesignFileChangeEvent( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.EditorPart#isSaveAsAllowed()
*/
public boolean isSaveAsAllowed( )
{
return getActivePageInstance( ).isSaveAsAllowed( );
}
// /*
// * (non-Javadoc)
// *
// * @see org.eclipse.ui.forms.editor.FormEditor#isDirty()
// */
// public boolean isDirty( )
// fLastDirtyState = computeDirtyState( );
// return fLastDirtyState;
// private boolean computeDirtyState( )
// IFormPage page = getActivePageInstance( );
// if ( page != null && page.isDirty( ) )
// return true;
// return false;
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.part.WorkbenchPart#getAdapter(java.lang.Class)
*/
public Object getAdapter( Class type )
{
if ( type == IReportProvider.class )
{
if ( reportProvider == null )
{
reportProvider = new FileReportProvider( );
}
return reportProvider;
}
if ( type == ILibraryProvider.class )
{
return new LibraryProvider( );
}
if ( type == PalettePage.class )
{
Object adapter = getPalettePage( );
updatePaletteView( getActivePageInstance( ) );
return adapter;
}
if ( type == IContentOutlinePage.class )
{
/*
* Update the logic under eclipse 3.7, eclipse always call the getAdapter(OutlinePage) when handle the ShellActive event.
* So we don't need to call updateOutLineView every time, only call it when new a outline page.
*/
boolean update = outlinePage == null || outlinePage.isDisposed();
Object adapter = getOutlinePage();
if (update) {
updateOutLineView(getActivePageInstance());
}
return adapter;
}
if ( type == DataViewPage.class )
{
Object adapter = getDataPage( );
updateDateView( getActivePageInstance( ) );
return adapter;
}
if ( type == AttributeViewPage.class )
{
Object adapter = getAttributePage( );
updateAttributeView( getActivePageInstance( ) );
return adapter;
}
if ( getActivePageInstance( ) != null )
{
return getActivePageInstance( ).getAdapter( type );
}
return super.getAdapter( type );
}
private void updateAttributeView( IFormPage activePageInstance )
{
if ( attributePage == null )
{
return;
}
Object adapter = activePageInstance.getAdapter( AttributeViewPage.class );
attributePage.setActivePage( (IPageBookViewPage) adapter );
}
private void updateDateView( IFormPage activePageInstance )
{
if ( dataPage == null )
{
return;
}
Object adapter = activePageInstance.getAdapter( DataViewPage.class );
if ( adapter instanceof DataViewTreeViewerPage )
{
( (DataViewTreeViewerPage) adapter ).setBackupState( dataBackup );
}
dataPage.setActivePage( (IPageBookViewPage) adapter );
}
private void updateOutLineView( IFormPage activePageInstance )
{
if ( outlinePage == null )
{
return;
}
if ( reloadOutlinePage( ) )
{
return;
}
Object designOutLinePage = activePageInstance.getAdapter( IContentOutlinePage.class );
if ( designOutLinePage instanceof DesignerOutlinePage )
{
( (DesignerOutlinePage) designOutLinePage ).setBackupState( outlineBackup );
}
outlinePage.setActivePage( (IPageBookViewPage) designOutLinePage );
}
public void outlineSwitch( )
{
if ( !getActivePageInstance( ).getId( ).equals( XMLSourcePage_ID )
|| outlinePage == null )
{
return;
}
if ( outlinePage.getCurrentPage( ) instanceof DesignerOutlinePage )
{
outlinePage.setActivePage( (IPageBookViewPage) getActivePageInstance( ).getAdapter( ContentOutlinePage.class ) );
}
else
{
outlinePage.setActivePage( (IPageBookViewPage) getActivePageInstance( ).getAdapter( IContentOutlinePage.class ) );
}
outlinePage.getSite( ).getActionBars( ).updateActionBars( );
}
public boolean reloadOutlinePage( )
{
if ( !getActivePageInstance( ).getId( ).equals( XMLSourcePage_ID )
|| outlinePage == null
|| !getCurrentPageInstance( ).getId( )
.equals( XMLSourcePage_ID ) )
{
return false;
}
if ( outlinePage.getCurrentPage( ) instanceof DesignerOutlinePage
|| outlinePage.getCurrentPage( ) == null )
{
outlinePage.setActivePage( (IPageBookViewPage) getActivePageInstance( ).getAdapter( IContentOutlinePage.class ) );
}
else
{
outlinePage.setActivePage( (IPageBookViewPage) getActivePageInstance( ).getAdapter( ContentOutlinePage.class ) );
}
if ( outlinePage.getSite( ) != null )
{
outlinePage.getSite( ).getActionBars( ).updateActionBars( );
}
return true;
}
private Object getDataPage( )
{
if ( dataPage == null || dataPage.isDisposed( ) )
{
dataPage = new ReportMultiBookPage( );
}
return dataPage;
}
private Object getAttributePage( )
{
if ( attributePage == null || attributePage.isDisposed( ) )
{
attributePage = new ReportMultiBookPage( );
}
return attributePage;
}
/**
* If new a outline page, should call updateOutLineView(
* getActivePageInstance( ) ) method at first.
*
* @Since 3.7.2
*
*/
public Object getOutlinePage( )
{
if ( outlinePage == null || outlinePage.isDisposed( ) )
{
outlinePage = new ReportMultiBookPage( );
}
return outlinePage;
}
private Object getPalettePage( )
{
if ( fPalettePage == null || fPalettePage.isDisposed( ) )
{
fPalettePage = new ReportMultiBookPage( );
}
return fPalettePage;
}
private void updatePaletteView( IFormPage activePageInstance )
{
if ( fPalettePage == null )
{
return;
}
Object palette = activePageInstance.getAdapter( PalettePage.class );
fPalettePage.setActivePage( (IPageBookViewPage) palette );
}
public void pageChange( String id )
{
IFormPage page = findPage( id );
if ( page != null )
{
pageChange( page.getIndex( ) );
}
}
protected void pageChange( int newPageIndex )
{
int oldPageIndex = getCurrentPage( );
if ( oldPageIndex == newPageIndex )
{
isChanging = false;
bingdingKey( oldPageIndex );
return;
}
if ( oldPageIndex != -1 )
{
Object oldPage = pages.get( oldPageIndex );
Object newPage = pages.get( newPageIndex );
if ( oldPage instanceof IFormPage )
{
if ( !( (IFormPage) oldPage ).canLeaveThePage( ) )
{
setActivePage( oldPageIndex );
return;
}
}
// change to new page, must do it first, because must check old page
// is canleave.
isChanging = true;
super.pageChange( newPageIndex );
// updateRelatedViews( );
// check new page status
if ( !prePageChanges( oldPage, newPage ) )
{
super.setActivePage( oldPageIndex );
updateRelatedViews( );
return;
}
else if ( isChanging )
{
bingdingKey( newPageIndex );
}
isChanging = false;
}
else
{
super.pageChange( newPageIndex );
}
updateRelatedViews( );
}
public void setFocus( )
{
super.setFocus( );
if ( pages == null
|| getCurrentPage( ) < 0
|| getCurrentPage( ) > pages.size( ) - 1 )
{
return;
}
bingdingKey( getCurrentPage( ) );
}
// this is a bug because the getActiveEditor() return null, we should change
// the getActivePage()
// return the correct current page index.we may delete this method
// TODO
private void bingdingKey( int newPageIndex )
{
final IKeyBindingService service = getSite( ).getKeyBindingService( );
final IEditorPart editor = (IEditorPart) pages.get( newPageIndex );
if ( editor != null && editor.getEditorSite( ) != null )
{
editor.setFocus( );
// There is no selected page, so deactivate the active service.
if ( service instanceof INestableKeyBindingService )
{
final INestableKeyBindingService nestableService = (INestableKeyBindingService) service;
if ( editor != null )
{
nestableService.activateKeyBindingService( editor.getEditorSite( ) );
}
else
{
nestableService.activateKeyBindingService( null );
}
}
else
{
}
}
}
public void updateRelatedViews( )
{
updatePaletteView( getCurrentPageInstance( ) );
updateOutLineView( getCurrentPageInstance( ) );
updateDateView( getCurrentPageInstance( ) );
}
protected boolean prePageChanges( Object oldPage, Object newPage )
{
boolean isNewPageValid = true;
if ( oldPage instanceof IReportEditorPage
&& newPage instanceof IReportEditorPage )
{
isNewPageValid = ( (IReportEditorPage) newPage ).onBroughtToTop( (IReportEditorPage) oldPage );
// TODO: HOW TO RESET MODEL?????????
// model = SessionHandleAdapter.getInstance(
// ).getReportDesignHandle( );
}
return isNewPageValid;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.forms.editor.FormEditor#editorDirtyStateChanged()
*/
public void editorDirtyStateChanged( )
{
super.editorDirtyStateChanged( );
markPageStale( );
}
private void markPageStale( )
{
// int currentIndex = getCurrentPage( );
IFormPage currentPage = getActivePageInstance( );
if ( !( currentPage instanceof IReportEditorPage ) )
{
return;
}
// if ( currentIndex != -1 )
// for ( int i = 0; i < pages.size( ); i++ )
// if ( i == currentIndex )
// continue;
// Object page = pages.get( i );
// if ( page instanceof IReportEditorPage )
// ( (IReportEditorPage) page ).markPageStale( ( (IReportEditorPage)
// currentPage ).getStaleType( ) );
}
/**
* Get the current report ModuleHandle.
*
* @return
*/
public ModuleHandle getModel( )
{
if ( reportProvider != null )
{
return reportProvider.queryReportModuleHandle( );
}
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IPartListener#partActivated(org.eclipse.ui.IWorkbenchPart)
*/
public void partActivated( IWorkbenchPart part )
{
fActivePart = part;
if ( part != this )
{
if ( part instanceof PageBookView )
{
PageBookView view = (PageBookView) part;
if ( view.getCurrentPage( ) instanceof DesignerOutlinePage )
{
ISelectionProvider provider = (ISelectionProvider) view.getCurrentPage( );
ReportRequest request = new ReportRequest( view.getCurrentPage( ) );
List list = new ArrayList( );
if ( provider.getSelection( ) instanceof IStructuredSelection )
{
list = ( (IStructuredSelection) provider.getSelection( ) ).toList( );
}
request.setSelectionObject( list );
request.setType( ReportRequest.SELECTION );
// no convert
// request.setRequestConvert(new
// EditorReportRequestConvert());
SessionHandleAdapter.getInstance( )
.getMediator( )
.notifyRequest( request );
SessionHandleAdapter.getInstance( )
.getMediator( )
.pushState( );
}
}
if ( getActivePageInstance( ) instanceof GraphicalEditorWithFlyoutPalette )
{
if ( ( (GraphicalEditorWithFlyoutPalette) getActivePageInstance( ) ).getGraphicalViewer( )
.getEditDomain( )
.getPaletteViewer( ) != null )
{
GraphicalEditorWithFlyoutPalette editor = (GraphicalEditorWithFlyoutPalette) getActivePageInstance( );
GraphicalViewer view = editor.getGraphicalViewer( );
view.getEditDomain( ).loadDefaultTool( );
}
}
return;
}
if ( part == this )
{
confirmSave( );
final ModuleHandle oldHandle = getModel();
if (needReset)
{
if (resolve != null && resolve.reset( ))
{
getProvider( ).getReportModuleHandle( getEditorInput( ), true );
}
else
{
needReset = false;
}
needReload = false;
}
if (needReload)
{
if (resolve != null && resolve.reload( getModel() ))
{
//do nothing now
}
else
{
needReload = false;
}
}
if ( getEditorInput( ).exists( ) )
{
handleActivation( );
ModuleHandle currentModel = getModel( );
SessionHandleAdapter.getInstance( )
.setReportDesignHandle( currentModel );
String str = SessionHandleAdapter.getInstance( ).getSessionHandle( )
.getResourceFolder();
UIUtil.processSessionResourceFolder( getEditorInput( ),
UIUtil.getProjectFromInput( getEditorInput( ) ), currentModel );
if (!str.equals( SessionHandleAdapter.getInstance( ).getSessionHandle( )
.getResourceFolder()) && getActivePageInstance( ) instanceof GraphicalEditorWithFlyoutPalette)
{
((GraphicalEditorWithFlyoutPalette)getActivePageInstance( )).getGraphicalViewer( ).getRootEditPart( );
refreshGraphicalEditor( );
}
}
if ( //getActivePageInstance( ) instanceof GraphicalEditorWithFlyoutPalette
getActivePageInstance( ) instanceof IReportEditorPage )
{
boolean isDispatch = false;
if (getActivePageInstance( ) instanceof GraphicalEditorWithFlyoutPalette)
{
isDispatch = true;
}
else if (needReload || needReset)
{
isDispatch = true;
}
final boolean tempDispatch = isDispatch;
Display.getCurrent( ).asyncExec( new Runnable( ) {
public void run( )
{
IReportEditorPage curPage = (IReportEditorPage) getActivePageInstance( );
if (needReload || needReset)
{
curPage.markPageStale( IPageStaleType.MODEL_RELOAD );
}
if ( getActivePageInstance( ) != null )
{
if (curPage instanceof IAdvanceReportEditorPage)
{
if (((IAdvanceReportEditorPage)curPage).isSensitivePartChange( ))
{
curPage.onBroughtToTop( (IReportEditorPage) getActivePageInstance( ) );
}
}
else
{
curPage.onBroughtToTop( (IReportEditorPage) getActivePageInstance( ) );
}
}
if (!tempDispatch)
{
return;
}
// UIUtil.resetViewSelection( view, true );
if (needReload || needReset)
{
updateRelatedViews( );
//doSave( null );
UIUtil.refreshCurrentEditorMarkers( );
curPage.markPageStale( IPageStaleType.NONE );
}
if (needReset)
{
SessionHandleAdapter.getInstance( ).resetReportDesign( oldHandle, getModel( ) );
oldHandle.close( );
}
needReload = false;
needReset = false;
}
} );
// UIUtil.resetViewSelection( view, true );
}
}
// if ( getModel( ) != null )
// getModel( ).setResourceFolder( getProjectFolder( ) );
}
private void refreshResourceEditPart(EditPart parent)
{
if (parent instanceof IResourceEditPart)
{
((IResourceEditPart)parent).refreshResource( );
}
List list = parent.getChildren( );
for (int i=0; i<list.size(); i++)
{
EditPart part = (EditPart)list.get( i );
refreshResourceEditPart( part );
}
}
public boolean isExistModelFile()
{
if ( getModel( ) == null )
{
return true;
}
File file = new File( getModel( ).getFileName( ) );
if ( file.exists( ) && file.isFile( ) )
{
return true;
}
return false;
}
// private String getProjectFolder( )
// IEditorInput input = getEditorInput( );
// Object fileAdapter = input.getAdapter( IFile.class );
// IFile file = null;
// if ( fileAdapter != null )
// file = (IFile) fileAdapter;
// if ( file != null && file.getProject( ) != null )
// return file.getProject( ).getLocation( ).toOSString( );
// if ( input instanceof IPathEditorInput )
// File fileSystemFile = ( (IPathEditorInput) input ).getPath( )
// .toFile( );
// return fileSystemFile.getParent( );
// return null;
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IPartListener#partBroughtToTop(org.eclipse.ui.IWorkbenchPart )
*/
public void partBroughtToTop( IWorkbenchPart part )
{
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IPartListener#partClosed(org.eclipse.ui.IWorkbenchPart)
*/
public void partClosed( IWorkbenchPart part )
{
if ( part == this && getModel( ) != null )
{
SessionHandleAdapter.getInstance( ).clear( getModel( ) );
if ( getModel( ) != null )
{
GlobalActionFactory.removeStackActions( getModel( ).getCommandStack( ) );
}
}
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IPartListener#partDeactivated(org.eclipse.ui.IWorkbenchPart )
*/
public void partDeactivated( IWorkbenchPart part )
{
fActivePart= null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.IPartListener#partOpened(org.eclipse.ui.IWorkbenchPart)
*/
public void partOpened( IWorkbenchPart part )
{
}
/**
* Tell me, i am activated.
*
*/
public void handleActivation( )
{
// if ( fIsHandlingActivation )
// return;
// fIsHandlingActivation = true;
// try
// // TODO: check external changes of file.
// // sanityCheckState( getEditorInput( ) );
// finally
// fIsHandlingActivation = false;
}
/**
* check the input is modify by file system.
*
* @param input
*/
protected void sanityCheckState( IEditorInput input )
{
if ( fModificationStamp == -1 )
{
fModificationStamp = getModificationStamp( input );
}
long stamp = getModificationStamp( input );
if ( stamp != fModificationStamp )
{
// reset the stamp whether user choose sync or not to avoid endless
// snag window.
fModificationStamp = stamp;
handleEditorInputChanged( );
}
}
/**
* Handles an external change of the editor's input element. Subclasses may
* extend.
*/
protected void handleEditorInputChanged( )
{
String title = Messages.getString( "ReportEditor.error.activated.outofsync.title" ); //$NON-NLS-1$
String msg = Messages.getString( "ReportEditor.error.activated.outofsync.message" ); //$NON-NLS-1$
if ( MessageDialog.openQuestion( getSite( ).getShell( ), title, msg ) )
{
IEditorInput input = getEditorInput( );
if ( input == null )
{
closeEditor( isSaveOnCloseNeeded( ) );
}
else
{
// getInputContext( ).setInput( input );
// rebuildModel( );
// superSetInput( input );
}
}
}
public void closeEditor( boolean save )
{
getSite( ).getPage( ).closeEditor( this, save );
}
protected long getModificationStamp( Object element )
{
if ( element instanceof IEditorInput )
{
IReportProvider provider = getProvider( );
if ( provider != null )
{
return computeModificationStamp( provider.getInputPath( (IEditorInput) element ) );
}
}
return 0;
}
protected long computeModificationStamp( IPath path )
{
return path.toFile( ).lastModified( );
}
/*
* (non-Javadoc)
*
* @see org.eclipse.ui.forms.editor.FormEditor#dispose()
*/
public void dispose( )
{
// dispose page
outlineBackup.dispose( );
dataBackup.dispose( );
List list = new ArrayList( pages );
int size = list.size( );
for ( int i = 0; i < size; i++ )
{
Object obj = list.get( i );
if ( obj instanceof IReportEditorPage )
{
( (IReportEditorPage) obj ).dispose( );
pages.remove( obj );
}
}
// getSite( ).getWorkbenchWindow( )
// .getPartService( )
// .removePartListener( this );
if ( fPalettePage != null )
{
fPalettePage.dispose( );
}
if ( outlinePage != null )
{
outlinePage.dispose( );
}
if ( dataPage != null )
{
dataPage.dispose( );
}
getSite( ).setSelectionProvider( null );
// remove the mediator listener
ReportMediator.removeGlobalColleague( this );
if ( getModel( ) != null )
{
getModel( ).close( );
}
IReportResourceSynchronizer synchronizer = ReportPlugin.getDefault( )
.getResourceSynchronizerService( );
if ( synchronizer != null )
{
synchronizer.removeListener(IReportResourceChangeEvent.LibraySaveChange|IReportResourceChangeEvent.ImageResourceChange|IReportResourceChangeEvent.DataDesignSaveChange, this );
}
PlatformUI.getWorkbench().removeWindowListener( windowListener);
if (prefs != null)
{
prefs.removePreferenceChangeListener( preferenceChangeListener );
}
super.dispose( );
}
protected void finalize( ) throws Throwable
{
if ( Policy.TRACING_PAGE_CLOSE )
{
System.out.println( "Report multi page finalized" ); //$NON-NLS-1$
}
super.finalize( );
}
public IEditorPart getEditorPart( )
{
return this;
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.report.designer.internal.ui.editors.parts.
* GraphicalEditorWithFlyoutPalette
* #performRequest(org.eclipse.birt.report.designer
* .core.util.mediator.request.ReportRequest)
*/
public void performRequest( ReportRequest request )
{
if ( ReportRequest.OPEN_EDITOR.equals( request.getType( ) )
&& ( request.getSelectionModelList( ).size( ) == 1 ) )
{
if ( request.getSelectionModelList( ).get( 0 ) instanceof MasterPageHandle )
{
handleOpenMasterPage( request );
return;
}
if ( request.getSelectionModelList( ).get( 0 ) instanceof ScriptObjectNode )
{
ScriptObjectNode node = (ScriptObjectNode)request.getSelectionModelList( ).get( 0 );
if (node.getParent( ) instanceof PropertyHandle)
{
PropertyHandle proHandle = (PropertyHandle)node.getParent( );
if (proHandle.getElementHandle( ).getModuleHandle( ).equals( getModel() ))
{
handleOpenScriptPage( request );
}
}
//handleOpenScriptPage( request );
return;
}
}
// super.performRequest( request );
}
/**
* @param request
*/
protected void handleOpenScriptPage( final ReportRequest request )
{
if ( this.getContainer( ).isVisible( ) )
{
setActivePage( ScriptForm_ID );
Display.getCurrent( ).asyncExec( new Runnable( ) {
public void run( )
{
ReportRequest r = new ReportRequest( );
r.setType( ReportRequest.SELECTION );
r.setSelectionObject( request.getSelectionModelList( ) );
SessionHandleAdapter.getInstance( )
.getMediator( )
.notifyRequest( r );
}
} );
}
}
/**
* @param request
*/
protected void handleOpenMasterPage( final ReportRequest request )
{
if ( this.getContainer( ).isVisible( ) )
{
setActivePage( LayoutMasterPage_ID );
Display.getCurrent( ).asyncExec( new Runnable( ) {
public void run( )
{
ReportRequest r = new ReportRequest( );
r.setType( ReportRequest.LOAD_MASTERPAGE );
r.setSelectionObject( request.getSelectionModelList( ) );
SessionHandleAdapter.getInstance( )
.getMediator( )
.notifyRequest( r );
}
} );
}
}
/**
* Returns current page instance if the currently selected page index is not
* -1, or <code>null</code> if it is.
*
* @return active page instance if selected, or <code>null</code> if no
* page is currently active.
*/
public IFormPage getCurrentPageInstance( )
{
int index = getCurrentPage( );
if ( index != -1 )
{
Object page = pages.get( index );
if ( page instanceof IFormPage )
return (IFormPage) page;
}
return null;
}
private void refreshGraphicalEditor()
{
for (int i=0; i<pages.size( ); i++)
{
Object page = pages.get( i );
if ( page instanceof IFormPage )
{
if (isGraphicalEditor(page))
{
if (((GraphicalEditorWithFlyoutPalette)page).getGraphicalViewer( ) != null)
{
EditPart root = ((GraphicalEditorWithFlyoutPalette)page).getGraphicalViewer( ).getRootEditPart( );
refreshResourceEditPart( root );
}
}
}
}
}
private boolean isGraphicalEditor(Object obj)
{
return obj instanceof GraphicalEditorWithFlyoutPalette;
//return LayoutEditor_ID.equals( id ) || LayoutMasterPage_ID.equals( id );
}
protected void setActivePage( int pageIndex )
{
super.setActivePage( pageIndex );
// setFocus( );
Display.getCurrent( ).asyncExec( new Runnable( ) {
public void run( )
{
setFocus( );
}
} );
}
/* (non-Javadoc)
* @see org.eclipse.birt.report.designer.ui.views.IReportResourceChangeListener#resourceChanged(org.eclipse.birt.report.designer.ui.views.IReportResourceChangeEvent)
*/
public void resourceChanged( IReportResourceChangeEvent event )
{
if ( ( event.getType( ) == IReportResourceChangeEvent.ImageResourceChange ) )
{
refreshGraphicalEditor( );
return;
}
if ( event.getSource( ).equals( getModel( ) ) )
{
return;
}
Object[] resolves = ElementAdapterManager.getAdapters( getModel( ),
IRelatedFileChangeResolve.class );
if (resolves == null)
{
return ;
}
for(int i=0;i<resolves.length; i++)
{
IRelatedFileChangeResolve find = (IRelatedFileChangeResolve)resolves[i];
if (find.acceptType( event.getType( ) ))
{
resolve = find;
needReload = find.isReload( event, getModel( ) );
needReset = find.isReset( event, getModel() );
break;
}
}
}
} |
package com.mapswithme.maps.api;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
public class MwmRequest {
private List<MWMPoint> mPoints = new ArrayList<MWMPoint>();
private PendingIntent mPendingIntent;
private String mTitle;
private double mZoomLevel = 1;
private boolean mReturnOnBalloonClick;
private boolean mPickPoint = false;
private String mCustomButtonName = "";
public MwmRequest setCustomButtonName(String buttonName) {
mCustomButtonName = buttonName != null ? buttonName : "";
return this;
}
public MwmRequest setTitle(String title) {
mTitle = title;
return this;
}
public MwmRequest setPickPointMode(boolean pickPoint) {
mPickPoint = pickPoint;
return this;
}
public MwmRequest addPoint(MWMPoint point) {
mPoints.add(point);
return this;
}
public MwmRequest addPoint(double lat, double lon, String name, String id) {
return addPoint(new MWMPoint(lat, lon, name, id));
}
public MwmRequest setPoints(Collection<MWMPoint> points) {
mPoints = new ArrayList<MWMPoint>(points);
return this;
}
public MwmRequest setReturnOnBalloonClick(boolean doReturn) {
mReturnOnBalloonClick = doReturn;
return this;
}
public MwmRequest setZoomLevel(double zoomLevel) {
mZoomLevel = zoomLevel;
return this;
}
public MwmRequest setPendingIntent(PendingIntent pi) {
mPendingIntent = pi;
return this;
}
public Intent toIntent(Context context) {
final Intent mwmIntent = new Intent(Const.ACTION_MWM_REQUEST);
// url
final String mwmUrl = createMwmUrl(context, mTitle, mZoomLevel, mPoints).toString();
mwmIntent.putExtra(Const.EXTRA_URL, mwmUrl);
// title
mwmIntent.putExtra(Const.EXTRA_TITLE, mTitle);
// more
mwmIntent.putExtra(Const.EXTRA_RETURN_ON_BALLOON_CLICK, mReturnOnBalloonClick);
// pick point
mwmIntent.putExtra(Const.EXTRA_PICK_POINT, mPickPoint);
// custom button name
mwmIntent.putExtra(Const.EXTRA_CUSTOM_BUTTON_NAME, mCustomButtonName);
final boolean hasIntent = mPendingIntent != null;
mwmIntent.putExtra(Const.EXTRA_HAS_PENDING_INTENT, hasIntent);
if (hasIntent)
mwmIntent.putExtra(Const.EXTRA_CALLER_PENDING_INTENT, mPendingIntent);
addCommonExtras(context, mwmIntent);
return mwmIntent;
}
/**
* @Hidden
* This method is internal only.
* Used for compatibility.
*/
MwmRequest setPoints(MWMPoint[] points) {
return setPoints(Arrays.asList(points));
}
// Below are utilities from MapsWithMeApi because we are not "Feature Envy"
private static StringBuilder createMwmUrl(Context context, String title, double zoomLevel, List<MWMPoint> points) {
final StringBuilder urlBuilder = new StringBuilder("mapswithme://map?");
// version
urlBuilder.append("v=").append(Const.API_VERSION).append("&");
// back url, always not null
urlBuilder.append("backurl=").append(getCallbackAction(context)).append("&");
// title
appendIfNotNull(urlBuilder, "appname", title);
// zoom
appendIfNotNull(urlBuilder, "z", isValidZoomLevel(zoomLevel) ? String.valueOf(zoomLevel) : null);
// points
for (final MWMPoint point : points) {
if (point != null) {
urlBuilder.append("ll=").append(String.format(Locale.US, "%f,%f&", point.getLat(), point.getLon()));
appendIfNotNull(urlBuilder, "n", point.getName());
appendIfNotNull(urlBuilder, "id", point.getId());
appendIfNotNull(urlBuilder, "s", point.getStyleForUrl());
}
}
return urlBuilder;
}
private static String getCallbackAction(Context context) {
return Const.CALLBACK_PREFIX + context.getPackageName();
}
@SuppressLint("NewApi")
private static Intent addCommonExtras(Context context, Intent intent) {
intent.putExtra(Const.EXTRA_CALLER_APP_INFO, context.getApplicationInfo());
intent.putExtra(Const.EXTRA_API_VERSION, Const.API_VERSION);
return intent;
}
private static StringBuilder appendIfNotNull(StringBuilder builder, String key, String value) {
if (value != null)
builder.append(key).append("=").append(Uri.encode(value)).append("&");
return builder;
}
private static boolean isValidZoomLevel(double zoom) {
return zoom >= MapsWithMeApi.ZOOM_MIN && zoom <= MapsWithMeApi.ZOOM_MAX;
}
} |
package biz.netcentric.cq.tools.actool.authorizableutils;
public class AuthorizableCreatorException extends Exception {
public AuthorizableCreatorException(final String message) {
super(message);
}
public AuthorizableCreatorException(final Throwable e) {
super(e);
}
} |
package org.duracloud.account.monitor.storereporter.util.impl;
import org.duracloud.account.monitor.storereporter.domain.StoreReporterInfo;
import org.duracloud.account.monitor.storereporter.util.StoreReporterUtil;
import org.duracloud.client.report.StorageReportManager;
import org.duracloud.client.report.StorageReportManagerImpl;
import org.duracloud.client.report.error.ReportException;
import org.duracloud.common.model.Credential;
import org.duracloud.common.util.ExceptionUtil;
import org.duracloud.reportdata.storage.StorageReportInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Calendar;
public class StoreReporterUtilImpl implements StoreReporterUtil {
private Logger log = LoggerFactory.getLogger(StoreReporterUtilImpl.class);
private StorageReportManager reportManager;
private String subdomain;
private int thresholdDays;
private static final String DOMAIN = ".duracloud.org";
private static final String PORT = "443";
private static final String CTXT_BOSS = "duraboss";
public StoreReporterUtilImpl(String subdomain,
Credential credential,
int thresholdDays) {
this(subdomain, credential, thresholdDays, null);
}
public StoreReporterUtilImpl(String subdomain,
Credential credential,
int thresholdDays,
StorageReportManager reportManager) {
if (null == reportManager) {
String host = subdomain + DOMAIN;
reportManager = new StorageReportManagerImpl(host, PORT, CTXT_BOSS);
reportManager.login(credential);
}
this.subdomain = subdomain;
this.thresholdDays = thresholdDays;
this.reportManager = reportManager;
}
@Override
public StoreReporterInfo pingStorageReporter() {
StorageReportInfo reportInfo = null;
StringBuilder error = new StringBuilder();
// Get current status of Storage Reporter.
try {
reportInfo = reportManager.getStorageReportInfo();
} catch (ReportException e) {
error.append(e.getMessage());
error.append("\n");
error.append(ExceptionUtil.getStackTraceAsString(e));
log.error("Error StoreReportUtil.pingStorageReporter: {}", error);
}
// Was any status returned?
if (null == reportInfo) {
error.append("Unable to collect StorageReportInfo: null");
} else {
// Determine if the Storage Reporter has hung.
long nextStart = reportInfo.getNextScheduledStartTime();
if (isThresholdDaysAgo(nextStart)) {
error.append("Next scheduled storage report is more than ");
error.append(thresholdDays);
error.append(" days AGO.");
error.append("\n");
}
}
// Collect result.
StoreReporterInfo result = new StoreReporterInfo(subdomain);
if (error.length() > 0) {
result.setError(error.toString());
} else {
result.setSuccess();
}
return result;
}
/**
* @param timeMillis of date in question
* @return true if arg timeMillis is greater than threshold days ago
*/
private boolean isThresholdDaysAgo(long timeMillis) {
Calendar nextDate = Calendar.getInstance();
nextDate.setTimeInMillis(timeMillis);
Calendar thresholdDaysAgo = Calendar.getInstance();
thresholdDaysAgo.add(Calendar.DATE, -thresholdDays);
return nextDate.before(thresholdDaysAgo);
}
} |
package org.csstudio.swt.rtplot.internal;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Stack;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import org.csstudio.swt.rtplot.Activator;
import org.csstudio.swt.rtplot.Annotation;
import org.csstudio.swt.rtplot.AxisRange;
import org.csstudio.swt.rtplot.Messages;
import org.csstudio.swt.rtplot.RTPlotListener;
import org.csstudio.swt.rtplot.SWTMediaPool;
import org.csstudio.swt.rtplot.Trace;
import org.csstudio.swt.rtplot.YAxis;
import org.csstudio.swt.rtplot.data.PlotDataItem;
import org.csstudio.swt.rtplot.internal.util.ScreenTransform;
import org.csstudio.swt.rtplot.undo.ChangeAxisRanges;
import org.csstudio.swt.rtplot.undo.UndoableActionManager;
import org.csstudio.swt.rtplot.undo.UpdateAnnotationAction;
import org.csstudio.swt.rtplot.util.UpdateThrottle;
import org.eclipse.swt.SWT;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.MouseMoveListener;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
/** Plot with axes and area that displays the traces
* @param <XTYPE> Data type used for the {@link PlotDataItem}
* @author Kay Kasemir
*/
@SuppressWarnings("nls")
public class Plot<XTYPE extends Comparable<XTYPE>> extends Canvas implements PaintListener, MouseListener, MouseMoveListener, MouseTrackListener
{
final private static int ARROW_SIZE = 8;
private static final double ZOOM_FACTOR = 1.5;
/** When using 'rubberband' to zoom in, need to select a region
* at least this wide resp. high.
* Smaller regions are likely the result of an accidental
* click-with-jerk, which would result into a huge zoom step.
*/
private static final int ZOOM_PIXEL_THRESHOLD = 20;
/** Support for un-do and re-do */
final private UndoableActionManager undo = new UndoableActionManager();
final private SWTMediaPool media;
/** Display */
final private Display display;
/** Background color */
private volatile RGB background = new RGB(255, 255, 255);
/** Opacity (0 .. 100 %) of 'area' */
private volatile int opacity = 20;
/** Font to use for, well, title */
private volatile Font title_font;
/** Font to use for labels */
private volatile Font label_font;
/** Font to use for scale */
private volatile Font scale_font;
/** Font to use for legend */
private volatile Font legend_font;
/** Area of this canvas */
private volatile Rectangle area = new Rectangle(0, 0, 0, 0);
/** Does layout need to be re-computed? */
final private AtomicBoolean need_layout = new AtomicBoolean(true);
/** Buffer for image of axes, plot area, but not mouse feedback.
*
* <p>UpdateThrottle calls updateImageBuffer() to set the image
* in its thread, PaintListener draws it in UI thread,
* and getImage() may hand a safe copy for printing, saving, e-mailing.
*
* <p>Synchronizing to access one and the same image
* deadlocks on Linux, so a new image is created for updates.
* To avoid access to disposed image, SYNC on the actual image during access.
*/
private volatile Optional<Image> plot_image = Optional.empty();
final private UpdateThrottle update_throttle;
final private TitlePart title_part;
final private List<Trace<XTYPE>> traces = new CopyOnWriteArrayList<>();
final private AxisPart<XTYPE> x_axis;
final private List<YAxisImpl<XTYPE>> y_axes = new CopyOnWriteArrayList<>();
final private PlotPart plot_area;
final private TracePainter<XTYPE> trace_painter = new TracePainter<XTYPE>();
final private List<AnnotationImpl<XTYPE>> annotations = new CopyOnWriteArrayList<>();
final private LegendPart<XTYPE> legend;
final private PlotProcessor<XTYPE> plot_processor;
final private Runnable redraw_runnable = () ->
{
if (isDisposed())
return;
try
{
redraw();
}
catch (SWTException ex)
{
if (! ex.getMessage().contains("disposed"))
Activator.getLogger().log(Level.WARNING, "Redraw failed", ex);
}
};
private boolean show_crosshair = false;
private MouseMode mouse_mode = MouseMode.NONE;
private Optional<Point> mouse_start = Optional.empty();
private volatile Optional<Point> mouse_current = Optional.empty();
private AxisRange<XTYPE> mouse_start_x_range;
private List<AxisRange<Double>> mouse_start_y_ranges = new ArrayList<>();
private int mouse_y_axis = -1;
private Stack<Boolean> pre_pan_auto_scales = new Stack<Boolean>();
// Annotation-related info. If mouse_annotation is set, the rest should be set.
private Optional<AnnotationImpl<XTYPE>> mouse_annotation = Optional.empty();
private Point mouse_annotation_start_offset;
private XTYPE mouse_annotation_start_position;
private double mouse_annotation_start_value;
/** Listener to X Axis {@link PlotPart} */
final PlotPartListener x_axis_listener = new PlotPartListener()
{
@Override
public void layoutPlotPart(final PlotPart plotPart)
{
need_layout.set(true);
}
@Override
public void refreshPlotPart(final PlotPart plotPart)
{
updateCursor();
requestUpdate();
}
};
/** Listener to Title, Y Axis and plot area {@link PlotPart}s */
final PlotPartListener plot_part_listener = new PlotPartListener()
{
@Override
public void layoutPlotPart(final PlotPart plotPart)
{
need_layout.set(true);
}
@Override
public void refreshPlotPart(final PlotPart plotPart)
{
requestUpdate();
}
};
final private List<RTPlotListener<XTYPE>> listeners = new CopyOnWriteArrayList<>();
private volatile Optional<List<CursorMarker>> cursor_markers = Optional.empty();
/** Constructor
* @param parent Parent widget
* @param type Type of X axis
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public Plot(final Composite parent, final Class<XTYPE> type)
{
super(parent, SWT.NO_BACKGROUND);
title_font = parent.getFont();
label_font = parent.getFont();
scale_font = parent.getFont();
legend_font = parent.getFont();
media = new SWTMediaPool(parent.getDisplay());
display = parent.getDisplay();
plot_processor = new PlotProcessor<XTYPE>(this);
// To avoid unchecked cast, X axis would need to be passed in,
// but its listener can only be created within this class.
// When passing X axis in, its listener needs to be set
// in here, but an axis design with final listener was preferred.
if (type == Double.class)
x_axis = (AxisPart) new HorizontalNumericAxis("X", x_axis_listener);
else if (type == Instant.class)
x_axis = (AxisPart) TimeAxis.forDuration("Time", x_axis_listener, Duration.ofMinutes(2));
else
throw new IllegalArgumentException("Cannot handle " + type.getName());
addYAxis("Value 1");
title_part = new TitlePart("", plot_part_listener);
plot_area = new PlotPart("main", plot_part_listener);
legend = new LegendPart<XTYPE>("legend", plot_part_listener);
setMouseMode(MouseMode.PAN);
// 50Hz default throttle
update_throttle = new UpdateThrottle(50, TimeUnit.MILLISECONDS,
() ->
{
plot_processor.autoscale();
updateImageBuffer();
redrawSafely();
});
addControlListener(new ControlAdapter()
{
@Override
public void controlResized(final ControlEvent e)
{
area = getClientArea();
need_layout.set(true);
requestUpdate();
}
});
addPaintListener(this);
addMouseListener(this);
addMouseMoveListener(this);
addMouseTrackListener(this);
addDisposeListener((final DisposeEvent e) -> handleDisposal());
}
/** @param listener Listener to add */
public void addListener(final RTPlotListener<XTYPE> listener)
{
Objects.requireNonNull(listener);
listeners.add(listener);
}
/** @param listener Listener to remove */
public void removeListener(final RTPlotListener<XTYPE> listener)
{
Objects.requireNonNull(listener);
listeners.remove(listener);
}
/** @return {@link UndoableActionManager} for this plot */
public UndoableActionManager getUndoableActionManager()
{
return undo;
}
/** @param color Background color */
public void setBackground(final RGB color)
{
background = color;
}
/** Opacity (0 .. 100 %) of 'area' */
public void setOpacity(final int opacity)
{
this.opacity = opacity;
}
/** @param title Title */
public void setTitle(final Optional<String> title)
{
title_part.setName(title.orElse(""));
}
/** @param font Font to use for title */
public void setTitleFont(final FontData font)
{
title_font = media.get(font);
need_layout.set(true);
requestUpdate();
}
/** @param font Font to use for labels */
public void setLabelFont(final FontData font)
{
label_font = media.get(font);
need_layout.set(true);
requestUpdate();
}
/** @param font Font to use for scale */
public void setScaleFont(final FontData font)
{
scale_font = media.get(font);
need_layout.set(true);
requestUpdate();
}
/** @return <code>true</code> if legend is visible */
public boolean isLegendVisible()
{
return legend.isVisible();
}
/** @param show <code>true</code> if legend should be displayed */
public void showLegend(final boolean show)
{
legend.setVisible(show);
need_layout.set(true);
requestUpdate();
for (RTPlotListener<XTYPE> listener : listeners)
listener.changedLegend(show);
}
/** @param font Font to use for scale */
public void setLegendFont(final FontData font)
{
legend_font = media.get(font);
need_layout.set(true);
requestUpdate();
}
/** @return X/Time axis */
public AxisPart<XTYPE> getXAxis()
{
return x_axis;
}
/** Add another Y axis
* @param name
* @return Y Axis that was added
*/
public YAxis<XTYPE> addYAxis(final String name)
{
YAxisImpl<XTYPE> axis = new YAxisImpl<XTYPE>(name, plot_part_listener);
y_axes.add(axis);
need_layout.set(true);
return axis;
}
/** @return Y axes */
public List<YAxisImpl<XTYPE>> getYAxes()
{
final List<YAxisImpl<XTYPE>> copy = new ArrayList<>();
copy.addAll(y_axes);
return copy;
}
/** @param index Index of Y axis to remove */
public void removeYAxis(final int index)
{
y_axes.remove(index);
need_layout.set(true);
}
/** Add trace to the plot
* @param trace {@link Trace}, where axis must be a valid Y axis index
*/
public void addTrace(final TraceImpl<XTYPE> trace)
{
traces.add(trace);
y_axes.get(trace.getYAxis()).addTrace(trace);
need_layout.set(true);
requestUpdate();
}
/** @param trace Trace to move from its current Y axis
* @param new_y_axis Index of new Y Axis
*/
public void moveTrace(final TraceImpl<XTYPE> trace, final int new_y_axis)
{
Objects.requireNonNull(trace);
y_axes.get(trace.getYAxis()).removeTrace(trace);
trace.setYAxis(new_y_axis);
y_axes.get(trace.getYAxis()).addTrace(trace);
}
/** @return Thread-safe, read-only traces of the plot */
public Iterable<Trace<XTYPE>> getTraces()
{
return traces;
}
/** @return Count the number of traces */
public int getTraceCount(){
return traces.size();
}
/** Remove trace from plot
* @param trace {@link Trace}, where axis must be a valid Y axis index
*/
public void removeTrace(final Trace<XTYPE> trace)
{
Objects.requireNonNull(trace);
traces.remove(trace);
y_axes.get(trace.getYAxis()).removeTrace(trace);
need_layout.set(true);
requestUpdate();
}
/** @return {@link Image} of current plot. Caller must dispose */
public Image getImage()
{
Image image = plot_image.orElse(null);
if (image != null)
synchronized (image)
{
return new Image(display, image, SWT.IMAGE_COPY);
}
return new Image(display, 10, 10);
}
/** Update the dormant time between updates
* @param dormant_time How long throttle remains dormant after a trigger
* @param unit Units for the dormant period
*/
public void setUpdateThrottle(final long dormant_time, final TimeUnit unit)
{
update_throttle.setDormantTime(dormant_time, unit);
}
/** Request a complete redraw of the plot */
final public void requestUpdate()
{
update_throttle.trigger();
}
/** Redraw the current image and cursors
*
* <p>Like <code>redraw()</code>, but may be called
* from any thread.
*/
final void redrawSafely()
{
if (! display.isDisposed())
display.asyncExec(redraw_runnable);
}
/** Add Annotation to a trace,
* determining initial position based on some
* sample of that trace
* @param trace Trace to which a Annotation should be added
* @param text Text for the annotation
*/
public void addAnnotation(final Trace<XTYPE> trace, final String text)
{
Objects.requireNonNull(trace);
plot_processor.createAnnotation(trace, text);
}
/** @param annotation Annotation to add */
@SuppressWarnings({ "rawtypes", "unchecked" })
public void addAnnotation(final Annotation<XTYPE> annotation)
{
Objects.requireNonNull(annotation);
if (annotation instanceof AnnotationImpl)
annotations.add((AnnotationImpl)annotation);
else
annotations.add(new AnnotationImpl<XTYPE>(annotation.getTrace(), annotation.getPosition(),
annotation.getValue(), annotation.getOffset(),
annotation.getText()));
requestUpdate();
fireAnnotationsChanged();
}
/** @return Current {@link AnnotationImpl}s */
public List<AnnotationImpl<XTYPE>> getAnnotations()
{
return annotations;
}
/** Update location and value of annotation
* @param annotation {@link AnnotationImpl} to update
* @param position New position
* @param value New value
*/
public void updateAnnotation(final AnnotationImpl<XTYPE> annotation, final XTYPE position, final double value,
final Point offset)
{
annotation.setLocation(position, value);
annotation.setOffset(offset);
requestUpdate();
fireAnnotationsChanged();
}
public void updateAnnotation(final Annotation<XTYPE> annotation, final String text)
{
final int index = annotations.indexOf(annotation);
if (index < 0)
throw new IllegalArgumentException("Unknown annotation " + annotation);
annotations.get(index).setText(text);
requestUpdate();
fireAnnotationsChanged();
}
/** @param annotation Annotation to remove */
public void removeAnnotation(final Annotation<XTYPE> annotation)
{
annotations.remove(annotation);
requestUpdate();
fireAnnotationsChanged();
}
/** Select Annotation at mouse position?
* @return Was a mouse annotation set?
*/
private boolean selectMouseAnnotation()
{
if (mouse_start.isPresent())
for (AnnotationImpl<XTYPE> annotation : annotations)
if (annotation.isSelected(mouse_start.get()))
{
mouse_annotation_start_offset = annotation.getOffset();
mouse_annotation_start_position = annotation.getPosition();
mouse_annotation_start_value = annotation.getValue();
mouse_annotation = Optional.of(annotation);
requestUpdate();
return true;
}
return false;
}
/** De-select an Annotation */
private void deselectMouseAnnotation()
{
if (mouse_annotation.isPresent())
{
AnnotationImpl<XTYPE> anno = mouse_annotation.get();
undo.add(new UpdateAnnotationAction<XTYPE>(this, anno,
mouse_annotation_start_position, mouse_annotation_start_value,
mouse_annotation_start_offset,
anno.getPosition(), anno.getValue(),
anno.getOffset()));
anno.deselect();
mouse_annotation = Optional.empty();
requestUpdate();
}
}
/** Compute layout of plot components */
private void computeLayout(final GC gc, final Rectangle bounds)
{
// Title on top, as high as desired
final int title_height = title_part.getDesiredHeight(gc, title_font);
title_part.setBounds(0, 0, bounds.width, title_height);
// Legend on bottom, as high as desired
final int legend_height = legend.getDesiredHeight(gc, bounds.width, legend_font, traces);
legend.setBounds(0, bounds.height-legend_height, bounds.width, legend_height);
// X Axis as high as desired. Width will depend on Y axes.
x_axis.setLabelFont(label_font.getFontData()[0]);
x_axis.setScaleFont(scale_font.getFontData()[0]);
final int x_axis_height = x_axis.getDesiredPixelSize(bounds, gc);
final int y_axis_height = bounds.height - title_height - x_axis_height - legend_height;
// Ask each Y Axis for its widths, which changes based on number of labels
// and how they are laid out
int total_left_axes_width = 0, total_right_axes_width = 0;
int plot_width = bounds.width;
final List<YAxisImpl<XTYPE>> save_copy = new ArrayList<>(y_axes);
// First, lay out 'left' axes in reverse order to get "2, 1, 0" on the left of the plot.
for (YAxisImpl<XTYPE> axis : save_copy)
if (! axis.isOnRight())
{
final Rectangle axis_region = new Rectangle(total_left_axes_width, title_height, plot_width, y_axis_height);
axis.setLabelFont(label_font.getFontData()[0]);
axis.setScaleFont(scale_font.getFontData()[0]);
axis_region.width = axis.getDesiredPixelSize(axis_region, gc);
axis.setBounds(axis_region);
total_left_axes_width += axis_region.width;
plot_width -= axis_region.width;
}
// Then lay out 'right' axes, also in reverse order, to get "0, 1, 2" on right side of plot.
for (YAxisImpl<XTYPE> axis : save_copy)
if (axis.isOnRight())
{
final Rectangle axis_region = new Rectangle(total_left_axes_width, title_height, plot_width, y_axis_height);
axis.setLabelFont(label_font.getFontData()[0]);
axis.setScaleFont(scale_font.getFontData()[0]);
axis_region.width = axis.getDesiredPixelSize(axis_region, gc);
total_right_axes_width += axis_region.width;
axis_region.x = bounds.width - total_right_axes_width;
axis.setBounds(axis_region);
plot_width -= axis_region.width;
}
x_axis.setBounds(total_left_axes_width, title_height+y_axis_height, plot_width, x_axis_height);
plot_area.setBounds(total_left_axes_width, title_height, plot_width, y_axis_height);
}
/** Draw all components into image buffer */
private void updateImageBuffer()
{
final Rectangle area_copy = area;
if (area_copy.width <= 0 || area_copy.height <= 0)
return;
final Image image = new Image(display, area_copy);
final GC gc = new GC(image);
if (need_layout.getAndSet(false))
computeLayout(gc, area_copy);
final Rectangle plot_bounds = plot_area.getBounds();
gc.setBackground(media.get(background));
gc.fillRectangle(area_copy);
title_part.paint(gc, media, title_font);
legend.paint(gc, media, legend_font, traces);
// Fetch x_axis transformation and use that to paint all traces,
// because X Axis tends to change from scrolling
// while we're painting traces
// x_axis.setLabelFont(label_font);
// x_axis.setScaleFont(scale_font);
x_axis.paint(gc, media, plot_bounds);
final ScreenTransform<XTYPE> x_transform = x_axis.getScreenTransform();
for (YAxisImpl<XTYPE> y_axis : y_axes)
{
// y_axis.setLabelFont(label_font);
// y_axis.setScaleFont(scale_font);
y_axis.paint(gc, media, plot_bounds);
}
gc.setClipping(plot_bounds);
plot_area.paint(gc, media);
for (YAxisImpl<XTYPE> y_axis : y_axes)
for (Trace<XTYPE> trace : y_axis.getTraces())
trace_painter.paint(gc, media, plot_area.getBounds(), opacity, x_transform, y_axis, trace);
// Annotations use label font
gc.setFont(label_font);
for (AnnotationImpl<XTYPE> annotation : annotations)
annotation.paint(gc, media, x_axis, y_axes.get(annotation.getTrace().getYAxis()));
gc.dispose();
// Update image
final Image old_image = plot_image.orElse(null);
plot_image = Optional.of(image);
if (old_image != null)
{
synchronized (old_image)
{
old_image.dispose();
}
}
}
/** PaintListener: {@inheritDoc} */
@Override
public void paintControl(final PaintEvent e)
{
Activator.getLogger().finer("paint");
final GC gc = e.gc;
final Image image = plot_image.orElse(null);
if (image != null)
synchronized (image)
{
gc.drawImage(image, 0, 0);
}
drawMouseModeFeedback(gc);
}
/** Draw visual feedback (rubber band rectangle etc.)
* for current mouse mode
* @param gc GC
*/
private void drawMouseModeFeedback(final GC gc)
{ // Safe copy, then check null (== isPresent())
final Point current = mouse_current.orElse(null);
if (current == null)
return;
final Point start = mouse_start.orElse(null);
final Rectangle plot_bounds = plot_area.getBounds();
if (mouse_mode == MouseMode.PAN_X || mouse_mode == MouseMode.PAN_Y || mouse_mode == MouseMode.PAN_PLOT)
{
// NOP, minimize additional UI thread drawing to allow better 'pan' updates
}
else if (show_crosshair && plot_bounds.contains(current))
{ // Cross-hair Cursor
gc.drawLine(area.x, current.y, area.x + area.width, current.y);
gc.drawLine(current.x, area.y, current.x, area.y + area.height);
// Corresponding axis ticks
gc.setBackground(media.get(background));
x_axis.drawTickLabel(gc, media, x_axis.getValue(current.x), true);
for (YAxisImpl<XTYPE> axis : y_axes)
axis.drawTickLabel(gc, media, axis.getValue(current.y), true);
// Trace markers
final List<CursorMarker> safe_markers = cursor_markers.orElse(null);
if (safe_markers != null)
CursorMarker.drawMarkers(gc, media, safe_markers, area);
}
if (mouse_mode == MouseMode.ZOOM_IN || mouse_mode == MouseMode.ZOOM_OUT)
{ // Update mouse pointer in read-to-zoom mode
if (plot_bounds.contains(current))
setCursor(display.getSystemCursor(SWT.CURSOR_SIZEALL));
else if (x_axis.getBounds().contains(current))
setCursor(display.getSystemCursor(SWT.CURSOR_SIZEWE));
else
{
for (YAxisImpl<XTYPE> axis : y_axes)
if (axis.getBounds().contains(current))
{
setCursor(display.getSystemCursor(SWT.CURSOR_SIZENS));
return;
}
setCursor(display.getSystemCursor(SWT.CURSOR_NO));
}
}
else if (mouse_mode == MouseMode.ZOOM_IN_X && start != null)
{
final int left = Math.min(start.x, current.x);
final int right = Math.max(start.x, current.x);
final int width = right - left;
final int mid_y = plot_bounds.y + plot_bounds.height / 2;
// Range on axis
gc.drawRectangle(left, start.y, width, 1);
// Left, right vertical bar
gc.drawLine(left, plot_bounds.y, left, plot_bounds.y + plot_bounds.height);
gc.drawLine(right, plot_bounds.y, right, plot_bounds.y + plot_bounds.height);
if (width >= 5*ARROW_SIZE)
{
gc.drawLine(left, mid_y, left + 2*ARROW_SIZE, mid_y);
gc.drawLine(left+ARROW_SIZE, mid_y-ARROW_SIZE, left + 2*ARROW_SIZE, mid_y);
gc.drawLine(left+ARROW_SIZE, mid_y+ARROW_SIZE, left + 2*ARROW_SIZE, mid_y);
gc.drawLine(right, mid_y, right - 2*ARROW_SIZE, mid_y);
gc.drawLine(right-ARROW_SIZE, mid_y-ARROW_SIZE, right - 2*ARROW_SIZE, mid_y);
gc.drawLine(right-ARROW_SIZE, mid_y+ARROW_SIZE, right - 2*ARROW_SIZE, mid_y);
}
}
else if (mouse_mode == MouseMode.ZOOM_IN_Y && start != null)
{
final int top = Math.min(start.y, current.y);
final int bottom = Math.max(start.y, current.y);
final int height = bottom - top;
final int mid_x = plot_bounds.x + plot_bounds.width / 2;
// Range on axis
gc.drawRectangle(start.x, top, 1, height);
// Top, bottom horizontal bar
gc.drawLine(plot_bounds.x, top, plot_bounds.x + plot_bounds.width, top);
gc.drawLine(plot_bounds.x, bottom, plot_bounds.x + plot_bounds.width, bottom);
if (height >= 5 * ARROW_SIZE)
{
gc.drawLine(mid_x, top, mid_x, top + 2*ARROW_SIZE);
gc.drawLine(mid_x-ARROW_SIZE, top+ARROW_SIZE, mid_x, top + 2*ARROW_SIZE);
gc.drawLine(mid_x+ARROW_SIZE, top+ARROW_SIZE, mid_x, top + 2*ARROW_SIZE);
gc.drawLine(mid_x, bottom - 2*ARROW_SIZE, mid_x, bottom);
gc.drawLine(mid_x, bottom - 2*ARROW_SIZE, mid_x-ARROW_SIZE, bottom - ARROW_SIZE);
gc.drawLine(mid_x, bottom - 2*ARROW_SIZE, mid_x+ARROW_SIZE, bottom - ARROW_SIZE);
}
}
else if (mouse_mode == MouseMode.ZOOM_IN_PLOT && start != null)
{
final int left = Math.min(start.x, current.x);
final int right = Math.max(start.x, current.x);
final int top = Math.min(start.y, current.y);
final int bottom = Math.max(start.y, current.y);
final int width = right - left;
final int height = bottom - top;
final int mid_x = left + width / 2;
final int mid_y = top + height / 2;
gc.drawRectangle(left, top, width, height);
if (width >= 5*ARROW_SIZE)
{
gc.drawLine(left, mid_y, left + 2*ARROW_SIZE, mid_y);
gc.drawLine(left+ARROW_SIZE, mid_y-ARROW_SIZE, left + 2*ARROW_SIZE, mid_y);
gc.drawLine(left+ARROW_SIZE, mid_y+ARROW_SIZE, left + 2*ARROW_SIZE, mid_y);
gc.drawLine(right, mid_y, right - 2*ARROW_SIZE, mid_y);
gc.drawLine(right-ARROW_SIZE, mid_y-ARROW_SIZE, right - 2*ARROW_SIZE, mid_y);
gc.drawLine(right-ARROW_SIZE, mid_y+ARROW_SIZE, right - 2*ARROW_SIZE, mid_y);
}
if (height >= 5*ARROW_SIZE)
{
gc.drawLine(mid_x, top, mid_x, top + 2*ARROW_SIZE);
gc.drawLine(mid_x-ARROW_SIZE, top+ARROW_SIZE, mid_x, top + 2*ARROW_SIZE);
gc.drawLine(mid_x+ARROW_SIZE, top+ARROW_SIZE, mid_x, top + 2*ARROW_SIZE);
gc.drawLine(mid_x, bottom - 2*ARROW_SIZE, mid_x, bottom);
gc.drawLine(mid_x, bottom - 2*ARROW_SIZE, mid_x-ARROW_SIZE, bottom - ARROW_SIZE);
gc.drawLine(mid_x, bottom - 2*ARROW_SIZE, mid_x+ARROW_SIZE, bottom - ARROW_SIZE);
}
}
}
/** Invoked as {@link DisposeListener} */
private void handleDisposal()
{ // Stop updates which could otherwise still use
// what's about to be disposed
update_throttle.dispose();
// .. then release resources
for (PlotPart y_axis : y_axes)
y_axis.dispose();
x_axis.dispose();
plot_area.dispose();
final Image old_image = plot_image.orElse(null);
plot_image = Optional.empty();
if (old_image != null)
synchronized (old_image)
{
old_image.dispose();
}
media.dispose();
}
/** @param show Show the cross-hair cursor? */
public void showCrosshair(final boolean show)
{
show_crosshair = show;
}
public void setMouseMode(final MouseMode mode)
{
if (mode.ordinal() >= MouseMode.INTERNAL_MODES.ordinal())
throw new IllegalArgumentException("Not permitted to set " + mode);
mouse_mode = mode;
// Selecting system cursor.
// Custom cursors are not supported with RAP..
switch (mode)
{
case PAN:
setCursor(display.getSystemCursor(SWT.CURSOR_HAND));
break;
case ZOOM_IN:
setCursor(display.getSystemCursor(SWT.CURSOR_CROSS));
break;
default:
setCursor(display.getSystemCursor(SWT.CURSOR_ARROW));
}
}
/** MouseListener: {@inheritDoc} */
@Override
public void mouseDown(final MouseEvent e)
{
// Don't start mouse actions when user invokes context menu
if (e.button != 1 || e.stateMask != 0)
return;
final Point current = new Point(e.x, e.y);
mouse_start = mouse_current = Optional.of(current);
if (selectMouseAnnotation())
return;
else if (mouse_mode == MouseMode.PAN)
{ // Determine start of 'pan'
mouse_start_x_range = x_axis.getValueRange();
mouse_start_y_ranges.clear();
for (int i=0; i<y_axes.size(); ++i)
{
final YAxisImpl<XTYPE> axis = y_axes.get(i);
mouse_start_y_ranges.add(axis.getValueRange());
if (axis.getBounds().contains(current))
{
mouse_y_axis = i;
mouse_mode = MouseMode.PAN_Y;
// Store the auto scale state during mouse actions,
// we can use it later to create an un-doable action.
pre_pan_auto_scales.push(axis.isAutoscale());
axis.setAutoscale(false);
fireAutoScaleChange(axis);
return;
}
}
if (plot_area.getBounds().contains(current)) {
mouse_mode = MouseMode.PAN_PLOT;
for (YAxisImpl<XTYPE> axis : y_axes) {
pre_pan_auto_scales.push(axis.isAutoscale());
axis.setAutoscale(false);
fireAutoScaleChange(axis);
}
}
else if (x_axis.getBounds().contains(current))
mouse_mode = MouseMode.PAN_X;
}
else if (mouse_mode == MouseMode.ZOOM_IN)
{ // Determine start of 'rubberband' zoom.
// Reset cursor from SIZE* to CROSS.
for (int i=0; i<y_axes.size(); ++i)
if (y_axes.get(i).getBounds().contains(current))
{
mouse_y_axis = i;
mouse_mode = MouseMode.ZOOM_IN_Y;
setCursor(display.getSystemCursor(SWT.CURSOR_CROSS));
return;
}
if (plot_area.getBounds().contains(current))
{
mouse_mode = MouseMode.ZOOM_IN_PLOT;
setCursor(display.getSystemCursor(SWT.CURSOR_CROSS));
}
else if (x_axis.getBounds().contains(current))
{
mouse_mode = MouseMode.ZOOM_IN_X;
setCursor(display.getSystemCursor(SWT.CURSOR_CROSS));
}
}
else if (mouse_mode == MouseMode.ZOOM_OUT)
{ // Zoom 'out' from where the mouse was clicked
if (x_axis.getBounds().contains(current))
{ // Zoom out of X axis
final AxisRange<XTYPE> orig = x_axis.getValueRange();
x_axis.zoom(current.x, ZOOM_FACTOR);
undo.add(new ChangeAxisRanges<XTYPE>(this, Messages.Zoom_Out_X, x_axis, orig, x_axis.getValueRange()));
fireXAxisChange();
}
else if (plot_area.getBounds().contains(current))
{ // Zoom out of X..
final AxisRange<XTYPE> orig_x = x_axis.getValueRange();
x_axis.zoom(current.x, ZOOM_FACTOR);
fireXAxisChange();
// .. and Y axes
final List<AxisRange<Double>> old_range = new ArrayList<>(y_axes.size()),
new_range = new ArrayList<>(y_axes.size());
for (YAxisImpl<XTYPE> axis : y_axes)
{
old_range.add(axis.getValueRange());
axis.zoom(current.y, ZOOM_FACTOR);
new_range.add(axis.getValueRange());
fireYAxisChange(axis);
}
undo.execute(new ChangeAxisRanges<XTYPE>(this, Messages.Zoom_Out,
x_axis, orig_x, x_axis.getValueRange(), y_axes, old_range, new_range));
}
else
{
for (YAxisImpl<XTYPE> axis : y_axes)
if (axis.getBounds().contains(current))
{
final AxisRange<Double> orig = axis.getValueRange();
axis.zoom(current.y, ZOOM_FACTOR);
fireYAxisChange(axis);
undo.add(new ChangeAxisRanges<XTYPE>(this, Messages.Zoom_Out_Y,
Arrays.asList(axis),
Arrays.asList(orig),
Arrays.asList(axis.getValueRange())));
break;
}
}
}
}
/** MouseMoveListener: {@inheritDoc} */
@Override
public void mouseMove(final MouseEvent e)
{
final Point current = new Point(e.x, e.y);
mouse_current = Optional.of(current);
final Point start = mouse_start.orElse(null);
if (mouse_annotation.isPresent() && start != null)
{
final AnnotationImpl<XTYPE> anno = mouse_annotation.get();
if (anno.getSelection() == AnnotationImpl.Selection.Body)
{
anno.setOffset(
new Point(mouse_annotation_start_offset.x + current.x - start.x,
mouse_annotation_start_offset.y + current.y - start.y));
requestUpdate();
fireAnnotationsChanged();
}
else
plot_processor.updateAnnotation(anno, x_axis.getValue(current.x));
}
else if (mouse_mode == MouseMode.PAN_X && start != null)
x_axis.pan(mouse_start_x_range, x_axis.getValue(start.x), x_axis.getValue(current.x));
else if (mouse_mode == MouseMode.PAN_Y && start != null)
{
final YAxisImpl<XTYPE> axis = y_axes.get(mouse_y_axis);
axis.pan(mouse_start_y_ranges.get(mouse_y_axis), axis.getValue(start.y), axis.getValue(current.y));
}
else if (mouse_mode == MouseMode.PAN_PLOT && start != null)
{
x_axis.pan(mouse_start_x_range, x_axis.getValue(start.x), x_axis.getValue(current.x));
for (int i=0; i<y_axes.size(); ++i)
{
final YAxisImpl<XTYPE> axis = y_axes.get(i);
axis.pan(mouse_start_y_ranges.get(i), axis.getValue(start.y), axis.getValue(current.y));
}
}
else
updateCursor();
}
/** Request update of cursor markers */
private void updateCursor()
{
final Point current = mouse_current.orElse(null);
if (current == null)
return;
final int x = current.x;
final XTYPE location = x_axis.getValue(x);
plot_processor.updateCursorMarkers(x, location, this::updateCursors);
}
/** Called by {@link PlotProcessor}
* @param markers Markes for current cursor position
*/
private void updateCursors(final List<CursorMarker> markers)
{
cursor_markers = Optional.ofNullable(markers);
redrawSafely();
fireCursorsChanged();
}
/** MouseListener: {@inheritDoc} */
@Override
public void mouseUp(final MouseEvent e)
{
deselectMouseAnnotation();
final Point start = mouse_start.orElse(null);
final Point current = mouse_current.orElse(null);
if (start == null || current == null)
return;
if (mouse_mode == MouseMode.PAN_X)
{
mouseMove(e);
undo.add(new ChangeAxisRanges<XTYPE>(this, Messages.Pan_X, x_axis, mouse_start_x_range, x_axis.getValueRange()));
fireXAxisChange();
mouse_mode = MouseMode.PAN;
}
else if (mouse_mode == MouseMode.PAN_Y)
{
mouseMove(e);
final YAxisImpl<XTYPE> y_axis = y_axes.get(mouse_y_axis);
List<Boolean> new_autoscales = Arrays.asList(new Boolean[y_axes.size()]);
Collections.fill(new_autoscales, Boolean.FALSE);
undo.add(new ChangeAxisRanges<XTYPE>(this, Messages.Pan_Y,
Arrays.asList(y_axis),
Arrays.asList(mouse_start_y_ranges.get(mouse_y_axis)),
Arrays.asList(y_axis.getValueRange()),
pre_pan_auto_scales, new_autoscales));
pre_pan_auto_scales = new Stack<Boolean>(); // Clear cache of autoscales
fireYAxisChange(y_axis);
mouse_mode = MouseMode.PAN;
}
else if (mouse_mode == MouseMode.PAN_PLOT)
{
mouseMove(e);
List<AxisRange<Double>> current_y_ranges = new ArrayList<>();
for (YAxisImpl<XTYPE> axis : y_axes)
current_y_ranges.add(axis.getValueRange());
List<Boolean> new_autoscales = Arrays.asList(new Boolean[y_axes.size()]);
Collections.fill(new_autoscales, Boolean.FALSE);
undo.add(new ChangeAxisRanges<XTYPE>(this, Messages.Pan,
x_axis, mouse_start_x_range, x_axis.getValueRange(),
y_axes, mouse_start_y_ranges, current_y_ranges, pre_pan_auto_scales, new_autoscales));
pre_pan_auto_scales = new Stack<Boolean>(); // Clear cache of autoscales
fireXAxisChange();
for (YAxisImpl<XTYPE> axis : y_axes)
fireYAxisChange(axis);
mouse_mode = MouseMode.PAN;
}
else if (mouse_mode == MouseMode.ZOOM_IN_X)
{ // X axis increases going _right_ just like mouse 'x' coordinate
if (Math.abs(start.x - current.x) > ZOOM_PIXEL_THRESHOLD)
{
int low = Math.min(start.x, current.x);
int high = Math.max(start.x, current.x);
final AxisRange<XTYPE> original_x_range = x_axis.getValueRange();
final AxisRange<XTYPE> new_x_range = new AxisRange<>(x_axis.getValue(low), x_axis.getValue(high));
undo.execute(new ChangeAxisRanges<XTYPE>(this, Messages.Zoom_In_X, x_axis, original_x_range, new_x_range));
}
mouse_mode = MouseMode.ZOOM_IN;
}
else if (mouse_mode == MouseMode.ZOOM_IN_Y)
{ // Mouse 'y' increases going _down_ the screen
if (Math.abs(start.y - current.y) > ZOOM_PIXEL_THRESHOLD)
{
final int high = Math.min(start.y, current.y);
final int low = Math.max(start.y, current.y);
final YAxisImpl<XTYPE> axis = y_axes.get(mouse_y_axis);
undo.execute(new ChangeAxisRanges<XTYPE>(this, Messages.Zoom_In_Y,
Arrays.asList(axis),
Arrays.asList(axis.getValueRange()),
Arrays.asList(new AxisRange<Double>(axis.getValue(low), axis.getValue(high))),
Arrays.asList(axis.isAutoscale()), Arrays.asList(Boolean.FALSE)));
}
mouse_mode = MouseMode.ZOOM_IN;
}
else if (mouse_mode == MouseMode.ZOOM_IN_PLOT)
{
if (Math.abs(start.x - current.x) > ZOOM_PIXEL_THRESHOLD ||
Math.abs(start.y - current.y) > ZOOM_PIXEL_THRESHOLD)
{ // X axis increases going _right_ just like mouse 'x' coordinate
int low = Math.min(start.x, current.x);
int high = Math.max(start.x, current.x);
final AxisRange<XTYPE> original_x_range = x_axis.getValueRange();
final AxisRange<XTYPE> new_x_range = new AxisRange<>(x_axis.getValue(low), x_axis.getValue(high));
// Mouse 'y' increases going _down_ the screen
final List<AxisRange<Double>> original_y_ranges = new ArrayList<>();
final List<AxisRange<Double>> new_y_ranges = new ArrayList<>();
high = Math.min(start.y, current.y);
low = Math.max(start.y, current.y);
for (YAxisImpl<XTYPE> axis : y_axes)
{
original_y_ranges.add(axis.getValueRange());
new_y_ranges.add(new AxisRange<Double>(axis.getValue(low), axis.getValue(high)));
}
undo.execute(new ChangeAxisRanges<XTYPE>(this, Messages.Zoom_In, x_axis, original_x_range, new_x_range, y_axes, original_y_ranges, new_y_ranges));
}
mouse_mode = MouseMode.ZOOM_IN;
}
}
/** MouseListener: {@inheritDoc} */
@Override
public void mouseDoubleClick(final MouseEvent e)
{
// NOP
}
/** MouseTrackListener: {@inheritDoc} */
@Override
public void mouseEnter(final MouseEvent e)
{
// NOP
}
/** MouseTrackListener: {@inheritDoc} */
@Override
public void mouseExit(final MouseEvent e)
{
deselectMouseAnnotation();
if (show_crosshair)
{
mouse_current = Optional.empty();
redraw();
}
}
/** MouseTrackListener: {@inheritDoc} */
@Override
public void mouseHover(final MouseEvent e)
{
// NOP
}
/** Stagger the range of axes */
public void stagger()
{
plot_processor.stagger();
}
/** Notify listeners */
public void fireXAxisChange()
{
for (RTPlotListener<XTYPE> listener : listeners)
listener.changedXAxis(x_axis);
}
/** Notify listeners */
public void fireYAxisChange(final YAxisImpl<XTYPE> axis)
{
for (RTPlotListener<XTYPE> listener : listeners)
listener.changedYAxis(axis);
}
/** Notify listeners */
private void fireAnnotationsChanged()
{
for (RTPlotListener<XTYPE> listener : listeners)
listener.changedAnnotations();
}
/** Notify listeners */
private void fireCursorsChanged()
{
for (RTPlotListener<XTYPE> listener : listeners)
listener.changedCursors();
}
/** Notify listeners */
public void fireToolbarChange(final boolean show)
{
for (RTPlotListener<XTYPE> listener : listeners)
listener.changedToolbar(show);
}
public void fireAutoScaleChange(YAxisImpl<XTYPE> axis)
{
for (RTPlotListener<XTYPE> listener : listeners)
listener.changedAutoScale(axis);
}
} |
package com.atlassian.webdriver.testing.rule;
import com.atlassian.webdriver.browsers.WebDriverBrowserAutoInstall;
import com.atlassian.webdriver.utils.WebDriverUtil;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.Lists;
import net.jsourcerer.webdriver.jserrorcollector.JavaScriptError;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Rule to log javascript console error messages.
*
* At present, the logging only works in Firefox, since we use
* a Firefox extension to collect the console output.
*
* @since 2.3
*/
public class LogConsoleOutputRule extends TestWatcher
{
private static final Logger DEFAULT_LOGGER = LoggerFactory.getLogger(LogConsoleOutputRule.class);
private static final List<String> EMPTY_LIST = Lists.newArrayList();
private final Logger logger;
private final Supplier<? extends WebDriver> webDriver;
private boolean haveReadErrors = false;
private List<String> errorStrings = Lists.newArrayList();
@Inject
public LogConsoleOutputRule(WebDriver webDriver, Logger logger)
{
this(Suppliers.ofInstance(checkNotNull(webDriver, "webDriver")),logger);
}
public LogConsoleOutputRule(Supplier<? extends WebDriver> webDriver, Logger logger)
{
this.webDriver = checkNotNull(webDriver, "webDriver");
this.logger = checkNotNull(logger, "logger");
}
public LogConsoleOutputRule(Logger logger)
{
this(WebDriverBrowserAutoInstall.driverSupplier(), logger);
}
public LogConsoleOutputRule()
{
this(DEFAULT_LOGGER);
}
@Override
protected void starting(final Description description)
{
haveReadErrors = false;
}
@Override
@VisibleForTesting
public void finished(final Description description)
{
if (!isLogConsoleOutputEnabled())
{
return;
}
if (supportsConsoleOutput())
{
logger.info("
if (errors().size() > 0)
{
logger.info("
logger.info("
if (shouldFailOnJavaScriptErrors())
{
throw new RuntimeException("Test failed due to javascript errors being detected: " + errors());
}
}
}
else
{
logger.info("<Console output only supported in Firefox right now, sorry!>");
}
}
@VisibleForTesting
public String getConsoleOutput()
{
final StringBuilder sb = new StringBuilder();
for (String error : errors())
{
sb.append(error);
sb.append("\n");
}
return sb.toString();
}
/**
* Get the console output from the browser.
*
* @return The result of invoking {@link JavaScriptError#toString} via a List.
*/
protected List<String> errors()
{
if (!haveReadErrors)
{
errorStrings = Lists.newArrayList();
if (supportsConsoleOutput())
{
final List<String> errorsToIgnore = errorsToIgnore();
final List<JavaScriptError> errors = JavaScriptError.readErrors(webDriver.get());
for (JavaScriptError error : errors)
{
if (errorsToIgnore.contains(error.getErrorMessage()))
{
if (logger.isDebugEnabled())
{
logger.debug("Ignoring JS error: {0}", error);
}
}
else
{
errorStrings.add(error.toString());
}
}
}
haveReadErrors = true;
}
return errorStrings;
}
/**
* An overridable method which provides a list of error messages
* that should be ignored when collecting messages from the console.
*
* @return a list of exact error message strings to be ignored.
*/
protected List<String> errorsToIgnore()
{
return EMPTY_LIST;
}
/**
* An overridable method which when returning true will cause
* the rule to throw an exception, thus causing the test method
* to record a failure.
*
* @return true if the test method being wrapped should fail if a javascript error is found. Returns false by default.
*/
protected boolean shouldFailOnJavaScriptErrors()
{
return false;
}
private boolean supportsConsoleOutput()
{
return WebDriverUtil.isInstance(webDriver.get(), FirefoxDriver.class);
}
private boolean isLogConsoleOutputEnabled()
{
return true;
}
} |
package org.jboss.as.clustering.infinispan.subsystem;
import static org.jboss.as.clustering.infinispan.subsystem.CacheResourceDefinition.Capability.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.transaction.xa.XAResource;
import org.infinispan.Cache;
import org.jboss.as.controller.PathAddress;
import org.jboss.as.txn.service.TxnServices;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.value.InjectedValue;
import org.jboss.tm.XAResourceRecovery;
import org.jboss.tm.XAResourceRecoveryRegistry;
import org.wildfly.clustering.service.Builder;
import org.wildfly.clustering.service.SuppliedValueService;
/**
* Builder for a {@link XAResourceRecovery} registration.
* @author Paul Ferraro
*/
public class XAResourceRecoveryBuilder implements Builder<XAResourceRecovery> {
@SuppressWarnings("rawtypes")
private final InjectedValue<Cache> cache = new InjectedValue<>();
private final InjectedValue<XAResourceRecoveryRegistry> registry = new InjectedValue<>();
private final PathAddress cacheAddress;
/**
* Constructs a new {@link XAResourceRecovery} builder.
*/
public XAResourceRecoveryBuilder(PathAddress cacheAddress) {
this.cacheAddress = cacheAddress;
}
@Override
public ServiceName getServiceName() {
return CACHE.getServiceName(this.cacheAddress).append("recovery");
}
@Override
public ServiceBuilder<XAResourceRecovery> build(ServiceTarget target) {
Supplier<XAResourceRecovery> supplier = () -> {
Cache<?, ?> cache = this.cache.getValue();
XAResourceRecovery recovery = cache.getCacheConfiguration().transaction().recovery().enabled() ? new InfinispanXAResourceRecovery(cache) : null;
if (recovery != null) {
this.registry.getValue().addXAResourceRecovery(recovery);
}
return recovery;
};
Consumer<XAResourceRecovery> destroyer = recovery -> {
if (recovery != null) {
this.registry.getValue().removeXAResourceRecovery(recovery);
}
};
Service<XAResourceRecovery> service = new SuppliedValueService<>(Function.identity(), supplier, destroyer);
return target.addService(this.getServiceName(), service)
.addDependency(TxnServices.JBOSS_TXN_ARJUNA_RECOVERY_MANAGER, XAResourceRecoveryRegistry.class, this.registry)
.addDependency(CACHE.getServiceName(this.cacheAddress), Cache.class, this.cache)
.setInitialMode(ServiceController.Mode.PASSIVE);
}
private static class InfinispanXAResourceRecovery implements XAResourceRecovery {
private final Cache<?, ?> cache;
InfinispanXAResourceRecovery(Cache<?, ?> cache) {
this.cache = cache;
}
@Override
public XAResource[] getXAResources() {
return new XAResource[] { this.cache.getAdvancedCache().getXAResource() };
}
@Override
public int hashCode() {
return this.cache.getCacheManager().getCacheManagerConfiguration().globalJmxStatistics().cacheManagerName().hashCode() ^ this.cache.getName().hashCode();
}
@Override
public boolean equals(Object object) {
if ((object == null) || !(object instanceof InfinispanXAResourceRecovery)) return false;
InfinispanXAResourceRecovery recovery = (InfinispanXAResourceRecovery) object;
return this.cache.getCacheManager().getCacheManagerConfiguration().globalJmxStatistics().cacheManagerName().equals(recovery.cache.getCacheManager().getCacheManagerConfiguration().globalJmxStatistics().cacheManagerName()) && this.cache.getName().equals(recovery.cache.getName());
}
@Override
public String toString() {
return this.cache.getCacheManager().getCacheManagerConfiguration().globalJmxStatistics().cacheManagerName() + "." + this.cache.getName();
}
}
} |
package io.cattle.platform.servicediscovery.upgrade.impl;
import static io.cattle.platform.core.model.tables.ServiceExposeMapTable.*;
import io.cattle.platform.activity.ActivityLog;
import io.cattle.platform.activity.ActivityService;
import io.cattle.platform.core.addon.InServiceUpgradeStrategy;
import io.cattle.platform.core.addon.RollingRestartStrategy;
import io.cattle.platform.core.addon.ServiceRestart;
import io.cattle.platform.core.addon.ServiceUpgradeStrategy;
import io.cattle.platform.core.addon.ToServiceUpgradeStrategy;
import io.cattle.platform.core.constants.CommonStatesConstants;
import io.cattle.platform.core.constants.HealthcheckConstants;
import io.cattle.platform.core.constants.InstanceConstants;
import io.cattle.platform.core.constants.ServiceConstants;
import io.cattle.platform.core.model.Instance;
import io.cattle.platform.core.model.Service;
import io.cattle.platform.core.model.ServiceExposeMap;
import io.cattle.platform.engine.process.ExitReason;
import io.cattle.platform.engine.process.impl.ProcessCancelException;
import io.cattle.platform.engine.process.impl.ProcessExecutionExitException;
import io.cattle.platform.json.JsonMapper;
import io.cattle.platform.lock.LockCallbackNoReturn;
import io.cattle.platform.lock.LockManager;
import io.cattle.platform.object.ObjectManager;
import io.cattle.platform.object.process.ObjectProcessManager;
import io.cattle.platform.object.resource.ResourceMonitor;
import io.cattle.platform.object.resource.ResourcePredicate;
import io.cattle.platform.object.util.DataAccessor;
import io.cattle.platform.process.common.util.ProcessUtils;
import io.cattle.platform.servicediscovery.api.dao.ServiceExposeMapDao;
import io.cattle.platform.servicediscovery.deployment.DeploymentManager;
import io.cattle.platform.servicediscovery.deployment.impl.lock.ServiceLock;
import io.cattle.platform.servicediscovery.service.ServiceDiscoveryService;
import io.cattle.platform.servicediscovery.upgrade.UpgradeManager;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
public class UpgradeManagerImpl implements UpgradeManager {
private enum Type {
ToUpgrade,
ToCleanup,
UpgradedUnmanaged,
}
@Inject
ServiceExposeMapDao exposeMapDao;
@Inject
ObjectManager objectManager;
@Inject
DeploymentManager deploymentMgr;
@Inject
LockManager lockManager;
@Inject
ObjectProcessManager objectProcessMgr;
@Inject
ResourceMonitor resourceMntr;
@Inject
ServiceDiscoveryService serviceDiscoveryService;
@Inject
JsonMapper jsonMapper;
@Inject
ActivityService activityService;
private static final long SLEEP = 1000L;
protected void setUpgrade(ServiceExposeMap map, boolean upgrade) {
if (upgrade) {
map.setUpgrade(true);
map.setManaged(false);
} else {
map.setUpgrade(false);
map.setManaged(true);
}
objectManager.persist(map);
}
public boolean doInServiceUpgrade(Service service, InServiceUpgradeStrategy strategy, boolean isUpgrade, String currentProcess) {
long batchSize = strategy.getBatchSize();
boolean startFirst = strategy.getStartFirst();
Map<String, List<Instance>> deploymentUnitInstancesToUpgrade = formDeploymentUnitsForUpgrade(service,
Type.ToUpgrade, isUpgrade, strategy);
Map<String, List<Instance>> deploymentUnitInstancesUpgradedUnmanaged = formDeploymentUnitsForUpgrade(
service,
Type.UpgradedUnmanaged, isUpgrade, strategy);
Map<String, List<Instance>> deploymentUnitInstancesToCleanup = formDeploymentUnitsForUpgrade(service,
Type.ToCleanup, isUpgrade, strategy);
// upgrade deployment units
upgradeDeploymentUnits(service, deploymentUnitInstancesToUpgrade, deploymentUnitInstancesUpgradedUnmanaged,
deploymentUnitInstancesToCleanup,
batchSize, startFirst, preseveDeploymentUnit(service, strategy), isUpgrade, currentProcess, strategy);
// check if empty
if (deploymentUnitInstancesToUpgrade.isEmpty()) {
deploymentMgr.activate(service);
return true;
}
return false;
}
protected boolean preseveDeploymentUnit(Service service, InServiceUpgradeStrategy strategy) {
boolean isServiceIndexDUStrategy = StringUtils.equalsIgnoreCase(
ServiceConstants.SERVICE_INDEX_DU_STRATEGY,
DataAccessor.fieldString(service, ServiceConstants.FIELD_SERVICE_INDEX_STRATEGY));
return isServiceIndexDUStrategy || !strategy.isFullUpgrade();
}
protected void upgradeDeploymentUnits(final Service service,
final Map<String, List<Instance>> deploymentUnitInstancesToUpgrade,
final Map<String, List<Instance>> deploymentUnitInstancesUpgradedUnmanaged,
final Map<String, List<Instance>> deploymentUnitInstancesToCleanup,
final long batchSize,
final boolean startFirst, final boolean preseveDeploymentUnit, final boolean isUpgrade,
final String currentProcess, final InServiceUpgradeStrategy strategy) {
// hold the lock so service.reconcile triggered by config.update
// (in turn triggered by instance.remove) won't interfere
lockManager.lock(new ServiceLock(service), new LockCallbackNoReturn() {
@Override
public void doWithLockNoResult() {
// wait for healthy only for upgrade
// should be skipped for rollback
if (isUpgrade) {
deploymentMgr.activate(service);
waitForHealthyState(service, currentProcess, strategy);
}
// mark for upgrade
markForUpgrade(batchSize);
if (startFirst) {
// 1. reconcile to start new instances
activate(service);
if (isUpgrade) {
waitForHealthyState(service, currentProcess, strategy);
}
// 2. stop instances
stopInstances(service, deploymentUnitInstancesToCleanup);
} else {
// reverse order
// 1. stop instances
stopInstances(service, deploymentUnitInstancesToCleanup);
// 2. wait for reconcile (new instances will be started along)
activate(service);
}
}
protected void markForUpgrade(final long batchSize) {
markForCleanup(batchSize, preseveDeploymentUnit);
}
protected void markForCleanup(final long batchSize,
boolean preseveDeploymentUnit) {
long i = 0;
Iterator<Map.Entry<String, List<Instance>>> it = deploymentUnitInstancesToUpgrade.entrySet()
.iterator();
while (it.hasNext() && i < batchSize) {
Map.Entry<String, List<Instance>> instances = it.next();
String deploymentUnitUUID = instances.getKey();
markForRollback(deploymentUnitUUID);
for (Instance instance : instances.getValue()) {
activityService.instance(instance, "mark.upgrade", "Mark for upgrade", ActivityLog.INFO);
ServiceExposeMap map = objectManager.findAny(ServiceExposeMap.class,
SERVICE_EXPOSE_MAP.INSTANCE_ID, instance.getId());
setUpgrade(map, true);
}
deploymentUnitInstancesToCleanup.put(deploymentUnitUUID, instances.getValue());
it.remove();
i++;
}
}
protected void markForRollback(String deploymentUnitUUIDToRollback) {
List<Instance> instances = new ArrayList<>();
if (preseveDeploymentUnit) {
instances = deploymentUnitInstancesUpgradedUnmanaged.get(deploymentUnitUUIDToRollback);
} else {
// when preserveDeploymentunit == false, we don't care what deployment unit needs to be rolled back
String toExtract = null;
for (String key : deploymentUnitInstancesUpgradedUnmanaged.keySet()) {
if (toExtract != null) {
break;
}
toExtract = key;
}
instances = deploymentUnitInstancesUpgradedUnmanaged.get(toExtract);
deploymentUnitInstancesUpgradedUnmanaged.remove(toExtract);
}
if (instances != null) {
for (Instance instance : instances) {
ServiceExposeMap map = objectManager.findAny(ServiceExposeMap.class,
SERVICE_EXPOSE_MAP.INSTANCE_ID, instance.getId());
setUpgrade(map, false);
}
}
}
});
}
protected Map<String, List<Instance>> formDeploymentUnitsForUpgrade(Service service, Type type, boolean isUpgrade,
InServiceUpgradeStrategy strategy) {
Map<String, Pair<String, Map<String, Object>>> preUpgradeLaunchConfigNamesToVersion = new HashMap<>();
Map<String, Pair<String, Map<String, Object>>> postUpgradeLaunchConfigNamesToVersion = new HashMap<>();
// getting an original config set (to cover the scenario when config could be removed along with the upgrade)
if (isUpgrade) {
postUpgradeLaunchConfigNamesToVersion.putAll(strategy.getNameToVersionToConfig(service.getName(), false));
preUpgradeLaunchConfigNamesToVersion.putAll(strategy.getNameToVersionToConfig(service.getName(), true));
} else {
postUpgradeLaunchConfigNamesToVersion.putAll(strategy.getNameToVersionToConfig(service.getName(), true));
preUpgradeLaunchConfigNamesToVersion.putAll(strategy.getNameToVersionToConfig(service.getName(), false));
}
Map<String, List<Instance>> deploymentUnitInstances = new HashMap<>();
// iterate over pre-upgraded state
// get desired version from post upgrade state
if (type == Type.UpgradedUnmanaged) {
for (String launchConfigName : postUpgradeLaunchConfigNamesToVersion.keySet()) {
List<Instance> instances = new ArrayList<>();
Pair<String, Map<String, Object>> post = postUpgradeLaunchConfigNamesToVersion.get(launchConfigName);
String toVersion = post.getLeft();
instances.addAll(exposeMapDao.getUpgradedInstances(service,
launchConfigName, toVersion, false));
for (Instance instance : instances) {
addInstanceToDeploymentUnits(deploymentUnitInstances, instance);
}
}
} else {
for (String launchConfigName : preUpgradeLaunchConfigNamesToVersion.keySet()) {
String toVersion = "undefined";
Pair<String, Map<String, Object>> post = postUpgradeLaunchConfigNamesToVersion.get(launchConfigName);
if (post != null) {
toVersion = post.getLeft();
}
List<Instance> instances = new ArrayList<>();
if (type == Type.ToUpgrade) {
instances.addAll(exposeMapDao.getInstancesToUpgrade(service, launchConfigName, toVersion));
} else if (type == Type.ToCleanup) {
instances.addAll(exposeMapDao.getInstancesToCleanup(service, launchConfigName, toVersion));
}
for (Instance instance : instances) {
addInstanceToDeploymentUnits(deploymentUnitInstances, instance);
}
}
}
return deploymentUnitInstances;
}
protected Map<String, List<Instance>> formDeploymentUnitsForRestart(Service service) {
Map<String, List<Instance>> deploymentUnitInstances = new HashMap<>();
List<? extends Instance> instances = getServiceInstancesToRestart(service);
for (Instance instance : instances) {
addInstanceToDeploymentUnits(deploymentUnitInstances, instance);
}
return deploymentUnitInstances;
}
protected List<? extends Instance> getServiceInstancesToRestart(Service service) {
// get all instances of the service
List<? extends Instance> instances = exposeMapDao.listServiceManagedInstances(service);
List<Instance> toRestart = new ArrayList<>();
ServiceRestart svcRestart = DataAccessor.field(service, ServiceConstants.FIELD_RESTART,
jsonMapper, ServiceRestart.class);
RollingRestartStrategy strategy = svcRestart.getRollingRestartStrategy();
Map<Long, Long> instanceToStartCount = strategy.getInstanceToStartCount();
// compare its start_count with one set on the service restart field
for (Instance instance : instances) {
if (instanceToStartCount.containsKey(instance.getId())) {
Long previousStartCount = instanceToStartCount.get(instance.getId());
if (previousStartCount == instance.getStartCount()) {
toRestart.add(instance);
}
}
}
return toRestart;
}
protected void addInstanceToDeploymentUnits(Map<String, List<Instance>> deploymentUnitInstancesToUpgrade,
Instance instance) {
List<Instance> toRemove = deploymentUnitInstancesToUpgrade.get(instance.getDeploymentUnitUuid());
if (toRemove == null) {
toRemove = new ArrayList<Instance>();
}
toRemove.add(instance);
deploymentUnitInstancesToUpgrade.put(instance.getDeploymentUnitUuid(), toRemove);
}
@Override
public void upgrade(Service service, io.cattle.platform.core.addon.ServiceUpgradeStrategy strategy, String currentProcess) {
if (strategy instanceof ToServiceUpgradeStrategy) {
ToServiceUpgradeStrategy toServiceStrategy = (ToServiceUpgradeStrategy) strategy;
Service toService = objectManager.loadResource(Service.class, toServiceStrategy.getToServiceId());
if (toService == null || toService.getRemoved() != null) {
return;
}
updateLinks(service, toServiceStrategy);
}
while (!doUpgrade(service, strategy, currentProcess)) {
sleep(service, strategy, currentProcess);
}
}
@Override
public void rollback(Service service, ServiceUpgradeStrategy strategy) {
if (strategy instanceof ToServiceUpgradeStrategy) {
return;
}
while (!doInServiceUpgrade(service, (InServiceUpgradeStrategy) strategy, false,
ServiceConstants.STATE_ROLLINGBACK)) {
sleep(service, strategy, ServiceConstants.STATE_ROLLINGBACK);
}
}
public boolean doUpgrade(Service service, io.cattle.platform.core.addon.ServiceUpgradeStrategy strategy,
String currentProcess) {
if (strategy instanceof InServiceUpgradeStrategy) {
InServiceUpgradeStrategy inService = (InServiceUpgradeStrategy) strategy;
return doInServiceUpgrade(service, inService, true, currentProcess);
} else {
ToServiceUpgradeStrategy toService = (ToServiceUpgradeStrategy) strategy;
return doToServiceUpgrade(service, toService, currentProcess);
}
}
protected void updateLinks(Service service, ToServiceUpgradeStrategy strategy) {
if (!strategy.isUpdateLinks()) {
return;
}
serviceDiscoveryService.cloneConsumingServices(service, objectManager.loadResource(Service.class,
strategy.getToServiceId()));
}
protected void sleep(final Service service, ServiceUpgradeStrategy strategy, final String currentProcess) {
final long interval = strategy.getIntervalMillis();
activityService.run(service, "sleep", String.format("Sleeping for %d seconds", interval/1000), new Runnable() {
@Override
public void run() {
for (int i = 0;; i++) {
final long sleepTime = Math.max(0, Math.min(SLEEP, interval - i * SLEEP));
if (sleepTime == 0) {
break;
} else {
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
stateCheck(service, currentProcess);
}
}
});
}
protected Service stateCheck(Service service, String currentProcess) {
service = objectManager.reload(service);
List<String> states = Arrays.asList(ServiceConstants.STATE_UPGRADING,
ServiceConstants.STATE_ROLLINGBACK, ServiceConstants.STATE_RESTARTING,
ServiceConstants.STATE_FINISHING_UPGRADE);
if (!states.contains(service.getState())) {
throw new ProcessExecutionExitException(ExitReason.STATE_CHANGED);
}
if (StringUtils.equals(currentProcess, ServiceConstants.STATE_RESTARTING)) {
return service;
}
// rollback should cancel upgarde, and vice versa
if (!StringUtils.equals(currentProcess, service.getState())) {
throw new ProcessExecutionExitException(ExitReason.STATE_CHANGED);
}
return service;
}
/**
* @param fromService
* @param strategy
* @return true if the upgrade is done
*/
protected boolean doToServiceUpgrade(Service fromService, ToServiceUpgradeStrategy strategy, String currentProcess) {
Service toService = objectManager.loadResource(Service.class, strategy.getToServiceId());
if (toService == null || toService.getRemoved() != null) {
return true;
}
deploymentMgr.activate(toService);
if (!deploymentMgr.isHealthy(toService)) {
return false;
}
deploymentMgr.activate(fromService);
fromService = objectManager.reload(fromService);
toService = objectManager.reload(toService);
long batchSize = strategy.getBatchSize();
long finalScale = strategy.getFinalScale();
long toScale = getScale(toService);
long totalScale = getScale(fromService) + toScale;
if (totalScale > finalScale) {
fromService = changeScale(fromService, 0 - Math.min(batchSize, totalScale - finalScale));
} else if (toScale < finalScale) {
long max = Math.min(batchSize, finalScale - toScale);
toService = changeScale(toService, Math.min(max, finalScale + batchSize - totalScale));
}
if (getScale(fromService) == 0 && getScale(toService) != finalScale) {
changeScale(toService, finalScale - getScale(toService));
}
return getScale(fromService) == 0 && getScale(toService) == finalScale;
}
protected Service changeScale(Service service, long delta) {
if (delta == 0) {
return service;
}
long newScale = Math.max(0, getScale(service) + delta);
service = objectManager.setFields(service, ServiceConstants.FIELD_SCALE, newScale);
deploymentMgr.activate(service);
return objectManager.reload(service);
}
protected int getScale(Service service) {
Integer i = DataAccessor.fieldInteger(service, ServiceConstants.FIELD_SCALE);
return i == null ? 0 : i;
}
@Override
public void finishUpgrade(Service service, boolean reconcile) {
// cleanup instances set for upgrade
cleanupUpgradedInstances(service);
// reconcile
if (reconcile) {
deploymentMgr.activate(service);
}
}
protected void waitForHealthyState(final Service service, final String currentProcess,
final InServiceUpgradeStrategy strategy) {
activityService.run(service, "wait", "Waiting for all instances to be healthy", new Runnable() {
@Override
public void run() {
final List<String> healthyStates = Arrays.asList(HealthcheckConstants.HEALTH_STATE_HEALTHY,
HealthcheckConstants.HEALTH_STATE_UPDATING_HEALTHY);
List<? extends Instance> instancesToCheck = getInstancesToCheckForHealth(service, strategy);
for (final Instance instance : instancesToCheck) {
if (instance.getState().equalsIgnoreCase(InstanceConstants.STATE_RUNNING)) {
resourceMntr.waitFor(instance,
new ResourcePredicate<Instance>() {
@Override
public boolean evaluate(Instance obj) {
boolean healthy = instance.getHealthState() == null
|| healthyStates.contains(obj.getHealthState());
if (!healthy) {
stateCheck(service, currentProcess);
}
return healthy;
}
@Override
public String getMessage() {
return "healthy";
}
});
}
}
}
});
}
private List<? extends Instance> getInstancesToCheckForHealth(Service service,
InServiceUpgradeStrategy strategy) {
if (strategy == null) {
return exposeMapDao.listServiceManagedInstances(service);
}
Map<String, String> lcToCurrentV = getLaunchConfigToCurrentVersion(service, strategy);
List<Instance> filtered = new ArrayList<>();
// only check upgraded instances for health
for (String lc : lcToCurrentV.keySet()) {
List<? extends Instance> instances = exposeMapDao.listServiceManagedInstances(service, lc);
for (Instance instance : instances) {
if (instance.getVersion() != null &&
instance.getVersion().equalsIgnoreCase(lcToCurrentV.get(lc))) {
filtered.add(instance);
}
}
}
return filtered;
}
private Map<String, String> getLaunchConfigToCurrentVersion(Service service, InServiceUpgradeStrategy strategy) {
Map<String, String> lcToV = new HashMap<>();
Map<String, Pair<String, Map<String, Object>>> vToC = strategy.getNameToVersionToConfig(service.getName(),
false);
for (String lc : vToC.keySet()) {
lcToV.put(lc, vToC.get(lc).getLeft());
}
return lcToV;
}
public void cleanupUpgradedInstances(Service service) {
List<? extends ServiceExposeMap> maps = exposeMapDao.getInstancesSetForUpgrade(service.getId());
List<Instance> waitList = new ArrayList<>();
for (ServiceExposeMap map : maps) {
Instance instance = objectManager.loadResource(Instance.class, map.getInstanceId());
if (instance == null || instance.getRemoved() != null || instance.getState().equals(
CommonStatesConstants.REMOVING)) {
continue;
}
try {
objectProcessMgr.scheduleProcessInstanceAsync(InstanceConstants.PROCESS_REMOVE,
instance, null);
} catch (ProcessCancelException ex) {
// in case instance was manually restarted
objectProcessMgr.scheduleProcessInstanceAsync(InstanceConstants.PROCESS_STOP,
instance, ProcessUtils.chainInData(new HashMap<String, Object>(),
InstanceConstants.PROCESS_STOP, InstanceConstants.PROCESS_REMOVE));
}
}
for (Instance instance : waitList) {
resourceMntr.waitForState(instance, CommonStatesConstants.REMOVED);
}
}
@Override
public void restart(Service service, RollingRestartStrategy strategy) {
Map<String, List<Instance>> toRestart = formDeploymentUnitsForRestart(service);
while (!doRestart(service, strategy, toRestart)) {
sleep(service, strategy, ServiceConstants.STATE_RESTARTING);
}
}
public boolean doRestart(Service service, RollingRestartStrategy strategy,
Map<String, List<Instance>> toRestart) {
long batchSize = strategy.getBatchSize();
final Map<String, List<Instance>> restartBatch = new HashMap<>();
long i = 0;
Iterator<Map.Entry<String, List<Instance>>> it = toRestart.entrySet()
.iterator();
while (it.hasNext() && i < batchSize) {
Map.Entry<String, List<Instance>> instances = it.next();
String deploymentUnitUUID = instances.getKey();
restartBatch.put(deploymentUnitUUID, instances.getValue());
it.remove();
i++;
}
restartDeploymentUnits(service, restartBatch);
if (toRestart.isEmpty()) {
return true;
}
return false;
}
protected void restartDeploymentUnits(final Service service,
final Map<String, List<Instance>> deploymentUnitsToStop) {
// hold the lock so service.reconcile triggered by config.update
// (in turn triggered by instance.remove) won't interfere
lockManager.lock(new ServiceLock(service), new LockCallbackNoReturn() {
@Override
public void doWithLockNoResult() {
// 1. Wait for the service instances to become healthy
waitForHealthyState(service, ServiceConstants.STATE_RESTARTING, null);
// 2. stop instances
stopInstances(service, deploymentUnitsToStop);
// 3. wait for reconcile (instances will be restarted along)
activate(service);
}
});
}
protected void activate(final Service service) {
activityService.run(service, "starting", "Starting new instances", new Runnable() {
@Override
public void run() {
deploymentMgr.activate(service);
}
});
}
protected void stopInstances(Service service, final Map<String, List<Instance>> deploymentUnitInstancesToStop) {
activityService.run(service, "stopping", "Stopping instances", new Runnable() {
@Override
public void run() {
List<Instance> toStop = new ArrayList<>();
List<Instance> toWait = new ArrayList<>();
for (String key : deploymentUnitInstancesToStop.keySet()) {
toStop.addAll(deploymentUnitInstancesToStop.get(key));
}
for (Instance instance : toStop) {
instance = resourceMntr.waitForNotTransitioning(instance);
if (InstanceConstants.STATE_ERROR.equals(instance.getState())) {
objectProcessMgr.scheduleProcessInstanceAsync(InstanceConstants.PROCESS_REMOVE,
instance, null);
} else if (!instance.getState().equalsIgnoreCase(InstanceConstants.STATE_STOPPED)) {
objectProcessMgr.scheduleProcessInstanceAsync(InstanceConstants.PROCESS_STOP,
instance, null);
toWait.add(instance);
}
}
for (Instance instance : toWait) {
resourceMntr.waitForState(instance, InstanceConstants.STATE_STOPPED);
}
}
});
}
} |
package edu.kit.iti.formal.pse.worthwhile.validation;
import org.antlr.runtime.EarlyExitException;
import org.antlr.runtime.NoViableAltException;
import org.eclipse.xtext.nodemodel.SyntaxErrorMessage;
import org.eclipse.xtext.parser.antlr.SyntaxErrorMessageProvider;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Program;
/**
* This class provides the correct syntax error messages.
*
* @author matthias
*
*/
public class WorthwhileSyntaxErrorMessageProvider extends SyntaxErrorMessageProvider {
/**
* Error code for "No newline at end of file".
*/
public static final String NO_NEWLINE_AT_EOF = "NoNewlineAtEOF";
/**
* Error code for "No return type specified for function".
*/
public static final String NO_FUNCTION_RETURN_TYPE = "NoFunctionReturnType";
/**
* Returns a syntax error messages for the context.
*
* @param context
* the context from which you want the error message
*
* @return the syntax error message
*/
@Override
public final SyntaxErrorMessage getSyntaxErrorMessage(final IParserErrorContext context) {
if (context.getRecognitionException() instanceof EarlyExitException) {
if (context.getCurrentNode().getRootNode().getTotalEndLine() == context.getCurrentNode()
.getEndLine()) {
return new SyntaxErrorMessage("Newline is missing", NO_NEWLINE_AT_EOF);
} else {
return new SyntaxErrorMessage("Delete this token.", "deleteToken");
}
} else if (context.getRecognitionException() instanceof NoViableAltException
&& context.getCurrentContext() instanceof Program) {
return new SyntaxErrorMessage("Return type of function is missing", NO_FUNCTION_RETURN_TYPE);
}
return super.getSyntaxErrorMessage(context);
}
} |
package org.jtalks.jcommune.web.controller;
import org.jtalks.jcommune.service.TopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
/**
* Delete post controller. This controller handle delete post user actions.
* Before user could delete some post he should pass though delete confirmation.
* After user confirm delete action post would be removed by {@code TopicService}
* @author Osadchuck Eugeny
* @author Kravchenko Vitaliy
*/
@Controller
public class DeletePostController {
private final TopicService topicService;
@Autowired
public DeletePostController(TopicService topicService) {
this.topicService = topicService;
}
/**
* Redirect user to confirmation page.
* @param topicId - topic id, this in topic which contains post which should be deleted
* @param postId - post id to delete
* @return - return ModelAndView with to parameter topicId and postId
*/
@RequestMapping(method = RequestMethod.GET, value = "/branch/{branchId}/topic/{topicId}/deletePost")
public ModelAndView confirm(@RequestParam("topicId") Long topicId, @RequestParam("postId") Long postId,
@PathVariable("branchId") long branchId){
ModelAndView mav = new ModelAndView("deletePost");
mav.addObject("topicId", topicId);
mav.addObject("postId", postId);
mav.addObject("branchId", branchId);
return mav;
}
/**
* Handle delete action. User confirm post deletion.
* @param topicId - topic id, this in topic which contains post which should be deleted
* also used for redirection back to topic.
* @param postId - post
* @return - redirect to /topics/topicId.
*/
@RequestMapping(method = RequestMethod.DELETE, value = "/branch/{branchId}/topic/{topicId}/deletePost")
public ModelAndView delete(@RequestParam("topicId") Long topicId, @RequestParam("postId") Long postId,
@PathVariable("branchId") long branchId){
topicService.deletePost(topicId, postId);
return new ModelAndView("redirect:/branch/"+ branchId + "/topic/" + topicId + ".html");
}
} |
package io.subutai.core.plugincommon.impl;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import io.subutai.common.security.objects.PermissionObject;
import io.subutai.common.security.objects.PermissionOperation;
import io.subutai.common.security.objects.PermissionScope;
import io.subutai.common.util.ServiceLocator;
import io.subutai.core.identity.api.IdentityManager;
import io.subutai.core.identity.api.model.User;
import io.subutai.core.plugincommon.model.ClusterDataEntity;
public class PluginDataService
{
private EntityManagerFactory emf;
private Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().disableHtmlEscaping().create();
private static final Logger LOG = LoggerFactory.getLogger( PluginDataService.class );
private IdentityManager identityManager;
public PluginDataService( final EntityManagerFactory emf ) throws SQLException
{
init();
this.emf = emf;
try
{
this.emf.createEntityManager().close();
}
catch ( Exception e )
{
throw new SQLException( e );
}
}
public PluginDataService( final EntityManagerFactory emf, final GsonBuilder gsonBuilder )
{
Preconditions.checkNotNull( emf, "EntityManagerFactory cannot be null." );
Preconditions.checkNotNull( gsonBuilder, "GsonBuilder cannot be null." );
init();
this.emf = emf;
gson = gsonBuilder.setPrettyPrinting().disableHtmlEscaping().create();
}
public void init()
{
ServiceLocator serviceLocator = new ServiceLocator();
identityManager = serviceLocator.getService( IdentityManager.class );
} |
package org.eclipse.birt.report.model.adapter.oda.impl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.eclipse.birt.report.model.adapter.oda.IODADesignFactory;
import org.eclipse.birt.report.model.adapter.oda.ODADesignFactory;
import org.eclipse.birt.report.model.adapter.oda.util.IdentifierUtility;
import org.eclipse.birt.report.model.api.ColumnHintHandle;
import org.eclipse.birt.report.model.api.ComputedColumnHandle;
import org.eclipse.birt.report.model.api.OdaDataSetHandle;
import org.eclipse.birt.report.model.api.OdaResultSetColumnHandle;
import org.eclipse.birt.report.model.api.ResultSetColumnHandle;
import org.eclipse.birt.report.model.api.StructureFactory;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.core.IStructure;
import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants;
import org.eclipse.birt.report.model.api.elements.structures.ColumnHint;
import org.eclipse.birt.report.model.api.elements.structures.FormatValue;
import org.eclipse.birt.report.model.api.elements.structures.OdaResultSetColumn;
import org.eclipse.birt.report.model.api.util.StringUtil;
import org.eclipse.datatools.connectivity.oda.design.AxisAttributes;
import org.eclipse.datatools.connectivity.oda.design.AxisType;
import org.eclipse.datatools.connectivity.oda.design.ColumnDefinition;
import org.eclipse.datatools.connectivity.oda.design.DataElementAttributes;
import org.eclipse.datatools.connectivity.oda.design.DataElementIdentifiers;
import org.eclipse.datatools.connectivity.oda.design.DataElementUIHints;
import org.eclipse.datatools.connectivity.oda.design.DataSetDesign;
import org.eclipse.datatools.connectivity.oda.design.HorizontalAlignment;
import org.eclipse.datatools.connectivity.oda.design.OutputElementAttributes;
import org.eclipse.datatools.connectivity.oda.design.ResultSetColumns;
import org.eclipse.datatools.connectivity.oda.design.ResultSetDefinition;
import org.eclipse.datatools.connectivity.oda.design.ResultSets;
import org.eclipse.datatools.connectivity.oda.design.ResultSubset;
import org.eclipse.datatools.connectivity.oda.design.TextWrapType;
import org.eclipse.datatools.connectivity.oda.design.ValueFormatHints;
import org.eclipse.emf.common.util.EList;
/**
* The utility class that converts between ROM ResultSets and ODA ODA
* ResultSetDefinition.
*
* @see OdaDataSetHandle
* @see ResultSetDefinition
*/
class ResultSetsAdapter
{
/**
* The data set handle.
*/
private final OdaDataSetHandle setHandle;
/**
* The data set design.
*/
private final DataSetDesign setDesign;
/**
* The data set handle defined parameters.
*/
private List setDefinedResults = null;
/**
* The data set handle defined parameters.
*/
private List setDefinedColumnHints = null;
/**
* Column hints for computed columns.
*/
private List<IStructure> columnHintsForComputedColumns = null;
private final IODADesignFactory designFactory;
private final ResultSetCriteriaAdapter filterAdapter;
/**
* The constructor.
*
* @param setHandle
* the data set handle
* @param setDesign
* the data set design
*
*/
ResultSetsAdapter( OdaDataSetHandle setHandle, DataSetDesign setDesign )
{
this.setHandle = setHandle;
this.setDesign = setDesign;
filterAdapter = new ResultSetCriteriaAdapter( setHandle, setDesign );
Iterator tmpIterator = setHandle.resultSetIterator( );
setDefinedResults = new ArrayList( );
while ( tmpIterator.hasNext( ) )
setDefinedResults.add( tmpIterator.next( ) );
tmpIterator = setHandle.columnHintsIterator( );
setDefinedColumnHints = new ArrayList( );
while ( tmpIterator.hasNext( ) )
setDefinedColumnHints.add( tmpIterator.next( ) );
designFactory = ODADesignFactory.getFactory( );
}
/**
* Creates the column hint with given column definition and the old column
* hint.
*
* @param columnDefn
* the latest column definition
* @param cachedColumnDefn
* the last (cached) column definition
* @param oldHint
* the existing column hint in the data set handle
* @return the newly created column hint
*/
static ColumnHint newROMColumnHintFromColumnDefinition(
ColumnDefinition columnDefn, ColumnDefinition cachedColumnDefn,
ColumnHint oldHint, OdaResultSetColumn resultSetColumn )
{
if ( columnDefn == null )
return null;
String columnName = resultSetColumn == null ? null : resultSetColumn
.getColumnName( );
DataElementAttributes dataAttrs = columnDefn.getAttributes( );
if ( dataAttrs == null )
return null;
ColumnHint newHint = null;
ColumnDefinition tmpCachedColumnDefn = cachedColumnDefn;
if ( oldHint == null )
{
newHint = StructureFactory.createColumnHint( );
tmpCachedColumnDefn = null;
}
else
newHint = (ColumnHint) oldHint.copy( );
DataElementUIHints dataUIHints = dataAttrs.getUiHints( );
OutputElementAttributes outputAttrs = columnDefn.getUsageHints( );
AxisAttributes axisAttrs = columnDefn.getMultiDimensionAttributes( );
boolean hasValue = hasColumnHintValue( dataUIHints, outputAttrs,
axisAttrs );
if ( !hasValue )
{
if ( oldHint == null )
return null;
return newHint;
}
DataElementAttributes cachedDataAttrs = tmpCachedColumnDefn == null
? null
: tmpCachedColumnDefn.getAttributes( );
updateColumnHintFromDataAttrs( columnDefn.getAttributes( ),
cachedDataAttrs, newHint );
updateColumnHintFromUsageHints(
outputAttrs,
tmpCachedColumnDefn == null ? null : tmpCachedColumnDefn
.getUsageHints( ), newHint, resultSetColumn );
updateColumnHintFromAxisAttrs(
columnDefn.getMultiDimensionAttributes( ),
tmpCachedColumnDefn == null ? null : tmpCachedColumnDefn
.getMultiDimensionAttributes( ), newHint );
if ( StringUtil.isBlank( (String) newHint.getProperty( null,
ColumnHint.COLUMN_NAME_MEMBER ) ) )
{
newHint.setProperty( ColumnHint.COLUMN_NAME_MEMBER, columnName );
}
return newHint;
}
/**
* Checks whether there are values for newly created column hint.
*
* @param dataUIHints
* the latest data ui hints
* @param outputAttrs
* the latest output element attributes
* @return <code>true</code> if no column hint value is set. Otherwise
* <code>false</code>.
*/
private static boolean hasColumnHintValue( DataElementUIHints dataUIHints,
OutputElementAttributes outputAttrs, AxisAttributes axisAttrs )
{
if ( dataUIHints == null && outputAttrs == null && axisAttrs == null )
return false;
boolean isValueSet = false;
if ( dataUIHints != null )
{
if ( dataUIHints.getDisplayName( ) != null )
isValueSet = true;
}
if ( !isValueSet && outputAttrs != null )
{
if ( outputAttrs.getHelpText( ) != null )
isValueSet = true;
if ( !isValueSet )
{
ValueFormatHints formatHints = outputAttrs.getFormattingHints( );
if ( formatHints != null )
isValueSet = true;
}
}
if ( !isValueSet && axisAttrs != null )
{
isValueSet = axisAttrs.isSetAxisType( );
if ( !isValueSet )
{
isValueSet = axisAttrs.isSetOnColumnLayout( );
}
}
return isValueSet;
}
/**
* Updates column hint values by given data element attributes.
*
* @param dataAttrs
* the latest data element attributes
* @param cachedDataAttrs
* the last(cached) data element attributes
* @param newHint
* the column hint
*/
private static void updateColumnHintFromDataAttrs(
DataElementAttributes dataAttrs,
DataElementAttributes cachedDataAttrs, ColumnHint newHint )
{
if ( dataAttrs == null )
return;
Object oldValue = cachedDataAttrs == null ? null : cachedDataAttrs
.getName( );
Object newValue = dataAttrs.getName( );
if ( !CompareUtil.isEquals( oldValue, newValue ) )
newHint.setProperty( ColumnHint.COLUMN_NAME_MEMBER, newValue );
DataElementUIHints dataUIHints = dataAttrs.getUiHints( );
if ( dataUIHints == null )
return;
DataElementUIHints cachedDataUIHints = cachedDataAttrs == null
? null
: cachedDataAttrs.getUiHints( );
oldValue = cachedDataUIHints == null ? null : cachedDataUIHints
.getDisplayName( );
newValue = dataUIHints.getDisplayName( );
if ( !CompareUtil.isEquals( oldValue, newValue ) )
{
newHint.setProperty( ColumnHint.DISPLAY_NAME_MEMBER, newValue );
}
oldValue = cachedDataUIHints == null ? null : cachedDataUIHints
.getDisplayNameKey( );
newValue = dataUIHints.getDisplayNameKey( );
if ( !CompareUtil.isEquals( oldValue, newValue ) )
{
newHint.setProperty( ColumnHint.DISPLAY_NAME_ID_MEMBER, newValue );
}
// description to description in data ui hints: not support now
/*
* oldValue = cachedDataUIHints == null ? null : cachedDataUIHints
* .getDescription( ); newValue = dataUIHints.getDescription( ); if (
* oldValue == null || !oldValue.equals( newValue ) ) {
* newHint.setProperty( ColumnHint.DESCRIPTION_MEMBER, newValue ); }
*
* oldValue = cachedDataUIHints == null ? null : cachedDataUIHints
* .getDescriptionKey( ); newValue = dataUIHints.getDescriptionKey( );
* if ( oldValue == null || !oldValue.equals( newValue ) ) {
* newHint.setProperty( ColumnHint.DESCRIPTION_ID_MEMBER, newValue ); }
*/
}
/**
* Updates column hint values by given output element attributes.
*
* @param outputAttrs
* the latest output element attributes
* @param cachedOutputAttrs
* the last(cached) output element attributes
* @param newHint
* the column hint
*/
private static void updateColumnHintFromUsageHints(
OutputElementAttributes outputAttrs,
OutputElementAttributes cachedOutputAttrs, ColumnHint newHint,
OdaResultSetColumn column )
{
if ( outputAttrs == null )
return;
// help text and key
Object oldValue = cachedOutputAttrs == null ? null : cachedOutputAttrs
.getHelpText( );
Object newValue = outputAttrs.getHelpText( );
if ( !CompareUtil.isEquals( oldValue, newValue ) )
{
newHint.setProperty( ColumnHint.HELP_TEXT_MEMBER, newValue );
}
oldValue = cachedOutputAttrs == null ? null : cachedOutputAttrs
.getHelpTextKey( );
newValue = outputAttrs.getHelpTextKey( );
if ( !CompareUtil.isEquals( oldValue, newValue ) )
{
newHint.setProperty( ColumnHint.HELP_TEXT_ID_MEMBER, newValue );
}
// m_label maps to heading
oldValue = cachedOutputAttrs == null ? null : cachedOutputAttrs
.getLabel( );
newValue = outputAttrs.getLabel( );
if ( !CompareUtil.isEquals( oldValue, newValue ) )
{
newHint.setProperty( ColumnHint.HEADING_MEMBER, newValue );
}
oldValue = cachedOutputAttrs == null ? null : cachedOutputAttrs
.getLabelKey( );
newValue = outputAttrs.getLabelKey( );
if ( !CompareUtil.isEquals( oldValue, newValue ) )
{
newHint.setProperty( ColumnHint.HEADING_ID_MEMBER, newValue );
}
// for values in formatting.
ValueFormatHints formatHints = outputAttrs.getFormattingHints( );
if ( formatHints == null )
return;
ValueFormatHints cachedFormatHints = cachedOutputAttrs == null
? null
: cachedOutputAttrs.getFormattingHints( );
oldValue = cachedFormatHints == null ? null : cachedFormatHints
.getDisplayFormat( );
// convert display format in oda to pattern part of value-format member
newValue = formatHints.getDisplayFormat( );
if ( !CompareUtil.isEquals( oldValue, newValue ) )
{
FormatValue format = (FormatValue) newHint.getProperty( null,
ColumnHint.VALUE_FORMAT_MEMBER );
if ( format == null && newValue != null )
{
format = StructureFactory.newFormatValue( );
newHint.setProperty( ColumnHint.VALUE_FORMAT_MEMBER, format );
}
// add logic to fix 32742: if the column is date-time, then do some
// special handle for the format string in IO
if ( newValue != null
&& ( column != null && DesignChoiceConstants.COLUMN_DATA_TYPE_DATETIME
.equals( column.getDataType( ) ) ) )
{
String formatValue = (String) newValue;
newValue = formatValue.replaceFirst( "mm/", "MM/" ); //$NON-NLS-1$//$NON-NLS-2$
}
if ( format != null )
format.setPattern( (String) newValue );
}
// not support display length
/*
* newValue = formatHints.getDisplaySize( ); oldValue =
* cachedFormatHints == null ? null : cachedFormatHints .getDisplaySize(
* ); if ( oldValue == null || !oldValue.equals( newValue ) ) {
* newHint.setProperty( ColumnHint.DISPLAY_LENGTH_MEMBER, newValue ); }
*/
newValue = formatHints.getHorizontalAlignment( );
oldValue = cachedFormatHints == null ? null : cachedFormatHints
.getHorizontalAlignment( );
if ( !CompareUtil.isEquals( oldValue, newValue ) )
{
newHint.setProperty(
ColumnHint.HORIZONTAL_ALIGN_MEMBER,
convertToROMHorizontalAlignment( (HorizontalAlignment) newValue ) );
}
// not support word-wrap
/*
* newValue = formatHints.getTextWrapType( ); oldValue =
* cachedFormatHints == null ? null : cachedFormatHints
* .getTextWrapType( );
*
* if ( oldValue == null || !oldValue.equals( newValue ) ) {
* newHint.setProperty( ColumnHint.WORD_WRAP_MEMBER,
* convertToROMWordWrap( (TextWrapType) newValue ) ); }
*/
// cannot handle text format since two objects in ODA and ROM are
// different.
}
static String convertToROMHorizontalAlignment( HorizontalAlignment tmpAlign )
{
if ( tmpAlign == null )
return null;
switch ( tmpAlign.getValue( ) )
{
case HorizontalAlignment.AUTOMATIC :
return null;
case HorizontalAlignment.CENTER :
return DesignChoiceConstants.TEXT_ALIGN_CENTER;
case HorizontalAlignment.LEFT :
return DesignChoiceConstants.TEXT_ALIGN_LEFT;
case HorizontalAlignment.RIGHT :
return DesignChoiceConstants.TEXT_ALIGN_RIGHT;
case HorizontalAlignment.LEFT_AND_RIGHT :
return DesignChoiceConstants.TEXT_ALIGN_JUSTIFY;
}
return null;
}
private static HorizontalAlignment convertToOdaHorizontalAlignment(
String tmpAlign )
{
if ( tmpAlign == null )
return HorizontalAlignment.get( HorizontalAlignment.AUTOMATIC );
if ( DesignChoiceConstants.TEXT_ALIGN_JUSTIFY
.equalsIgnoreCase( tmpAlign ) )
return HorizontalAlignment.get( HorizontalAlignment.LEFT_AND_RIGHT );
if ( DesignChoiceConstants.TEXT_ALIGN_CENTER
.equalsIgnoreCase( tmpAlign ) )
return HorizontalAlignment.get( HorizontalAlignment.CENTER );
if ( DesignChoiceConstants.TEXT_ALIGN_LEFT.equalsIgnoreCase( tmpAlign ) )
return HorizontalAlignment.get( HorizontalAlignment.LEFT );
if ( DesignChoiceConstants.TEXT_ALIGN_RIGHT.equalsIgnoreCase( tmpAlign ) )
return HorizontalAlignment.get( HorizontalAlignment.RIGHT );
return null;
}
static Boolean convertToROMWordWrap( TextWrapType newValue )
{
if ( newValue == null )
return null;
switch ( newValue.getValue( ) )
{
case TextWrapType.WORD :
return Boolean.TRUE;
case TextWrapType.NONE :
return Boolean.FALSE;
}
return null;
}
private static TextWrapType convertToROMWordWrap( boolean newValue )
{
if ( newValue )
return TextWrapType.WORD_LITERAL;
return TextWrapType.NONE_LITERAL;
}
/**
* Updates column hint values by given axis attributes.
*
* @param outputAttrs
* the latest axis attributes
* @param cachedOutputAttrs
* the last(cached) axis attributes
* @param newHint
* the column hint
*/
private static void updateColumnHintFromAxisAttrs(
AxisAttributes axisAttributes, AxisAttributes cachedAxisAttributes,
ColumnHint newHint )
{
if ( axisAttributes == null )
return;
Object newValue = axisAttributes.getAxisType( );
Object oldValue = cachedAxisAttributes == null
? null
: cachedAxisAttributes.getAxisType( );
if ( !CompareUtil.isEquals( oldValue, newValue ) )
{
newHint.setProperty( ColumnHint.ANALYSIS_MEMBER,
convertAxisTypeToAnalysisType( (AxisType) newValue ) );
}
newValue = axisAttributes.isOnColumnLayout( );
oldValue = cachedAxisAttributes == null ? null : cachedAxisAttributes
.isOnColumnLayout( );
if ( !CompareUtil.isEquals( oldValue, newValue ) )
{
newHint.setProperty( ColumnHint.ON_COLUMN_LAYOUT_MEMBER, newValue );
}
newValue = axisAttributes.getRelatedColumns( );
oldValue = cachedAxisAttributes == null ? null : cachedAxisAttributes
.getRelatedColumns( );
if ( !CompareUtil.isEquals( oldValue, newValue ) )
{
String analysisColumnName = null;
DataElementIdentifiers columns = ( (ResultSubset) newValue )
.getColumnIdentifiers( );
if ( columns != null && !columns.getIdentifiers( ).isEmpty( ) )
analysisColumnName = columns.getIdentifiers( ).get( 0 )
.getName( );
newHint.setProperty( ColumnHint.ANALYSIS_COLUMN_MEMBER,
analysisColumnName );
}
}
/**
* Transfers oda axis type to rom analysis type.
*
* @param axisType
* the oda axis type
* @return the rom analysis type, or null if no such type defined in rom
*/
static String convertAxisTypeToAnalysisType( AxisType axisType )
{
switch ( axisType )
{
case MEASURE_LITERAL :
return DesignChoiceConstants.ANALYSIS_TYPE_MEASURE;
case DIMENSION_ATTRIBUTE_LITERAL :
return DesignChoiceConstants.ANALYSIS_TYPE_ATTRIBUTE;
case DIMENSION_MEMBER_LITERAL :
return DesignChoiceConstants.ANALYSIS_TYPE_DIMENSION;
}
return null;
}
/**
* Updates column hint values by given column definition.
*
* @param columnDefn
* the latest column definition
* @param cachedColumnDefn
* the last(cached) column definition
* @param setColumn
* the oda result set column
* @param dataSourceId
* the data source id
* @param dataSetId
* the data set id
* @param columns
* the iterator that includes oda result set columns
*/
private void updateROMOdaResultSetColumnFromColumnDefinition(
ColumnDefinition columnDefn, ColumnDefinition cachedColumnDefn,
OdaResultSetColumn setColumn, String dataSourceId, String dataSetId )
{
if ( columnDefn == null )
return;
updateResultSetColumnFromDataAttrs(
columnDefn.getAttributes( ),
cachedColumnDefn == null ? null : cachedColumnDefn
.getAttributes( ), setColumn, dataSourceId, dataSetId );
}
/**
* Updates result set column values by given data element attributes.
*
* @param dataAttrs
* the latest data element attributes
* @param cachedDataAttrs
* the last (cached) data element attributes
* @param newColumn
* the result set column
* @param dataSourceId
* the data source id
* @param dataSetId
* the data set id
* @param params
* the iterator that includes oda result set columns
*/
private void updateResultSetColumnFromDataAttrs(
DataElementAttributes dataAttrs,
DataElementAttributes cachedDataAttrs,
OdaResultSetColumn newColumn, String dataSourceId, String dataSetId )
{
if ( dataAttrs == null )
{
return;
}
Object oldValue = cachedDataAttrs == null ? null : cachedDataAttrs
.getName( );
Object newValue = dataAttrs.getName( );
if ( !CompareUtil.isEquals( oldValue, newValue ) )
{
// if the native name is just empty, treat it as null
String tmpNativeName = (String) newValue;
if ( tmpNativeName != null && tmpNativeName.length( ) == 0 )
tmpNativeName = null;
newColumn.setNativeName( tmpNativeName );
}
oldValue = cachedDataAttrs == null ? null : Integer
.valueOf( cachedDataAttrs.getPosition( ) );
newValue = Integer.valueOf( dataAttrs.getPosition( ) );
if ( !CompareUtil.isEquals( oldValue, newValue ) )
{
newColumn.setPosition( (Integer) newValue );
}
oldValue = cachedDataAttrs == null ? null : Integer
.valueOf( cachedDataAttrs.getNativeDataTypeCode( ) );
newValue = Integer.valueOf( dataAttrs.getNativeDataTypeCode( ) );
if ( !CompareUtil.isEquals( oldValue, newValue )
|| newColumn.getNativeDataType( ) == null )
{
newColumn.setNativeDataType( (Integer) newValue );
}
newColumn.setDataType( getROMDataType( dataSourceId, dataSetId,
newColumn ) );
}
/**
* Returns the rom data type in string.
*
* @param dataSourceId
* the id of the data source
* @param dataSetId
* the ide of the data set
* @param column
* the rom data set parameter
* @param setHandleParams
* params defined in data set handle
* @return the rom data type in string
*/
private String getROMDataType( String dataSourceId, String dataSetId,
OdaResultSetColumn column )
{
String name = column.getNativeName( );
Integer position = column.getPosition( );
Integer nativeDataType = column.getNativeDataType( );
OdaResultSetColumnHandle tmpParam = findOdaResultSetColumn(
setDefinedResults.iterator( ), name, position, nativeDataType );
if ( tmpParam == null )
return AdapterUtil.convertNativeTypeToROMDataType( dataSourceId,
dataSetId, column.getNativeDataType( ).intValue( ), null );
Integer tmpPosition = tmpParam.getPosition( );
if ( tmpPosition == null )
return AdapterUtil.convertNativeTypeToROMDataType( dataSourceId,
dataSetId, column.getNativeDataType( ).intValue( ), null );
if ( !tmpPosition.equals( column.getPosition( ) ) )
return AdapterUtil.convertNativeTypeToROMDataType( dataSourceId,
dataSetId, column.getNativeDataType( ).intValue( ), null );
Integer tmpNativeCodeType = tmpParam.getNativeDataType( );
if ( tmpNativeCodeType == null
|| tmpNativeCodeType.equals( column.getNativeDataType( ) ) )
return tmpParam.getDataType( );
String oldDataType = tmpParam.getDataType( );
return AdapterUtil
.convertNativeTypeToROMDataType( dataSourceId, dataSetId,
column.getNativeDataType( ).intValue( ), oldDataType );
}
/**
* Returns the matched oda result set column with the specified name and
* position.
*
* @param columns
* the iterator that includes oda result set columns
* @param paramName
* the result set column name
* @param position
* the position
* @return the matched oda result set column
*/
static OdaResultSetColumnHandle findOdaResultSetColumn( Iterator columns,
String paramName, Integer position, Integer nativeDataType )
{
if ( position == null || nativeDataType == null )
return null;
while ( columns.hasNext( ) )
{
OdaResultSetColumnHandle column = (OdaResultSetColumnHandle) columns
.next( );
Integer tmpNativeDataType = column.getNativeDataType( );
String nativeName = column.getNativeName( );
if ( ( StringUtil.isBlank( nativeName ) || nativeName
.equalsIgnoreCase( paramName ) )
&& position.equals( column.getPosition( ) )
&& ( tmpNativeDataType == null || nativeDataType
.equals( tmpNativeDataType ) ) )
return column;
}
return null;
}
/**
* Returns the matched column definition with the specified name and
* position.
*
* @param columns
* the ODA defined result set column definitions
* @param paramName
* the result set column name
* @param position
* the position
* @return the matched oda result set column
*/
private static ColumnDefinition findColumnDefinition(
ResultSetColumns columns, String columnName, Integer position )
{
if ( columns == null || columnName == null )
return null;
EList odaColumns = columns.getResultColumnDefinitions( );
if ( odaColumns == null || odaColumns.isEmpty( ) )
return null;
for ( int i = 0; i < odaColumns.size( ); i++ )
{
ColumnDefinition columnDefn = (ColumnDefinition) odaColumns.get( i );
DataElementAttributes dataAttrs = columnDefn.getAttributes( );
if ( dataAttrs == null )
continue;
if ( columnName.equals( dataAttrs.getName( ) )
&& ( position == null || position.intValue( ) == dataAttrs
.getPosition( ) ) )
return columnDefn;
}
return null;
}
/**
* Creates a list containing ROM ResultSetColumn according to given ODA
* ResultSets.
*
* @param setDesign
* the data set design
* @param setHandle
* the data set handle
* @param cachedSetDefn
* the ODA result set in designer values
* @return a list containing ROM ResultSetColumn.
* @throws SemanticException
*/
List<ResultSetColumnInfo> newROMResultSets(
ResultSetDefinition cachedSetDefn ) throws SemanticException
{
ResultSetColumns cachedSetColumns = cachedSetDefn == null
? null
: cachedSetDefn.getResultSetColumns( );
ResultSetDefinition resultDefn = setDesign.getPrimaryResultSet( );
if ( resultDefn == null )
{
ResultSets resultSets = setDesign.getResultSets( );
if ( resultSets != null
&& !resultSets.getResultSetDefinitions( ).isEmpty( ) )
resultDefn = (ResultSetDefinition) resultSets
.getResultSetDefinitions( ).get( 0 );
}
if ( resultDefn == null )
return null;
ResultSetColumns setColumns = resultDefn.getResultSetColumns( );
if ( setColumns == null )
return null;
EList odaSetColumns = setColumns.getResultColumnDefinitions( );
if ( odaSetColumns.isEmpty( ) )
return null;
List<ResultSetColumnInfo> retList = new ArrayList<ResultSetColumnInfo>( );
ResultSetColumnInfo setInfo = null;
for ( int i = 0; i < odaSetColumns.size( ); i++ )
{
ColumnDefinition columnDefn = (ColumnDefinition) odaSetColumns
.get( i );
DataElementAttributes dataAttrs = columnDefn.getAttributes( );
ColumnDefinition cachedColumnDefn = null;
OdaResultSetColumnHandle oldColumn = null;
if ( dataAttrs != null )
{
String nativeName = dataAttrs.getName( );
Integer position = Integer.valueOf( dataAttrs.getPosition( ) );
cachedColumnDefn = findColumnDefinition( cachedSetColumns,
nativeName, position );
oldColumn = findOdaResultSetColumn(
setDefinedResults.iterator( ), nativeName, position,
Integer.valueOf( dataAttrs.getNativeDataTypeCode( ) ) );
}
OdaResultSetColumn newColumn = null;
// to use old values if applies
if ( oldColumn == null )
{
// if the old column is not found, this means it can be removed.
// Only update.
newColumn = StructureFactory.createOdaResultSetColumn( );
cachedColumnDefn = null;
}
else
newColumn = (OdaResultSetColumn) oldColumn.getStructure( )
.copy( );
updateROMOdaResultSetColumnFromColumnDefinition( columnDefn,
cachedColumnDefn, newColumn,
setDesign.getOdaExtensionDataSourceId( ),
setDesign.getOdaExtensionDataSetId( ) );
ColumnHint oldHint = null;
ColumnHintHandle oldHintHandle = AdapterUtil.findColumnHint(
newColumn, setDefinedColumnHints.iterator( ) );
if ( oldHintHandle != null )
oldHint = (ColumnHint) oldHintHandle.getStructure( );
ColumnHint newHint = newROMColumnHintFromColumnDefinition(
columnDefn, cachedColumnDefn, oldHint, newColumn );
setInfo = new ResultSetColumnInfo( newColumn, newHint );
retList.add( setInfo );
}
List<OdaResultSetColumn> columns = new ArrayList<OdaResultSetColumn>( );
ResultSetColumnInfo.updateResultSetColumnList( retList, columns, null );
// create unique column names if native names is null or empty.
createUniqueResultSetColumnNames( retList );
// retrieve column hints for computed columns.
updateHintsForComputedColumn( );
return retList;
}
/**
* Returns the matched column hint with the given result set column.
*
* @param name
* the name of the column hint
* @param columns
* the iterator that includes column hints
* @return the matched column hint
*/
static ResultSetColumnHandle findColumn( String name, Iterator columns )
{
if ( name == null )
return null;
while ( columns.hasNext( ) )
{
ResultSetColumnHandle column = (ResultSetColumnHandle) columns
.next( );
if ( name.equals( column.getColumnName( ) ) )
return column;
}
return null;
}
/**
* Updates the ResultSetDefinition with the given ROM ResultSet columns.
*
*/
void updateOdaResultSetDefinition( )
{
setDesign.setPrimaryResultSet( newOdaResultSetDefinition( ) );
filterAdapter.updateODAResultSetCriteria( );
}
/**
* Creates a ResultSetDefinition with the given ROM ResultSet columns.
*
* @return the created ResultSetDefinition
*/
private ResultSetDefinition newOdaResultSetDefinition( )
{
Iterator romSets = setDefinedResults.iterator( );
String name = setHandle.getResultSetName( );
if ( !romSets.hasNext( ) )
return null;
ResultSetDefinition odaSetDefn = null;
ResultSetColumns odaSetColumns = null;
if ( !StringUtil.isBlank( name ) )
{
odaSetDefn = designFactory.createResultSetDefinition( );
odaSetDefn.setName( name );
}
while ( romSets.hasNext( ) )
{
if ( odaSetDefn == null )
odaSetDefn = designFactory.createResultSetDefinition( );
if ( odaSetColumns == null )
odaSetColumns = designFactory.createResultSetColumns( );
OdaResultSetColumnHandle setColumn = (OdaResultSetColumnHandle) romSets
.next( );
// get the colum hint
ColumnHintHandle hint = AdapterUtil.findColumnHint(
(OdaResultSetColumn) setColumn.getStructure( ),
setDefinedColumnHints.iterator( ) );
ColumnDefinition columnDefn = designFactory
.createColumnDefinition( );
DataElementAttributes dataAttrs = designFactory
.createDataElementAttributes( );
String newName = setColumn.getNativeName( );
dataAttrs.setName( newName );
Integer position = setColumn.getPosition( );
if ( position != null )
dataAttrs.setPosition( setColumn.getPosition( ).intValue( ) );
Integer nativeDataType = setColumn.getNativeDataType( );
if ( nativeDataType != null )
dataAttrs.setNativeDataTypeCode( nativeDataType.intValue( ) );
columnDefn.setAttributes( dataAttrs );
odaSetColumns.getResultColumnDefinitions( ).add( columnDefn );
if ( hint == null )
continue;
updateOdaColumnHint( columnDefn, hint );
}
if ( odaSetDefn != null )
odaSetDefn.setResultSetColumns( odaSetColumns );
return odaSetDefn;
}
/**
* Updates oda filter expression by ROM filter condition
*/
void updateOdaFilterExpression( )
{
filterAdapter.updateODAResultSetCriteria( );
}
/**
* Updates rom filter condition by ODA filter expression
*/
void updateROMFilterCondition( ) throws SemanticException
{
filterAdapter.updateROMSortAndFilter( );
}
/**
* Creates unique result set column names if column names are
* <code>null</code> or empty string.
*
* @param resultSetColumn
* a list containing result set columns
*/
static void createUniqueResultSetColumnNames(
List<ResultSetColumnInfo> columnInfo )
{
if ( columnInfo == null || columnInfo.isEmpty( ) )
return;
Set<String> names = new HashSet<String>( );
for ( int i = 0; i < columnInfo.size( ); i++ )
{
ResultSetColumnInfo tmpInfo = columnInfo.get( i );
OdaResultSetColumn column = tmpInfo.column;
String nativeName = column.getNativeName( );
if ( nativeName != null )
names.add( nativeName );
}
Set<String> newNames = new HashSet<String>( );
for ( int i = 0; i < columnInfo.size( ); i++ )
{
ResultSetColumnInfo tmpInfo = columnInfo.get( i );
OdaResultSetColumn column = tmpInfo.column;
String nativeName = column.getNativeName( );
String name = column.getColumnName( );
if ( !StringUtil.isBlank( name ) )
{
newNames.add( name );
continue;
}
nativeName = StringUtil.trimString( nativeName );
String newName = IdentifierUtility.getUniqueColumnName( names,
newNames, nativeName, i );
newNames.add( newName );
column.setColumnName( newName );
if ( tmpInfo.hint != null )
tmpInfo.hint.setProperty( ColumnHint.COLUMN_NAME_MEMBER,
newName );
}
names.clear( );
newNames.clear( );
}
/**
* Updates column hints for computed columns. Saved in the field.
*
*/
private void updateHintsForComputedColumn( )
{
Iterator columns = setHandle.computedColumnsIterator( );
List<String> columnNames = new ArrayList<String>( );
while ( columns.hasNext( ) )
{
ComputedColumnHandle tmpColumn = (ComputedColumnHandle) columns
.next( );
columnNames.add( tmpColumn.getName( ) );
}
for ( int i = 0; i < columnNames.size( ); i++ )
{
String columnName = columnNames.get( i );
ColumnHintHandle hintHandle = AdapterUtil.findColumnHint(
columnName, setDefinedColumnHints.iterator( ) );
if ( hintHandle == null )
continue;
if ( columnHintsForComputedColumns == null )
columnHintsForComputedColumns = new ArrayList<IStructure>( );
columnHintsForComputedColumns.add( hintHandle.getStructure( )
.copy( ) );
}
}
/**
* Returns column hints for computed columns.
*
* @return a list containing column hints structures.
*/
List<IStructure> getHintsForComputedColumn( )
{
if ( columnHintsForComputedColumns == null )
return Collections.EMPTY_LIST;
return columnHintsForComputedColumns;
}
/**
* Updates hint-related information on ODA column definitions.
*
*/
void updateOdaColumnHints( )
{
ResultSetDefinition columnDefns = setDesign.getPrimaryResultSet( );
if ( columnDefns == null )
return;
for ( int i = 0; i < setDefinedColumnHints.size( ); i++ )
{
ColumnHintHandle hint = (ColumnHintHandle) setDefinedColumnHints
.get( i );
OdaResultSetColumnHandle column = (OdaResultSetColumnHandle) findColumn(
hint.getColumnName( ), setDefinedResults.iterator( ) );
if ( column == null )
continue;
ColumnDefinition odaColumn = findColumnDefinition(
columnDefns.getResultSetColumns( ),
column.getNativeName( ), column.getPosition( ) );
if ( odaColumn == null )
continue;
updateOdaColumnHint( odaColumn, hint );
}
}
/**
* Updates hint-related information on the ODA <code>columnDefn</code>.
*
* @param columnDefn
* @param hint
*/
private void updateOdaColumnHint( ColumnDefinition columnDefn,
ColumnHintHandle hint )
{
DataElementAttributes dataAttrs = columnDefn.getAttributes( );
DataElementUIHints uiHints = null;
// update display name
String displayName = hint.getDisplayName( );
String displayNameKey = hint.getDisplayNameKey( );
if ( displayName != null || displayNameKey != null )
{
uiHints = designFactory.createDataElementUIHints( );
uiHints.setDisplayName( displayName );
uiHints.setDisplayNameKey( displayNameKey );
}
// description maps to the description in data element UI hints.
// String desc = hint.getDescription( );
// String descKey = hint.getDescriptionKey( );
/*
* if ( desc != null || descKey != null ) { if ( uiHints == null )
* uiHints = designFactory.createDataElementUIHints( );
*
* uiHints.setDescription( desc ); uiHints.setDescriptionKey( descKey );
* }
*/
dataAttrs.setUiHints( uiHints );
// update usage hints.
OutputElementAttributes outputAttrs = null;
String helpText = hint.getHelpText( );
String helpTextKey = hint.getHelpTextKey( );
if ( helpText != null || helpTextKey != null )
{
outputAttrs = designFactory.createOutputElementAttributes( );
if ( helpText != null || helpTextKey != null )
{
outputAttrs.setHelpText( helpText );
outputAttrs.setHelpTextKey( helpTextKey );
}
}
// heading maps to m_label
String heading = hint.getHeading( );
String headingKey = hint.getHeadingKey( );
if ( heading != null || headingKey != null )
{
if ( outputAttrs == null )
outputAttrs = designFactory.createOutputElementAttributes( );
if ( heading != null || headingKey != null )
{
outputAttrs.setLabel( heading );
outputAttrs.setLabelKey( headingKey );
}
}
// formatting related.
FormatValue format = hint.getValueFormat( );
// int displayLength = hint.getDisplayLength( );
// boolean wordWrap = hint.wordWrap( );
String horizontalAlign = hint.getHorizontalAlign( );
if ( ( format != null && format.getPattern( ) != null )
|| horizontalAlign != null )
{
if ( outputAttrs == null )
outputAttrs = designFactory.createOutputElementAttributes( );
ValueFormatHints formatHint = designFactory
.createValueFormatHints( );
if ( format != null )
formatHint.setDisplayFormat( format.getPattern( ) );
// formatHint.setDisplaySize( displayLength );
formatHint
.setHorizontalAlignment( convertToOdaHorizontalAlignment( horizontalAlign ) );
// formatHint.setTextWrapType( convertToROMWordWrap( wordWrap ) );
// cannot handle text format since two objects in ODA and ROM are
// different.
outputAttrs.setFormattingHints( formatHint );
}
columnDefn.setUsageHints( outputAttrs );
// update axis attributes
AxisAttributes axisAttrs = null;
String analysisType = hint.getAnalysis( );
AxisType axisType = convertAnalysisTypeToAxisType( analysisType );
if ( axisType != null )
{
axisAttrs = designFactory.createAxisAttributes( );
axisAttrs.setAxisType( axisType );
axisAttrs.setOnColumnLayout( hint.isOnColumnLayout( ) );
String analysisColumnName = hint.getAnalysisColumn( );
if ( !StringUtil.isBlank( analysisColumnName ) )
{
ResultSubset relatedColumns = designFactory
.createResultSubset( );
relatedColumns.addColumnIdentifier( analysisColumnName );
axisAttrs.setRelatedColumns( relatedColumns );
}
}
columnDefn.setMultiDimensionAttributes( axisAttrs );
}
/**
* Transfers rom analysis type to oda axis type.
*
* @param analysisType
* the rom analysis type
* @return the oda axis type, or null if no such type defined in oda
*/
private AxisType convertAnalysisTypeToAxisType( String analysisType )
{
AxisType axisType = null;
if ( DesignChoiceConstants.ANALYSIS_TYPE_MEASURE.equals( analysisType ) )
axisType = AxisType.MEASURE_LITERAL;
else if ( DesignChoiceConstants.ANALYSIS_TYPE_ATTRIBUTE
.equals( analysisType ) )
axisType = AxisType.DIMENSION_ATTRIBUTE_LITERAL;
else if ( DesignChoiceConstants.ANALYSIS_TYPE_DIMENSION
.equals( analysisType ) )
axisType = AxisType.DIMENSION_MEMBER_LITERAL;
return axisType;
}
/**
* The data strcuture to hold a result set column and its column hint.
*
*/
static class ResultSetColumnInfo
{
private OdaResultSetColumn column;
private ColumnHint hint;
/**
* @param column
* @param hint
*/
ResultSetColumnInfo( OdaResultSetColumn column, ColumnHint hint )
{
this.column = column;
this.hint = hint;
}
/**
* Distributes result set columns and column hints to different lists.
*
* @param infos
* the list containing result set column info
* @param columns
* the list containing result set column
* @param hints
* the list containing column hint
*/
static void updateResultSetColumnList( List<ResultSetColumnInfo> infos,
List<OdaResultSetColumn> columns, List<ColumnHint> hints )
{
if ( infos == null || infos.isEmpty( ) )
return;
for ( int i = 0; i < infos.size( ); i++ )
{
ResultSetColumnInfo info = infos.get( i );
if ( columns != null )
columns.add( info.column );
if ( info.hint != null && hints != null )
hints.add( info.hint );
}
}
}
} |
package org.jtalks.poulpe.web.controller.section.dialogs;
import org.jtalks.common.model.entity.Group;
import org.jtalks.poulpe.model.entity.PoulpeBranch;
import org.jtalks.poulpe.model.entity.PoulpeSection;
import org.jtalks.poulpe.service.ForumStructureService;
import org.jtalks.poulpe.service.GroupService;
import org.jtalks.poulpe.web.controller.section.ForumStructureTreeModel;
import org.jtalks.poulpe.web.controller.section.ForumStructureVm;
import org.zkoss.bind.annotation.BindingParam;
import org.zkoss.bind.annotation.Command;
import org.zkoss.bind.annotation.GlobalCommand;
import org.zkoss.bind.annotation.NotifyChange;
import org.zkoss.zul.ListModelList;
import javax.annotation.Nonnull;
import javax.validation.constraints.NotNull;
import java.util.List;
/**
* View model that manages branch editing dialog and its data (like section list in dropdown).
*
* @author stanislav bashkirtsev
*/
public class BranchEditingDialog {
private static final String SHOW_DIALOG = "showDialog", EDITED_BRANCH = "editedBranch";
private static final String MODERATING_GROUP = "moderatingGroup", CANDIDATES_TO_MODERATE = "candidatesToModerate";
private final GroupService groupService;
private final ListModelList<PoulpeSection> sectionList = new ListModelList<PoulpeSection>();
private final GroupList groupList = new GroupList();
private final ForumStructureVm forumStructureVm;
private final ForumStructureService forumStructureService;
private PoulpeBranch editedBranch = new PoulpeBranch();
private boolean showDialog;
public BranchEditingDialog(GroupService groupService, ForumStructureVm forumStructureVm,
ForumStructureService forumStructureService) {
this.groupService = groupService;
this.forumStructureVm = forumStructureVm;
this.forumStructureService = forumStructureService;
}
@GlobalCommand
@NotifyChange({SHOW_DIALOG, EDITED_BRANCH, MODERATING_GROUP, CANDIDATES_TO_MODERATE})
public void showBranchDialog(@BindingParam("selectedBranch") PoulpeBranch selectedBranch) {
showDialog(selectedBranch);
}
@GlobalCommand
@NotifyChange({SHOW_DIALOG, EDITED_BRANCH, MODERATING_GROUP, CANDIDATES_TO_MODERATE})
public void showCreateBranchDialog() {
showDialog(new PoulpeBranch());
}
@Command
@NotifyChange(SHOW_DIALOG)
public void saveBranch() {
PoulpeBranch updatedBranch = storeSelectedBranch();
forumStructureVm.updateBranchInTree(updatedBranch);
closeDialog();
}
/**
* Closes the dialog without removing any underlying state.
*/
public void closeDialog() {
showDialog = false;
}
private void showDialog(PoulpeBranch editedBranch) {
groupList.setGroups(groupService.getAll());
this.editedBranch = editedBranch;
ForumStructureTreeModel treeModel = forumStructureVm.getTreeModel();
renewSectionsFromTree(treeModel);
selectSection(treeModel.getSelectedSection());
showDialog = true;
}
/**
* By this flag the ZUL decides whether to show the branch editing dialog or not.
*
* @return whether to show the branch editing dialog
*/
public boolean isShowDialog() {
boolean result = showDialog;
showDialog = false;
return result;
}
public void selectSection(PoulpeSection section) {
sectionList.addToSelection(section);
}
/**
* Gets the list of available sections so that it's possible to place the branch to some other section.
*
* @return the list of available sections so that it's possible to place the branch to some other section
*/
public ListModelList<PoulpeSection> getSectionList() {
return sectionList;
}
/**
* Clears the previous sections and gets the new ones from the specified tree.
*
* @param forumTree a forum structure tree to get sections from it
*/
void renewSectionsFromTree(@Nonnull ForumStructureTreeModel forumTree) {
this.sectionList.clear();
this.sectionList.addAll(forumTree.getSections());
}
public PoulpeBranch getEditedBranch() {
return editedBranch;
}
PoulpeBranch storeSelectedBranch() {
PoulpeSection section = sectionList.getSelection().iterator().next();
return forumStructureService.saveBranch(section, editedBranch);
}
/**
* Gets a list of all the groups in the database so that user can choose another moderating group from the list.
*
* @return a list of all the groups in the database
*/
public List<Group> getCandidatesToModerate() {
return groupList.getGroups();
}
/**
* Gets the group that is equal to the one that is currently moderating the selected branch. A new group with the
* empty fields will be created if there is no moderating group of the branch (it's a new branch). Note, that this
* method will be used by ZK in order to identify currently selected item in Combo Box, which means that it doesn't
* actually need a real object to be returned, but it will be enough if we return an equal object (in our case
* equals means they have the same UUID). Due to this and due to the problem with ZK binding (Hibernate will return
* a proxy here, but method {@link #getCandidatesToModerate()} returns non-proxies, and when ZK tries to set the
* value, it throws a class cast exception because proxy != a usual class instance). That's why this method returns
* an instance that is equal to the real moderating group, not the actual one.
*
* @return the group that is equal to the one that is currently moderating the selected branch
*/
@NotNull(message = "{branch.moderating_group.not_null_constraint}")
public Group getModeratingGroup() {
Group currentModeratorsGroup = editedBranch.getModeratorsGroup();
return groupList.getEqual(currentModeratorsGroup);
}
/**
* Sets the moderating group to the branch after user changed it in the dialog's list.
*
* @param moderatingGroup a new moderating group to set to the branch (or the old one, but this doesn't change
* anything)
*/
public void setModeratingGroup(Group moderatingGroup) {
editedBranch.setModeratorsGroup(moderatingGroup);
}
} |
package hudson.maven;
import hudson.Launcher;
import hudson.maven.MavenBuild.ProxyImpl2;
import hudson.model.BuildListener;
import hudson.model.Hudson;
import hudson.model.Result;
import hudson.remoting.Channel;
import hudson.remoting.DelegatingCallable;
import hudson.remoting.Future;
import hudson.util.IOException2;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutionException;
import org.apache.maven.execution.AbstractExecutionListener;
import org.apache.maven.execution.ExecutionEvent;
import org.apache.maven.execution.ExecutionListener;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.Mojo;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.PluginConfigurationException;
import org.apache.maven.plugin.PluginContainerException;
import org.apache.maven.plugin.PluginParameterExpressionEvaluator;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator;
import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration;
import org.jvnet.hudson.maven3.agent.Maven3Main;
import org.jvnet.hudson.maven3.launcher.Maven3Launcher;
import org.jvnet.hudson.maven3.listeners.HudsonMavenBuildHelper;
import org.jvnet.hudson.maven3.listeners.HudsonMavenExecutionResult;
/**
* @author Olivier Lamy
*
*/
public class Maven3Builder extends AbstractMavenBuilder implements DelegatingCallable<Result,IOException> {
/**
* Flag needs to be set at the constructor, so that this reflects
* the setting at master.
*/
private final boolean profile = MavenProcessFactory.profile;
/**
* Record all asynchronous executions as they are scheduled,
* to make sure they are all completed before we finish.
*/
protected transient /*final*/ List<Future<?>> futures;
HudsonMavenExecutionResult mavenExecutionResult;
private final Map<ModuleName,MavenBuildProxy2> proxies;
private final Map<ModuleName,ProxyImpl2> sourceProxies;
private final Map<ModuleName,List<MavenReporter>> reporters = new HashMap<ModuleName,List<MavenReporter>>();
protected Maven3Builder(BuildListener listener,Map<ModuleName,ProxyImpl2> proxies, Map<ModuleName,List<MavenReporter>> reporters, List<String> goals, Map<String, String> systemProps) {
super( listener, goals, systemProps );
sourceProxies = new HashMap<ModuleName, ProxyImpl2>(proxies);
this.proxies = new HashMap<ModuleName, MavenBuildProxy2>(proxies);
for (Entry<ModuleName,MavenBuildProxy2> e : this.proxies.entrySet())
e.setValue(new FilterImpl(e.getValue()));
this.reporters.putAll( reporters );
}
public Result call()
throws IOException
{
MavenExecutionListener mavenExecutionListener = new MavenExecutionListener( this );
try {
futures = new ArrayList<Future<?>>();
Maven3Launcher.setMavenExecutionListener( mavenExecutionListener );
markAsSuccess = false;
// working around NPE when someone puts a null value into systemProps.
for (Map.Entry<String,String> e : systemProps.entrySet()) {
if (e.getValue()==null)
throw new IllegalArgumentException("System property "+e.getKey()+" has a null value");
System.getProperties().put(e.getKey(), e.getValue());
}
listener.getLogger().println(formatArgs(goals));
int r = Maven3Main.launch( goals.toArray(new String[goals.size()]));
// now check the completion status of async ops
boolean messageReported = false;
long startTime = System.nanoTime();
for (Future<?> f : futures) {
try {
if(!f.isDone() && !messageReported) {
messageReported = true;
// FIXME messages
listener.getLogger().println("maven builder waiting");
}
f.get();
} catch (InterruptedException e) {
// attempt to cancel all asynchronous tasks
for (Future<?> g : futures)
g.cancel(true);
// FIXME messages
listener.getLogger().println("build aborted");
return Result.ABORTED;
} catch (ExecutionException e) {
// FIXME messages
e.printStackTrace(listener.error("async build failed"));
}
}
mavenExecutionListener.overheadTime += System.nanoTime()-startTime;
futures.clear();
if(profile) {
NumberFormat n = NumberFormat.getInstance();
PrintStream logger = listener.getLogger();
logger.println("Total overhead was "+format(n,mavenExecutionListener.overheadTime)+"ms");
Channel ch = Channel.current();
logger.println("Class loading " +format(n,ch.classLoadingTime.get()) +"ms, "+ch.classLoadingCount+" classes");
logger.println("Resource loading "+format(n,ch.resourceLoadingTime.get())+"ms, "+ch.resourceLoadingCount+" times");
}
mavenExecutionResult = Maven3Launcher.getMavenExecutionResult();
//FIXME handle
//mavenExecutionResult.getThrowables()
PrintStream logger = listener.getLogger();
logger.println("Maven3Builder classLoaderDebug");
logger.println("getClass().getClassLoader(): " + getClass().getClassLoader());
if(r==0 && mavenExecutionResult.getThrowables().isEmpty()) {
logger.print( "r==0" );
markAsSuccess = true;
}
if (!mavenExecutionResult.getThrowables().isEmpty()) {
logger.println( "mavenExecutionResult.throwables not empty");
for(Throwable throwable : mavenExecutionResult.getThrowables()) {
throwable.printStackTrace( logger );
}
markAsSuccess = false;
}
if(markAsSuccess) {
// FIXME message
//listener.getLogger().println(Messages.MavenBuilder_Failed());
listener.getLogger().println("success");
return Result.SUCCESS;
}
return Result.FAILURE;
} catch (NoSuchMethodException e) {
throw new IOException2(e);
} catch (IllegalAccessException e) {
throw new IOException2(e);
} catch (InvocationTargetException e) {
throw new IOException2(e);
} catch (ClassNotFoundException e) {
throw new IOException2(e);
} catch (Exception e) {
throw new IOException2(e);
}
}
// since reporters might be from plugins, use the uberjar to resolve them.
public ClassLoader getClassLoader() {
return Hudson.getInstance().getPluginManager().uberClassLoader;
}
/**
* Invoked after the maven has finished running, and in the master, not in the maven process.
*/
void end(Launcher launcher) throws IOException, InterruptedException {
for (Map.Entry<ModuleName,ProxyImpl2> e : sourceProxies.entrySet()) {
ProxyImpl2 p = e.getValue();
for (MavenReporter r : reporters.get(e.getKey())) {
// we'd love to do this when the module build ends, but doing so requires
// we know how many task segments are in the current build.
r.end(p.owner(),launcher,listener);
p.appendLastLog();
}
p.close();
}
}
private class FilterImpl extends MavenBuildProxy2.Filter<MavenBuildProxy2> implements Serializable {
public FilterImpl(MavenBuildProxy2 core) {
super(core);
}
@Override
public void executeAsync(final BuildCallable<?,?> program) throws IOException {
futures.add(Channel.current().callAsync(new AsyncInvoker(core,program)));
}
private static final long serialVersionUID = 1L;
}
private static final class MavenExecutionListener extends AbstractExecutionListener implements Serializable, ExecutionListener {
private final Maven3Builder maven3Builder;
/**
* Number of total nanoseconds {@link Maven3Builder} spent.
*/
long overheadTime;
private final Map<ModuleName,MavenBuildProxy2> proxies;
private final Map<ModuleName,List<ExecutedMojo>> executedMojosPerModule = new ConcurrentHashMap<ModuleName, List<ExecutedMojo>>();
private final Map<ModuleName,List<MavenReporter>> reporters = new HashMap<ModuleName,List<MavenReporter>>();
private final Map<ModuleName, Long> currentMojoStartPerModuleName = new ConcurrentHashMap<ModuleName, Long>();
public MavenExecutionListener(Maven3Builder maven3Builder) {
this.maven3Builder = maven3Builder;
this.proxies = new HashMap<ModuleName, MavenBuildProxy2>(maven3Builder.proxies);
for (Entry<ModuleName,MavenBuildProxy2> e : this.proxies.entrySet())
{
e.setValue(maven3Builder.new FilterImpl(e.getValue()));
executedMojosPerModule.put( e.getKey(), new CopyOnWriteArrayList<ExecutedMojo>() );
}
this.reporters.putAll( new HashMap<ModuleName, List<MavenReporter>>(maven3Builder.reporters) );
}
private MavenBuildProxy2 getMavenBuildProxy2(MavenProject mavenProject)
{
for (Entry<ModuleName,MavenBuildProxy2> entry : proxies.entrySet())
{
if (entry.getKey().compareTo( new ModuleName( mavenProject ) ) == 0)
{
return entry.getValue();
}
}
return null;
}
// FIXME MojoInfo need the real mojo ??
// so tricky to do need to use MavenPluginManager on the current Maven Build
private Mojo getMojo(MojoExecution mojoExecution, MavenSession mavenSession)
{
try
{
return HudsonMavenBuildHelper.getMavenPluginManager().getConfiguredMojo( Mojo.class, mavenSession,
mojoExecution );
}
catch ( PluginContainerException e )
{
throw new RuntimeException( e.getMessage(), e );
}
catch ( PluginConfigurationException e )
{
throw new RuntimeException( e.getMessage(), e );
}
}
private ExpressionEvaluator getExpressionEvaluator(MavenSession session, MojoExecution mojoExecution)
{
return new PluginParameterExpressionEvaluator( session, mojoExecution );
}
private List<MavenReporter> getMavenReporters(MavenProject mavenProject)
{
return reporters.get( new ModuleName( mavenProject ) );
}
private void initMojoStartTime( MavenProject mavenProject)
{
this.currentMojoStartPerModuleName.put( new ModuleName( mavenProject.getGroupId(),
mavenProject.getArtifactId() ),
Long.valueOf( new Date().getTime() ) );
}
private Long getMojoStartTime(MavenProject mavenProject)
{
return currentMojoStartPerModuleName.get( new ModuleName( mavenProject.getGroupId(),
mavenProject.getArtifactId() ) );
}
/**
* @see org.apache.maven.execution.ExecutionListener#projectDiscoveryStarted(org.apache.maven.execution.ExecutionEvent)
*/
public void projectDiscoveryStarted( ExecutionEvent event )
{
}
/**
* @see org.apache.maven.execution.ExecutionListener#sessionStarted(org.apache.maven.execution.ExecutionEvent)
*/
public void sessionStarted( ExecutionEvent event )
{
}
/**
* @see org.apache.maven.execution.ExecutionListener#sessionEnded(org.apache.maven.execution.ExecutionEvent)
*/
public void sessionEnded( ExecutionEvent event )
{
maven3Builder.listener.getLogger().println( "sessionEnded in MavenExecutionListener " );
}
/**
* @see org.apache.maven.execution.ExecutionListener#projectSkipped(org.apache.maven.execution.ExecutionEvent)
*/
public void projectSkipped( ExecutionEvent event )
{
MavenBuildProxy2 mavenBuildProxy2 = getMavenBuildProxy2( event.getProject() );
}
/**
* @see org.apache.maven.execution.ExecutionListener#projectStarted(org.apache.maven.execution.ExecutionEvent)
*/
public void projectStarted( ExecutionEvent event )
{
maven3Builder.listener.getLogger().println( "projectStarted in MavenExecutionListener "
+ event.getProject().getGroupId() + ":"
+ event.getProject().getArtifactId() );
MavenProject mavenProject = event.getProject();
List<MavenReporter> mavenReporters = getMavenReporters( mavenProject );
MavenBuildProxy2 mavenBuildProxy2 = getMavenBuildProxy2( mavenProject );
mavenBuildProxy2.start();
if (mavenReporters != null)
{
for (MavenReporter mavenReporter : mavenReporters)
{
try
{
mavenReporter.enterModule( mavenBuildProxy2 ,mavenProject, maven3Builder.listener);
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
if (mavenReporters != null)
{
for (MavenReporter mavenReporter : mavenReporters)
{
try
{
mavenReporter.preBuild( mavenBuildProxy2 ,mavenProject, maven3Builder.listener);
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
}
/**
* @see org.apache.maven.execution.ExecutionListener#projectSucceeded(org.apache.maven.execution.ExecutionEvent)
*/
public void projectSucceeded( ExecutionEvent event )
{
maven3Builder.listener.getLogger().println( "projectSucceeded in MavenExecutionListener "
+ event.getProject().getGroupId() + ":"
+ event.getProject().getArtifactId() );
MavenProject mavenProject = event.getProject();
List<MavenReporter> mavenReporters = getMavenReporters( mavenProject );
MavenBuildProxy2 mavenBuildProxy2 = getMavenBuildProxy2( mavenProject );
mavenBuildProxy2.end();
mavenBuildProxy2.setResult( Result.SUCCESS );
if ( mavenReporters != null )
{
for ( MavenReporter mavenReporter : mavenReporters )
{
try
{
mavenReporter.leaveModule( mavenBuildProxy2, mavenProject, maven3Builder.listener);
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
if ( mavenReporters != null )
{
for ( MavenReporter mavenReporter : mavenReporters )
{
try
{
mavenReporter.postBuild( mavenBuildProxy2, mavenProject, maven3Builder.listener);
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
}
/**
* @see org.apache.maven.execution.ExecutionListener#projectFailed(org.apache.maven.execution.ExecutionEvent)
*/
public void projectFailed( ExecutionEvent event )
{
maven3Builder.listener.getLogger().println("projectFailed" );
MavenBuildProxy2 mavenBuildProxy2 = getMavenBuildProxy2( event.getProject() );
mavenBuildProxy2.end();
mavenBuildProxy2.setResult( Result.SUCCESS );
}
/**
* @see org.apache.maven.execution.ExecutionListener#mojoSkipped(org.apache.maven.execution.ExecutionEvent)
*/
public void mojoSkipped( ExecutionEvent event )
{
// TODO ?
}
/**
* @see org.apache.maven.execution.ExecutionListener#mojoStarted(org.apache.maven.execution.ExecutionEvent)
*/
public void mojoStarted( ExecutionEvent event )
{
initMojoStartTime( event.getProject() );
maven3Builder.listener.getLogger().println("mojoStarted " + event.getMojoExecution().getArtifactId());
MavenProject mavenProject = event.getProject();
XmlPlexusConfiguration xmlPlexusConfiguration = new XmlPlexusConfiguration( event.getMojoExecution().getConfiguration() );
Mojo mojo = null;//getMojo( event.getMojoExecution(), event.getSession() );
MojoInfo mojoInfo =
new MojoInfo( event.getMojoExecution(), mojo, xmlPlexusConfiguration,
getExpressionEvaluator( event.getSession(), event.getMojoExecution() ) );
List<MavenReporter> mavenReporters = getMavenReporters( mavenProject );
MavenBuildProxy2 mavenBuildProxy2 = getMavenBuildProxy2( mavenProject );
if (mavenReporters != null)
{
for (MavenReporter mavenReporter : mavenReporters)
{
try
{
mavenReporter.preExecute( mavenBuildProxy2, mavenProject, mojoInfo, maven3Builder.listener);
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
}
/**
* @see org.apache.maven.execution.ExecutionListener#mojoSucceeded(org.apache.maven.execution.ExecutionEvent)
*/
public void mojoSucceeded( ExecutionEvent event )
{
Long startTime = getMojoStartTime( event.getProject() );
Date endTime = new Date();
maven3Builder.listener.getLogger().println("mojoSucceeded " + event.getMojoExecution().getArtifactId());
MavenProject mavenProject = event.getProject();
XmlPlexusConfiguration xmlPlexusConfiguration = new XmlPlexusConfiguration( event.getMojoExecution().getConfiguration() );
Mojo mojo = null;//getMojo( event.getMojoExecution(), event.getSession() );
MojoInfo mojoInfo =
new MojoInfo( event.getMojoExecution(), mojo, xmlPlexusConfiguration,
getExpressionEvaluator( event.getSession(), event.getMojoExecution() ) );
try
{
ExecutedMojo executedMojo =
new ExecutedMojo( mojoInfo, startTime == null ? 0 : endTime.getTime() - startTime.longValue() );
this.executedMojosPerModule.get( new ModuleName( mavenProject.getGroupId(),
mavenProject.getArtifactId() ) ).add( executedMojo );
}
catch ( Exception e )
{
// ignoring this
maven3Builder.listener.getLogger().println( "ignoring exception during new ExecutedMojo "
+ e.getMessage() );
}
List<MavenReporter> mavenReporters = getMavenReporters( mavenProject );
MavenBuildProxy2 mavenBuildProxy2 = getMavenBuildProxy2( mavenProject );
mavenBuildProxy2.setExecutedMojos( this.executedMojosPerModule.get( new ModuleName( event.getProject() ) ) );
if (mavenReporters != null)
{
for (MavenReporter mavenReporter : mavenReporters)
{
try
{
mavenReporter.postExecute( mavenBuildProxy2, mavenProject, mojoInfo, maven3Builder.listener, null);
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
}
/**
* @see org.apache.maven.execution.ExecutionListener#mojoFailed(org.apache.maven.execution.ExecutionEvent)
*/
public void mojoFailed( ExecutionEvent event )
{
maven3Builder.listener.getLogger().println("mojoFailed " + event.getMojoExecution().getArtifactId());
Long startTime = getMojoStartTime( event.getProject() );
Date endTime = new Date();
MavenProject mavenProject = event.getProject();
XmlPlexusConfiguration xmlPlexusConfiguration = new XmlPlexusConfiguration( event.getMojoExecution().getConfiguration() );
Mojo mojo = null;//getMojo( event.getMojoExecution(), event.getSession() );
MojoInfo mojoInfo =
new MojoInfo( event.getMojoExecution(), mojo, xmlPlexusConfiguration,
getExpressionEvaluator( event.getSession(), event.getMojoExecution() ) );
try
{
ExecutedMojo executedMojo =
new ExecutedMojo( mojoInfo, startTime == null ? 0 : endTime.getTime() - startTime.longValue() );
this.executedMojosPerModule.get( new ModuleName( mavenProject.getGroupId(),
mavenProject.getArtifactId() ) ).add( executedMojo );
}
catch ( Exception e )
{
// ignoring this
maven3Builder.listener.getLogger().println( "ignoring exception during new ExecutedMojo "
+ e.getMessage() );
}
List<MavenReporter> mavenReporters = getMavenReporters( mavenProject );
MavenBuildProxy2 mavenBuildProxy2 = getMavenBuildProxy2( mavenProject );
mavenBuildProxy2.setExecutedMojos( this.executedMojosPerModule.get( new ModuleName( event.getProject() ) ) );
if (mavenReporters != null)
{
for (MavenReporter mavenReporter : mavenReporters)
{
try
{
// FIXME get exception during mojo execution ?
mavenReporter.postExecute( mavenBuildProxy2, mavenProject, mojoInfo, maven3Builder.listener, null );
}
catch ( InterruptedException e )
{
e.printStackTrace();
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
}
/**
* @see org.apache.maven.execution.ExecutionListener#forkStarted(org.apache.maven.execution.ExecutionEvent)
*/
public void forkStarted( ExecutionEvent event )
{
// TODO !
}
/**
* @see org.apache.maven.execution.ExecutionListener#forkSucceeded(org.apache.maven.execution.ExecutionEvent)
*/
public void forkSucceeded( ExecutionEvent event )
{
// TODO !
}
/**
* @see org.apache.maven.execution.ExecutionListener#forkFailed(org.apache.maven.execution.ExecutionEvent)
*/
public void forkFailed( ExecutionEvent event )
{
// TODO !
}
/**
* @see org.apache.maven.execution.ExecutionListener#forkedProjectStarted(org.apache.maven.execution.ExecutionEvent)
*/
public void forkedProjectStarted( ExecutionEvent event )
{
// TODO !
}
/**
* @see org.apache.maven.execution.ExecutionListener#forkedProjectSucceeded(org.apache.maven.execution.ExecutionEvent)
*/
public void forkedProjectSucceeded( ExecutionEvent event )
{
// TODO !
}
/**
* @see org.apache.maven.execution.ExecutionListener#forkedProjectFailed(org.apache.maven.execution.ExecutionEvent)
*/
public void forkedProjectFailed( ExecutionEvent event )
{
// TODO !
}
}
public static boolean markAsSuccess;
private static final long serialVersionUID = 1L;
} |
package com.psddev.dari.db;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.psddev.dari.util.CompactMap;
import com.psddev.dari.util.ConversionException;
import com.psddev.dari.util.ConversionFunction;
import com.psddev.dari.util.Converter;
import com.psddev.dari.util.ErrorUtils;
import com.psddev.dari.util.LoadingCacheMap;
import com.psddev.dari.util.ObjectToIterable;
import com.psddev.dari.util.ObjectUtils;
import com.psddev.dari.util.StorageItem;
import com.psddev.dari.util.StringUtils;
import com.psddev.dari.util.TypeDefinition;
import com.psddev.dari.util.UuidUtils;
/** Represents the state of an object stored in the database. */
public class State implements Map<String, Object> {
public static final String ID_KEY = "_id";
public static final String TYPE_KEY = "_type";
public static final String LABEL_KEY = "_label";
private static final Logger LOGGER = LoggerFactory.getLogger(State.class);
/**
* {@linkplain Query#getOptions Query option} that contains the object
* whose fields are being resolved automatically.
*/
public static final String REFERENCE_RESOLVING_QUERY_OPTION = "dari.referenceResolving";
public static final String REFERENCE_FIELD_QUERY_OPTION = "dari.referenceField";
public static final String UNRESOLVED_TYPE_IDS_QUERY_OPTION = "dari.unresolvedTypeIds";
public static final String SUB_DATA_STATE_EXTRA_PREFIX = "dari.subDataState.";
private static final String ATOMIC_OPERATIONS_EXTRA = "dari.atomicOperations";
private static final String MODIFICATIONS_EXTRA = "dari.modifications";
private static final int STATUS_FLAG_OFFSET = 16;
private static final int STATUS_FLAG_MASK = -1 >>> STATUS_FLAG_OFFSET;
private static final int ALL_RESOLVED_FLAG = 1 << 0;
private static final int RESOLVE_TO_REFERENCE_ONLY_FLAG = 1 << 1;
private static final int RESOLVE_WITHOUT_CACHE = 1 << 2;
private static final int RESOLVE_USING_MASTER = 1 << 3;
private static final int RESOLVE_INVISIBLE = 1 << 4;
private static final ThreadLocal<List<Listener>> LISTENERS_LOCAL = new ThreadLocal<List<Listener>>();
private final Map<Class<?>, Object> linkedObjects = new CompactMap<Class<?>, Object>();
private Database database;
private UUID id;
private UUID typeId;
private final Map<String, Object> rawValues = new CompactMap<String, Object>();
private Map<String, Object> extras;
private Map<ObjectField, List<String>> errors;
private volatile int flags;
public static State getInstance(Object object) {
if (object == null) {
return null;
} else if (object instanceof State) {
return (State) object;
} else if (object instanceof Recordable) {
return ((Recordable) object).getState();
} else {
throw new IllegalArgumentException(String.format(
"Can't retrieve state from an instance of [%s]!",
object.getClass().getName()));
}
}
/**
* Links the given {@code object} to this state so that changes on
* either side are copied over.
*/
public void linkObject(Object object) {
if (object != null) {
linkedObjects.put(object.getClass(), object);
}
}
/**
* Unlinks the given {@code object} from this state so that changes
* on either side are no longer copied over.
*/
public void unlinkObject(Object object) {
if (object != null) {
linkedObjects.remove(object.getClass());
}
}
/**
* Returns the effective originating database.
*
* <p>This method will check the following:</p>
*
* <ul>
* <li>{@linkplain #getRealDatabase Real originating database}.</li>
* <li>{@linkplain Database.Static#getDefault Default database}.</li>
* <li>{@linkplain ObjectType#getSourceDatabase Source database}.</li>
* <li>
*
* @return Never {@code null}.
*/
public Database getDatabase() {
if (database == null) {
Database newDatabase = Database.Static.getDefault();
this.database = newDatabase;
ObjectType type = getType();
if (type != null) {
newDatabase = type.getSourceDatabase();
if (newDatabase != null) {
this.database = newDatabase;
}
}
}
return database;
}
/**
* Returns the real originating database.
*
* @return May be {@code null}.
*/
public Database getRealDatabase() {
return database;
}
/**
* Sets the originating database.
*
* @param database May be {@code null}.
*/
public void setDatabase(Database database) {
this.database = database;
}
/** Returns the unique ID. */
public UUID getId() {
if (id == null) {
setId(UuidUtils.createSequentialUuid());
}
return this.id;
}
/** Sets the unique ID. */
public void setId(UUID id) {
this.id = id;
}
/** Returns the type ID. */
public UUID getTypeId() {
if (typeId == null) {
UUID newTypeId = UuidUtils.ZERO_UUID;
if (!linkedObjects.isEmpty()) {
Database database = getDatabase();
if (database != null) {
ObjectType type = database.getEnvironment().getTypeByClass(linkedObjects.keySet().iterator().next());
if (type != null) {
newTypeId = type.getId();
}
}
}
typeId = newTypeId;
}
return typeId;
}
public UUID getVisibilityAwareTypeId() {
ObjectType type = getType();
if (type != null) {
updateVisibilities(getDatabase().getEnvironment().getIndexes());
updateVisibilities(type.getIndexes());
@SuppressWarnings("unchecked")
List<String> visibilities = (List<String>) get("dari.visibilities");
if (visibilities != null && !visibilities.isEmpty()) {
String field = visibilities.get(visibilities.size() - 1);
Object value = toSimpleValue(get(field), false, false);
if (value != null) {
byte[] typeId = UuidUtils.toBytes(getTypeId());
byte[] md5 = StringUtils.md5(field + "/" + value.toString().trim().toLowerCase(Locale.ENGLISH));
for (int i = 0, length = typeId.length; i < length; ++ i) {
typeId[i] ^= md5[i];
}
return UuidUtils.fromBytes(typeId);
}
}
}
return getTypeId();
}
private void updateVisibilities(List<ObjectIndex> indexes) {
@SuppressWarnings("unchecked")
List<String> visibilities = (List<String>) get("dari.visibilities");
for (ObjectIndex index : indexes) {
if (index.isVisibility()) {
String field = index.getField();
Object value = toSimpleValue(index.getValue(this), false, false);
if (value == null) {
if (visibilities != null) {
visibilities.remove(field);
if (visibilities.isEmpty()) {
remove("dari.visibilities");
}
}
} else {
if (visibilities == null) {
visibilities = new ArrayList<String>();
put("dari.visibilities", visibilities);
}
if (!visibilities.contains(field)) {
visibilities.add(field);
}
}
}
}
}
/** Sets the type ID. */
public void setTypeId(UUID typeId) {
this.typeId = typeId;
}
/** Returns the type. */
public ObjectType getType() {
ObjectType type = getDatabase().getEnvironment().getTypeById(getTypeId());
if (type == null) {
// During the bootstrapping process, the type for the root
// type is not available, so fake it here.
for (Object object : linkedObjects.values()) {
if (object instanceof ObjectType && getId().equals(getTypeId())) {
type = (ObjectType) object;
type.setObjectClassName(ObjectType.class.getName());
type.initialize();
}
break;
}
}
return type;
}
/**
* Sets the type. This method may also change the originating
* database based on the the given {@code type}.
*/
public void setType(ObjectType type) {
if (type == null) {
setTypeId(null);
} else {
setTypeId(type.getId());
setDatabase(type.getState().getDatabase());
}
}
/**
* Returns {@code true} if this state is visible (all visibility-indexed
* fields are {@code null}).
*/
public boolean isVisible() {
return ObjectUtils.isBlank(get("dari.visibilities"));
}
public ObjectField getField(String name) {
ObjectField field = getDatabase().getEnvironment().getField(name);
if (field == null) {
ObjectType type = getType();
if (type != null) {
field = type.getField(name);
}
}
return field;
}
/** Returns the status. */
public StateStatus getStatus() {
int statusFlag = flags >>> STATUS_FLAG_OFFSET;
for (StateStatus status : StateStatus.values()) {
if (statusFlag == status.getFlag()) {
return status;
}
}
return null;
}
/**
* Returns {@code true} if this state has never been saved to the
* database.
*/
public boolean isNew() {
return (flags >>> STATUS_FLAG_OFFSET) == 0;
}
private boolean checkStatus(StateStatus status) {
return ((flags >>> STATUS_FLAG_OFFSET) & status.getFlag()) > 0;
}
/**
* Returns {@code true} if this state was recently deleted from the
* database.
*/
public boolean isDeleted() {
return checkStatus(StateStatus.DELETED);
}
/**
* Returns {@code true} if this state only contains the reference
* to the object (ID and type ID).
*/
public boolean isReferenceOnly() {
return checkStatus(StateStatus.REFERENCE_ONLY);
}
/**
* Sets the status. This method will also clear all pending atomic
* operations and existing validation errors.
*/
public void setStatus(StateStatus status) {
flags &= STATUS_FLAG_MASK;
if (status != null) {
flags |= status.getFlag() << STATUS_FLAG_OFFSET;
}
getExtras().remove(ATOMIC_OPERATIONS_EXTRA);
if (errors != null) {
errors.clear();
}
}
/** Returns the map of all the fields values. */
public Map<String, Object> getValues() {
resolveReferences();
return this;
}
/** Sets the map of all the values. */
public void setValues(Map<String, Object> values) {
clear();
putAll(values);
}
/**
* Returns a map of all values converted to only simple types:
* {@code null}, {@link java.lang.Boolean}, {@link java.lang.Number},
* {@link java.lang.String}, {@link java.util.ArrayList}, or
* {@link CompactMap}.
*/
public Map<String, Object> getSimpleValues() {
return getSimpleValues(false);
}
public Map<String, Object> getSimpleValues(boolean withTypeNames) {
Map<String, Object> values = new CompactMap<String, Object>();
for (Map.Entry<String, Object> entry : getValues().entrySet()) {
String name = entry.getKey();
Object value = entry.getValue();
ObjectField field = getField(name);
if (field == null) {
values.put(name, toSimpleValue(value, false, withTypeNames));
} else if (value != null && !(value instanceof Metric)) {
values.put(name, toSimpleValue(value, field.isEmbedded(), withTypeNames));
}
}
values.put(StateValueUtils.ID_KEY, getId().toString());
if (withTypeNames && getType() != null) {
values.put(StateValueUtils.TYPE_KEY, getType().getInternalName());
} else {
values.put(StateValueUtils.TYPE_KEY, getTypeId().toString());
}
return values;
}
/**
* Similar to {@link #getSimpleValues()} but only returns those values
* with fields strictly defined on this State's type.
* @deprecated No replacement
* @see #getSimpleValues()
*/
@Deprecated
public Map<String, Object> getSimpleFieldedValues() {
Map<String, Object> values = new CompactMap<String, Object>();
for (Map.Entry<String, Object> e : getValues().entrySet()) {
String name = e.getKey();
ObjectField field = getField(name);
if (field != null) {
values.put(name, toSimpleValue(e.getValue(), field.isEmbedded(), false));
}
}
values.put(StateValueUtils.ID_KEY, getId().toString());
values.put(StateValueUtils.TYPE_KEY, getTypeId().toString());
return values;
}
/**
* Converts the given {@code value} into an instance of one of
* the simple types listed in {@link #getSimpleValues}.
*/
private static Object toSimpleValue(Object value, boolean isEmbedded, boolean withTypeNames) {
if (value == null) {
return null;
}
Iterable<Object> valueIterable = ObjectToIterable.iterable(value);
if (valueIterable != null) {
List<Object> list = new ArrayList<Object>();
for (Object item : valueIterable) {
list.add(toSimpleValue(item, isEmbedded, withTypeNames));
}
return list;
} else if (value instanceof Map) {
Map<String, Object> map = new CompactMap<String, Object>();
for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
Object key = entry.getKey();
if (key != null) {
map.put(key.toString(), toSimpleValue(entry.getValue(), isEmbedded, withTypeNames));
}
}
return map;
} else if (value instanceof Query) {
return ((Query<?>) value).getState().getSimpleValues(withTypeNames);
} else if (value instanceof Metric) {
return null;
} else if (value instanceof Recordable) {
State valueState = ((Recordable) value).getState();
if (valueState.isNew()) {
ObjectType type;
if (isEmbedded ||
((type = valueState.getType()) != null &&
type.isEmbedded())) {
return valueState.getSimpleValues(withTypeNames);
}
}
Map<String, Object> map = new CompactMap<String, Object>();
map.put(StateValueUtils.REFERENCE_KEY, valueState.getId().toString());
if (withTypeNames && valueState.getType() != null) {
map.put(StateValueUtils.TYPE_KEY, valueState.getType().getInternalName());
} else {
map.put(StateValueUtils.TYPE_KEY, valueState.getTypeId().toString());
}
return map;
} else if (value instanceof Boolean ||
value instanceof Number ||
value instanceof String) {
return value;
} else if (value instanceof Character ||
value instanceof CharSequence ||
value instanceof String ||
value instanceof URI ||
value instanceof URL ||
value instanceof UUID) {
return value.toString();
} else if (value instanceof Date) {
return ((Date) value).getTime();
} else if (value instanceof Enum) {
return ((Enum<?>) value).name();
} else {
return toSimpleValue(ObjectUtils.to(Map.class, value), isEmbedded, withTypeNames);
}
}
/**
* Returns the value associated with the given {@code path}.
*
* @param path If {@code null}, returns {@code null}.
* @return May be {@code null}.
*/
public Object getByPath(String path) {
if (path == null) {
return null;
}
DatabaseEnvironment environment = getDatabase().getEnvironment();
Object value = this;
KEY: for (String key; path != null;) {
int slashAt = path.indexOf('/');
if (slashAt > -1) {
key = path.substring(0, slashAt);
path = path.substring(slashAt + 1);
} else {
key = path;
path = null;
}
if (key.indexOf('.') > -1 &&
environment.getTypeByName(key) != null) {
continue;
}
if (value instanceof Recordable) {
value = ((Recordable) value).getState();
}
if (key.endsWith("()")) {
if (value instanceof State) {
key = key.substring(0, key.length() - 2);
Class<?> keyClass = null;
int dotAt = key.lastIndexOf('.');
if (dotAt > -1) {
keyClass = ObjectUtils.getClassByName(key.substring(0, dotAt));
key = key.substring(dotAt + 1);
}
if (keyClass == null) {
value = ((State) value).getOriginalObject();
keyClass = value.getClass();
} else {
value = ((State) value).as(keyClass);
}
for (Class<?> c = keyClass; c != null; c = c.getSuperclass()) {
try {
Method keyMethod = c.getDeclaredMethod(key);
keyMethod.setAccessible(false);
value = keyMethod.invoke(value);
continue KEY;
} catch (IllegalAccessException error) {
throw new IllegalStateException(error);
} catch (InvocationTargetException error) {
ErrorUtils.rethrow(error.getCause());
} catch (NoSuchMethodException error) {
// Try to find the method in the super class.
}
}
}
return null;
}
if (value instanceof State) {
State valueState = (State) value;
if (ID_KEY.equals(key)) {
value = valueState.getId();
} else if (TYPE_KEY.equals(key)) {
value = valueState.getType();
} else if (LABEL_KEY.equals(key)) {
value = valueState.getLabel();
} else {
value = valueState.get(key);
}
} else if (value instanceof Map) {
value = ((Map<?, ?>) value).get(key);
} else if (value instanceof List) {
Integer index = ObjectUtils.to(Integer.class, key);
if (index != null) {
List<?> list = (List<?>) value;
int listSize = list.size();
if (index < 0) {
index += listSize;
}
if (index >= 0 && index < listSize) {
value = list.get(index);
continue;
}
}
return null;
} else {
return null;
}
}
return value;
}
public Map<String, Object> getRawValues() {
return rawValues;
}
/**
* Returns the field associated with the given {@code name} as an
* instance of the given {@code returnType}. This version of get will
* not trigger reference resolution which avoids a round-trip to the
* database.
*/
public Object getRawValue(String name) {
Object value = rawValues;
for (String part : StringUtils.split(name, "/")) {
if (value == null) {
break;
} else if (value instanceof Recordable) {
value = ((Recordable) value).getState().getValue(part);
} else if (value instanceof Map) {
value = ((Map<?, ?>) value).get(part);
} else if (value instanceof List) {
Integer index = ObjectUtils.to(Integer.class, part);
if (index != null) {
List<?> list = (List<?>) value;
if (index >= 0 && index < list.size()) {
value = list.get(index);
continue;
}
}
value = null;
break;
}
}
return value;
}
/** Puts the given field value at given name. */
@SuppressWarnings("unchecked")
public void putByPath(String name, Object value) {
Map<String, Object> parent = getValues();
String[] parts = StringUtils.split(name, "/");
int last = parts.length - 1;
for (int i = 0; i < last; i ++) {
String part = parts[i];
Object child = parent.get(part);
if (child instanceof Recordable) {
parent = ((Recordable) child).getState().getValues();
} else {
if (!(child instanceof Map)) {
child = new CompactMap<String, Object>();
parent.put(part, child);
}
parent = (Map<String, Object>) child;
}
}
parent.put(parts[last], value);
}
/** Returns the indexes for the ObjectType returned by {@link #getType()}
* as well as any embedded indexes on this State. */
public Set<ObjectIndex> getIndexes() {
Set<ObjectIndex> indexes = new LinkedHashSet<ObjectIndex>();
ObjectType type = getType();
if (type != null) {
indexes.addAll(type.getIndexes());
for (Map.Entry<String, Object> entry : getValues().entrySet()) {
ObjectField field = getField(entry.getKey());
if (field != null) {
getEmbeddedIndexes(indexes, null, field, entry.getValue());
}
}
}
return indexes;
}
/** Recursively gathers all the embedded Indexes for this State object. */
private void getEmbeddedIndexes(Set<ObjectIndex> indexes,
String parentFieldName,
ObjectField field, Object fieldValue) {
if (fieldValue instanceof Recordable) {
State state = State.getInstance(fieldValue);
ObjectType type = state.getType();
if (type == null) {
return;
}
if (field.isEmbedded() || type.isEmbedded()) {
for (ObjectIndex i : type.getIndexes()) {
ObjectIndex index = new ObjectIndex(getType(), null);
StringBuilder builder = new StringBuilder();
StringBuilder builder2 = new StringBuilder();
if (parentFieldName != null) {
builder.append(parentFieldName).append('/');
builder2.append(parentFieldName).append('/');
}
builder.append(field.getInternalName()).append('/');
builder2.append(field.getInternalName()).append('/');
builder.append(i.getField());
builder2.append(i.getUniqueName());
String fieldName = builder.toString();
index.setField(fieldName);
index.setType(i.getType());
index.setUnique(i.isUnique());
// get the declaring class of the first level field name
int slashAt = fieldName.indexOf('/');
String firstLevelFieldName = fieldName.substring(0, slashAt);
ObjectField firstLevelField = getField(firstLevelFieldName);
if (firstLevelField != null && firstLevelField.getJavaDeclaringClassName() != null) {
index.setJavaDeclaringClassName(firstLevelField.getJavaDeclaringClassName());
} else {
index.setJavaDeclaringClassName(getType().getObjectClassName());
}
indexes.add(index);
ObjectIndex index2 = new ObjectIndex(getType(), null);
index2.setName(builder2.toString());
index2.setField(index.getField());
index2.setType(index.getType());
index2.setUnique(index.isUnique());
index2.setJavaDeclaringClassName(index.getJavaDeclaringClassName());
indexes.add(index2);
}
if (parentFieldName == null) {
parentFieldName = field.getInternalName();
} else {
parentFieldName += "/" + field.getInternalName();
}
Map<String, Object> values = state.getValues();
for (Map.Entry<String, Object> entry : values.entrySet()) {
ObjectField objectField = state.getField(entry.getKey());
if (objectField != null) {
getEmbeddedIndexes(indexes, parentFieldName,
objectField, entry.getValue());
}
}
}
} else if (fieldValue instanceof Map) {
for (Map.Entry<?, ?> entry : ((Map<?, ?>) fieldValue).entrySet()) {
getEmbeddedIndexes(indexes, parentFieldName, field, entry.getValue());
}
} else if (fieldValue instanceof Iterable) {
for (Object listItem : (Iterable<?>) fieldValue) {
getEmbeddedIndexes(indexes, parentFieldName, field, listItem);
}
}
}
/**
* Returns an unmodifiable list of all the atomic operations pending on
* this record.
*/
public List<AtomicOperation> getAtomicOperations() {
Map<String, Object> extras = getExtras();
@SuppressWarnings("unchecked")
List<AtomicOperation> ops = (List<AtomicOperation>) extras.get(ATOMIC_OPERATIONS_EXTRA);
if (ops == null) {
ops = new ArrayList<AtomicOperation>();
extras.put(ATOMIC_OPERATIONS_EXTRA, ops);
}
return ops;
}
// Queues up an atomic operation and updates the internal state.
private void queueAtomicOperation(AtomicOperation operation) {
operation.execute(this);
getAtomicOperations().add(operation);
}
/**
* Increments the field associated with the given {@code name} by the
* given {@code value}. If the field contains a non-numeric value, it
* will be set to 0 first.
*/
public void incrementAtomically(String name, double value) {
queueAtomicOperation(new AtomicOperation.Increment(name, value));
}
/**
* Decrements the field associated with the given {@code name} by the
* given {@code value}. If the field contains a non-numeric value, it
* will be set to 0 first.
*/
public void decrementAtomically(String name, double value) {
incrementAtomically(name, -value);
}
/**
* Adds the given {@code value} to the collection field associated with
* the given {@code name}.
*/
public void addAtomically(String name, Object value) {
queueAtomicOperation(new AtomicOperation.Add(name, value));
}
/**
* Removes all instances of the given {@code value} in the collection
* field associated with the given {@code name}.
*/
public void removeAtomically(String name, Object value) {
queueAtomicOperation(new AtomicOperation.Remove(name, value));
}
/**
* Replaces the field value at the given {@code name} with the given
* {@code value}. If the object changes in the database before
* {@link #save()} is called, {@link AtomicOperation.ReplacementException}
* will be thrown.
*/
public void replaceAtomically(String name, Object value) {
queueAtomicOperation(new AtomicOperation.Replace(name, getValue(name), value));
}
/**
* Puts the given {@code value} into the field associated with the
* given {@code name} atomically.
*/
public void putAtomically(String name, Object value) {
queueAtomicOperation(new AtomicOperation.Put(name, value));
}
/** Returns all the fields with validation errors from this record. */
public Set<ObjectField> getErrorFields() {
return errors != null ?
Collections.unmodifiableSet(errors.keySet()) :
Collections.<ObjectField>emptySet();
}
/**
* Returns all the validation errors for the given field from this
* record.
*/
public List<String> getErrors(ObjectField field) {
if (errors != null) {
List<String> messages = errors.get(field);
if (messages != null && !messages.isEmpty()) {
return Collections.unmodifiableList(messages);
}
}
return Collections.emptyList();
}
/** Returns true if this record has any validation errors. */
public boolean hasAnyErrors() {
if (errors != null) {
for (List<String> messages : errors.values()) {
if (messages != null && !messages.isEmpty()) {
return true;
}
}
}
ObjectType type = getType();
if (type != null) {
for (ObjectField field : type.getFields()) {
if (hasErrorsForValue(get(field.getInternalName()), field.isEmbedded())) {
return true;
}
}
}
return false;
}
private boolean hasErrorsForValue(Object value, boolean embedded) {
if (value instanceof Map) {
value = ((Map<?, ?>) value).values();
}
if (value instanceof Iterable) {
for (Object item : (Iterable<?>) value) {
if (hasErrorsForValue(item, embedded)) {
return true;
}
}
} else if (value instanceof Recordable) {
State valueState = ((Recordable) value).getState();
if (embedded) {
if (valueState.hasAnyErrors()) {
return true;
}
} else {
ObjectType valueType = valueState.getType();
if (valueType != null && valueType.isEmbedded() && valueState.hasAnyErrors()) {
return true;
}
}
}
return false;
}
/**
* Returns true if the given field in this record has any validation
* errors.
*/
public boolean hasErrors(ObjectField field) {
return errors != null && errors.get(field).size() > 0;
}
public void clearAllErrors() {
errors = null;
}
/** Returns a modifiable map of all the extras values from this state. */
public Map<String, Object> getExtras() {
if (extras == null) {
extras = new CompactMap<String, Object>();
}
return extras;
}
/**
* Returns the extra value associated with the given {@code name} from
* this state.
*/
public Object getExtra(String name) {
return extras != null ? extras.get(name) : null;
}
public void addError(ObjectField field, String message) {
if (errors == null) {
errors = new CompactMap<ObjectField, List<String>>();
}
List<String> messages = errors.get(field);
if (messages == null) {
messages = new ArrayList<String>();
errors.put(field, messages);
}
messages.add(message);
}
public boolean isResolveToReferenceOnly() {
return (flags & RESOLVE_TO_REFERENCE_ONLY_FLAG) != 0;
}
public void setResolveToReferenceOnly(boolean resolveToReferenceOnly) {
if (resolveToReferenceOnly) {
flags |= RESOLVE_TO_REFERENCE_ONLY_FLAG;
} else {
flags &= ~RESOLVE_TO_REFERENCE_ONLY_FLAG;
}
}
public boolean isResolveUsingCache() {
return (flags & RESOLVE_WITHOUT_CACHE) == 0;
}
public void setResolveUsingCache(boolean resolveUsingCache) {
if (resolveUsingCache) {
flags &= ~RESOLVE_WITHOUT_CACHE;
} else {
flags |= RESOLVE_WITHOUT_CACHE;
}
}
public boolean isResolveUsingMaster() {
return (flags & RESOLVE_USING_MASTER) != 0;
}
public void setResolveUsingMaster(boolean resolveUsingMaster) {
if (resolveUsingMaster) {
flags |= RESOLVE_USING_MASTER;
} else {
flags &= ~RESOLVE_USING_MASTER;
}
}
public boolean isResolveInvisible() {
return (flags & RESOLVE_INVISIBLE) != 0;
}
public void setResolveInvisible(boolean resolveInvisible) {
if (resolveInvisible) {
flags |= RESOLVE_INVISIBLE;
} else {
flags &= ~RESOLVE_INVISIBLE;
}
}
/**
* Returns a descriptive label for this state.
*/
public String getLabel() {
Object object = getOriginalObjectOrNull();
String label = null;
if (object instanceof Record) {
try {
label = ((Record) object).getLabel();
} catch (RuntimeException error) {
// Ignore errors from a bad implementation of #getLabel
// and fall back to the default label algorithm.
}
}
return ObjectUtils.isBlank(label) ?
getDefaultLabel() :
label;
}
// To check for circular references in resolving labels.
private static final ThreadLocal<Map<UUID, String>> LABEL_CACHE = new ThreadLocal<Map<UUID, String>>();
/**
* Returns the default, descriptive label for this state.
* Fields specified in {@link Recordable.LabelFields} are used to
* construct it. If the referenced field value contains a state,
* it may call itself, but not more than once per state.
*/
protected String getDefaultLabel() {
ObjectType type = getType();
if (type != null) {
StringBuilder label = new StringBuilder();
for (String field : type.getLabelFields()) {
Object value = getValue(field);
if (value != null) {
String valueString;
if (value instanceof Recordable) {
State valueState = ((Recordable) value).getState();
UUID valueId = valueState.getId();
Map<UUID, String> cache = LABEL_CACHE.get();
boolean isFirst = false;
if (cache == null) {
cache = new HashMap<UUID, String>();
LABEL_CACHE.set(cache);
isFirst = true;
}
try {
if (cache.containsKey(valueId)) {
valueString = cache.get(valueId);
if (valueString == null) {
valueString = valueId.toString();
}
} else {
cache.put(valueId, null);
valueString = valueState.getLabel();
cache.put(valueId, valueString);
}
} finally {
if (isFirst) {
LABEL_CACHE.remove();
}
}
} else if (value instanceof Iterable<?>) {
StringBuilder iterableLabel = new StringBuilder();
iterableLabel.append('[');
for (Object item : (Iterable<?>) value) {
if (item instanceof Recordable) {
iterableLabel.append(((Recordable) item).getState().getLabel());
} else {
iterableLabel.append(item.toString());
}
iterableLabel.append(", ");
}
if (iterableLabel.length() > 2) {
iterableLabel.setLength(iterableLabel.length() - 2);
}
iterableLabel.append(']');
valueString = iterableLabel.toString();
} else {
valueString = value.toString();
}
if (valueString.length() > 0) {
label.append(valueString);
label.append(' ');
}
}
}
if (label.length() > 0) {
label.setLength(label.length() - 1);
return label.toString();
}
}
return getId().toString();
}
/** Returns a storage item that can be used to preview this state. */
public StorageItem getPreview() {
ObjectType type = getType();
if (type != null) {
String field = type.getPreviewField();
if (!ObjectUtils.isBlank(field)) {
return (StorageItem) getValue(field);
}
}
return null;
}
/**
* Returns the label that identifies the current visibility in effect.
*
* @return May be {@code null}.
* @see VisibilityLabel
*/
public String getVisibilityLabel() {
@SuppressWarnings("unchecked")
List<String> visibilities = (List<String>) get("dari.visibilities");
if (visibilities != null && !visibilities.isEmpty()) {
String fieldName = visibilities.get(visibilities.size() - 1);
ObjectField field = getField(fieldName);
if (field != null) {
Class<?> fieldDeclaring = ObjectUtils.getClassByName(field.getJavaDeclaringClassName());
if (fieldDeclaring != null &&
VisibilityLabel.class.isAssignableFrom(fieldDeclaring)) {
return ((VisibilityLabel) as(fieldDeclaring)).createVisibilityLabel(field);
}
}
return ObjectUtils.to(String.class, get(fieldName));
}
return null;
}
public void prefetch() {
prefetch(getValues());
}
private void prefetch(Object object) {
if (object instanceof Map) {
for (Object item : ((Map<?, ?>) object).values()) {
prefetch(item);
}
} else if (object instanceof Iterable) {
for (Object item : (Iterable<?>) object) {
prefetch(item);
}
}
}
/**
* Returns an instance of the given {@code modificationClass} linked
* to this state.
*/
public <T> T as(Class<T> objectClass) {
@SuppressWarnings("unchecked")
T object = (T) linkedObjects.get(objectClass);
if (object == null) {
object = TypeDefinition.getInstance(objectClass).newInstance();
((Recordable) object).setState(this);
copyRawValuesToJavaFields(object);
}
return object;
}
/**
* Fires the given trigger on all objects (the original and the
* modifications) associated with this state.
*
* @param trigger Can't be {@code null}.
*/
@SuppressWarnings("unchecked")
public void fireTrigger(Trigger trigger) {
// Global modifications.
for (ObjectType modType : getDatabase().getEnvironment().getTypesByGroup(Modification.class.getName())) {
if (modType.isAbstract()) {
continue;
}
Class<?> modClass = modType.getObjectClass();
if (modClass != null &&
Modification.class.isAssignableFrom(modClass) &&
Modification.Static.getModifiedClasses((Class<? extends Modification<?>>) modClass).contains(Object.class)) {
fireModificationTrigger(trigger, modClass);
}
}
ObjectType type = getType();
if (type == null ||
type.isAbstract()) {
return;
}
// Type-specific modifications.
TYPE_CHANGE: while (true) {
for (String modClassName : type.getModificationClassNames()) {
Class<?> modClass = ObjectUtils.getClassByName(modClassName);
if (modClass != null) {
fireModificationTrigger(trigger, modClass);
ObjectType newType = getType();
if (!type.equals(newType)) {
type = newType;
continue TYPE_CHANGE;
}
}
}
break;
}
// Embedded objects.
for (ObjectField field : type.getFields()) {
fireValueTrigger(trigger, get(field.getInternalName()), field.isEmbedded());
}
}
private void fireModificationTrigger(Trigger trigger, Class<?> modClass) {
Object modObject;
try {
modObject = as(modClass);
} catch (RuntimeException ex) {
return;
}
LOGGER.debug(
"Firing trigger [{}] from [{}] on [{}]",
new Object[] { trigger, modClass.getName(), State.getInstance(modObject) });
trigger.execute(modObject);
}
private void fireValueTrigger(Trigger trigger, Object value, boolean embedded) {
if (value instanceof Map) {
value = ((Map<?, ?>) value).values();
}
if (value instanceof Iterable) {
for (Object item : (Iterable<?>) value) {
fireValueTrigger(trigger, item, embedded);
}
} else if (value instanceof Recordable) {
State valueState = ((Recordable) value).getState();
if (embedded) {
valueState.fireTrigger(trigger);
} else {
ObjectType valueType = valueState.getType();
if (valueType != null && valueType.isEmbedded()) {
valueState.fireTrigger(trigger);
}
}
}
}
/**
* Returns the original object, which is an instance of the Java class
* associated with the type.
*
* @return May be {@code null}.
*/
public Object getOriginalObjectOrNull() {
ObjectType type = getType();
if (type != null) {
Class<?> objectClass = type.getObjectClass();
if (objectClass == null) {
objectClass = Record.class;
}
for (Object object : linkedObjects.values()) {
if (objectClass.equals(object.getClass())) {
return object;
}
}
return as(objectClass);
}
return null;
}
public Object getOriginalObject() {
Object object = getOriginalObjectOrNull();
if (object != null) {
return object;
} else {
throw new IllegalStateException(String.format(
"No original object associated with [%s]!",
getId()));
}
}
/** Returns a set of all objects that can be used with this state. */
@SuppressWarnings("all")
public Collection<Record> getObjects() {
List<Record> objects = new ArrayList<Record>();
objects.addAll((Collection) linkedObjects.values());
return objects;
}
public void beforeFieldGet(String name) {
List<Listener> listeners = LISTENERS_LOCAL.get();
if (listeners != null && !listeners.isEmpty()) {
for (Listener listener : listeners) {
listener.beforeFieldGet(this, name);
}
}
}
/**
* Resolves the reference possibly stored in the given {@code field}.
* This method doesn't need to be used directly in typical cases, because
* it will be called automatically by {@link LazyLoadEnhancer}.
*
* @param field If {@code null}, resolves all references.
*/
public void resolveReference(String field) {
if ((flags & ALL_RESOLVED_FLAG) != 0) {
return;
}
synchronized (this) {
if ((flags & ALL_RESOLVED_FLAG) != 0) {
return;
}
flags |= ALL_RESOLVED_FLAG;
if (linkedObjects.isEmpty()) {
return;
}
Object object = linkedObjects.values().iterator().next();
Map<UUID, Object> references = StateValueUtils.resolveReferences(getDatabase(), object, rawValues.values(), field);
Map<String, Object> resolved = new HashMap<String, Object>();
resolveMetricReferences(resolved);
for (Map.Entry<? extends String, ? extends Object> e : rawValues.entrySet()) {
UUID id = StateValueUtils.toIdIfReference(e.getValue());
if (id != null) {
resolved.put(e.getKey(), references.get(id));
}
}
for (Map.Entry<String, Object> e : resolved.entrySet()) {
put(e.getKey(), e.getValue());
}
}
}
/**
* Instantiate all Metric objects.
*/
private void resolveMetricReferences(Map<String, Object> map) {
for (Object obj : linkedObjects.values()) {
ObjectType type = getDatabase().getEnvironment().getTypeByClass(obj.getClass());
if (type != null) {
for (ObjectField metricField : type.getMetricFields()) {
map.put(metricField.getInternalName(), new Metric(this, metricField));
}
}
}
for (ObjectField metricField : getDatabase().getEnvironment().getMetricFields()) {
map.put(metricField.getInternalName(), new Metric(this, metricField));
}
}
/**
* Resolves all references to other objects. This method doesn't need to
* be used directly in typical cases, because it will be called
* automatically by {@link LazyLoadEnhancer}.
*/
public void resolveReferences() {
resolveReference(null);
}
/**
* Returns {@code true} if the field values in this state is valid.
* The validation rules are typically read from annotations such as
* {@link Recordable.FieldRequired}.
*/
public boolean validate() {
ObjectType type = getType();
if (type != null) {
for (ObjectField field : type.getFields()) {
field.validate(this);
validateValue(get(field.getInternalName()), field.isEmbedded());
}
}
DatabaseEnvironment environment = getDatabase().getEnvironment();
for (ObjectField field : environment.getFields()) {
field.validate(this);
}
return !hasAnyErrors();
}
private void validateValue(Object value, boolean embedded) {
if (value instanceof Map) {
value = ((Map<?, ?>) value).values();
}
if (value instanceof Iterable) {
for (Object item : (Iterable<?>) value) {
validateValue(item, embedded);
}
} else if (value instanceof Recordable) {
State valueState = ((Recordable) value).getState();
if (embedded) {
valueState.validate();
} else {
ObjectType valueType = valueState.getType();
if (valueType != null && valueType.isEmbedded()) {
valueState.validate();
}
}
}
}
private void copyJavaFieldsToRawValues() {
DatabaseEnvironment environment = getDatabase().getEnvironment();
for (Object object : linkedObjects.values()) {
Class<?> objectClass = object.getClass();
ObjectType type = environment.getTypeByClass(objectClass);
if (type == null) {
continue;
}
for (ObjectField field : type.getFields()) {
Field javaField = field.getJavaField(objectClass);
if (javaField == null ||
!javaField.getDeclaringClass().getName().equals(field.getJavaDeclaringClassName())) {
continue;
}
try {
rawValues.put(field.getInternalName(), javaField.get(object));
} catch (IllegalAccessException ex) {
throw new IllegalStateException(ex);
}
}
}
}
void copyRawValuesToJavaFields(Object object) {
Class<?> objectClass = object.getClass();
ObjectType type = getDatabase().getEnvironment().getTypeByClass(objectClass);
if (type == null) {
return;
}
for (ObjectField field : type.getFields()) {
String key = field.getInternalName();
Object value = StateValueUtils.toJavaValue(getDatabase(), object, field, field.getInternalType(), rawValues.get(key));
rawValues.put(key, value);
Field javaField = field.getJavaField(objectClass);
if (javaField != null) {
setJavaField(field, javaField, object, key, value);
}
}
}
private static final Converter CONVERTER; static {
CONVERTER = new Converter();
CONVERTER.setThrowError(true);
CONVERTER.putAllStandardFunctions();
CONVERTER.putInheritableFunction(Query.class, Query.class, new QueryToQuery());
}
@SuppressWarnings("rawtypes")
private static class QueryToQuery implements ConversionFunction<Query, Query> {
@Override
public Query convert(Converter converter, Type returnType, Query query) {
return query;
}
}
private void setJavaField(
ObjectField field,
Field javaField,
Object object,
String key,
Object value) {
if (!javaField.getDeclaringClass().getName().equals(field.getJavaDeclaringClassName())) {
return;
}
try {
Type javaFieldType = javaField.getGenericType();
if ((!javaField.getType().isPrimitive() &&
!Number.class.isAssignableFrom(javaField.getType())) &&
(javaFieldType instanceof Class ||
((value instanceof StateValueList ||
value instanceof StateValueMap ||
value instanceof StateValueSet) &&
ObjectField.RECORD_TYPE.equals(field.getInternalItemType())))) {
try {
javaField.set(object, value);
return;
} catch (IllegalArgumentException error) {
// Ignore since it will be retried below.
}
}
try {
if (javaFieldType instanceof TypeVariable) {
javaField.set(object, value);
} else if (javaFieldType instanceof Class &&
((Class<?>) javaFieldType).isPrimitive()) {
javaField.set(object, ObjectUtils.to(javaFieldType, value));
} else {
javaField.set(object, CONVERTER.convert(javaFieldType, value));
}
} catch (RuntimeException error) {
Throwable cause;
if (error instanceof ConversionException) {
cause = error.getCause();
if (cause == null) {
cause = error;
}
} else {
cause = error;
}
rawValues.put("dari.trash." + key, value);
rawValues.put("dari.trashError." + key, cause.getClass().getName());
rawValues.put("dari.trashErrorMessage." + key, cause.getMessage());
}
} catch (IllegalAccessException error) {
throw new IllegalStateException(error);
}
}
@Override
public void clear() {
rawValues.clear();
DatabaseEnvironment environment = getDatabase().getEnvironment();
for (Object object : linkedObjects.values()) {
Class<?> objectClass = object.getClass();
ObjectType type = environment.getTypeByClass(objectClass);
if (type == null) {
continue;
}
for (ObjectField field : type.getFields()) {
Field javaField = field.getJavaField(objectClass);
if (javaField == null) {
continue;
}
try {
javaField.set(object, ObjectUtils.to(javaField.getGenericType(), null));
} catch (IllegalAccessException ex) {
throw new IllegalStateException(ex);
}
}
}
}
@Override
public boolean containsKey(Object key) {
return rawValues.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
copyJavaFieldsToRawValues();
return rawValues.containsKey(value);
}
@Override
public Set<Map.Entry<String, Object>> entrySet() {
copyJavaFieldsToRawValues();
return rawValues.entrySet();
}
@Override
public Object get(Object key) {
if (!(key instanceof String)) {
return null;
}
resolveReferences();
for (Object object : linkedObjects.values()) {
Class<?> objectClass = object.getClass();
ObjectType type = getDatabase().getEnvironment().getTypeByClass(objectClass);
if (type == null) {
continue;
}
ObjectField field = type.getField((String) key);
if (field == null) {
continue;
}
Field javaField = field.getJavaField(objectClass);
if (javaField == null) {
continue;
}
Object value;
try {
value = javaField.get(object);
} catch (IllegalAccessException ex) {
throw new IllegalStateException(ex);
}
rawValues.put(field.getInternalName(), value);
return value;
}
return rawValues.get(key);
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public Set<String> keySet() {
return rawValues.keySet();
}
@Override
public Object put(String key, Object value) {
if (key == null) {
return null;
}
if (key.startsWith("_")) {
if (key.equals(StateValueUtils.ID_KEY)) {
setId(ObjectUtils.to(UUID.class, value));
} else if (key.equals(StateValueUtils.TYPE_KEY)) {
UUID valueTypeId = ObjectUtils.to(UUID.class, value);
if (valueTypeId != null) {
setTypeId(valueTypeId);
} else {
if (value != null) {
ObjectType valueType = getDatabase().getEnvironment().getTypeByName(ObjectUtils.to(String.class, value));
if (valueType != null) {
setTypeId(valueType.getId());
}
}
}
}
return null;
}
boolean first = true;
for (Object object : linkedObjects.values()) {
ObjectField field = State.getInstance(object).getField(key);
if (first) {
value = StateValueUtils.toJavaValue(getDatabase(), object, field, field != null ? field.getInternalType() : null, value);
first = false;
}
if (field != null) {
Field javaField = field.getJavaField(object.getClass());
if (javaField != null) {
setJavaField(field, javaField, object, key, value);
}
}
}
return rawValues.put(key, value);
}
@Override
public void putAll(Map<? extends String, ? extends Object> map) {
if (!linkedObjects.isEmpty()) {
Object object = linkedObjects.values().iterator().next();
if (object != null && getType() != null && getType().isLazyLoaded()) {
for (Map.Entry<? extends String, ? extends Object> e : map.entrySet()) {
String key = e.getKey();
Object value = e.getValue();
if (StateValueUtils.toIdIfReference(value) != null) {
rawValues.put(key, value);
} else {
put(key, value);
}
}
Map<String, Object> metricObjects = new HashMap<String, Object>();
resolveMetricReferences(metricObjects);
for (Map.Entry<? extends String, ? extends Object> e : metricObjects.entrySet()) {
put(e.getKey(), e.getValue());
}
flags &= ~ALL_RESOLVED_FLAG;
return;
} else {
rawValues.putAll(map);
resolveReferences();
}
}
for (Map.Entry<? extends String, ? extends Object> e : map.entrySet()) {
put(e.getKey(), e.getValue());
}
}
@Override
public Object remove(Object key) {
if (key instanceof String) {
Object oldValue = put((String) key, null);
rawValues.remove(key);
return oldValue;
} else {
return null;
}
}
@Override
public int size() {
return rawValues.size() + 2;
}
@Override
public Collection<Object> values() {
copyJavaFieldsToRawValues();
return rawValues.values();
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof State) {
State otherState = (State) other;
return getId().equals(otherState.getId());
} else {
return false;
}
}
@Override
public int hashCode() {
return getId().hashCode();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{database=").append(getDatabase());
sb.append(", status=").append(getStatus());
sb.append(", id=").append(getId());
sb.append(", typeId=").append(getTypeId());
sb.append(", simpleValues=").append(getSimpleValues());
sb.append(", extras=").append(extras);
sb.append(", errors=").append(errors);
sb.append('}');
return sb.toString();
}
public Map<String, Object> getAs() {
@SuppressWarnings("unchecked")
Map<String, Object> as = (Map<String, Object>) getExtras().get(MODIFICATIONS_EXTRA);
if (as == null) {
as = new LoadingCacheMap<String, Object>(String.class, CacheBuilder.
newBuilder().
<String, Object>build(new CacheLoader<String, Object>() {
@Override
public Object load(String modificationClassName) {
Class<?> modificationClass = ObjectUtils.getClassByName(modificationClassName);
if (modificationClass != null) {
return as(modificationClass);
} else {
throw new IllegalArgumentException(String.format(
"[%s] isn't a valid class name!", modificationClassName));
}
}
}));
extras.put(MODIFICATIONS_EXTRA, as);
}
return as;
}
/** @see Database#beginWrites() */
public boolean beginWrites() {
return getDatabase().beginWrites();
}
/** @see Database#commitWrites() */
public boolean commitWrites() {
return getDatabase().commitWrites();
}
/** @see Database#endWrites() */
public boolean endWrites() {
return getDatabase().endWrites();
}
/**
* {@linkplain Database#save Saves} this state to the
* {@linkplain #getDatabase originating database}.
*/
public void save() {
getDatabase().save(this);
}
/**
* Saves this state {@linkplain Database#beginIsolatedWrites immediately}
* to the {@linkplain #getDatabase originating database}.
*/
public void saveImmediately() {
Database database = getDatabase();
database.beginIsolatedWrites();
try {
database.save(this);
database.commitWrites();
} finally {
database.endWrites();
}
}
/**
* Saves this state {@linkplain Database#commitWritesEventually eventually}
* to the {@linkplain #getDatabase originating database}.
*/
public void saveEventually() {
Database database = getDatabase();
database.beginWrites();
try {
database.save(this);
database.commitWritesEventually();
} finally {
database.endWrites();
}
}
/**
* {@linkplain Database#saveUnsafely Saves} this state to the
* {@linkplain #getDatabase originating database} without validating
* the data.
*/
public void saveUnsafely() {
getDatabase().saveUnsafely(this);
}
public void saveUniquely() {
ObjectType type = getType();
if (type == null) {
throw new IllegalStateException("No type!");
}
Query<?> query = Query.fromType(type).noCache().master();
for (ObjectIndex index : type.getIndexes()) {
if (index.isUnique()) {
for (String field : index.getFields()) {
Object value = get(field);
query.and(field + " = ?", value != null ? value : Query.MISSING_VALUE);
}
}
}
if (query.getPredicate() == null) {
throw new IllegalStateException("No unique indexes!");
}
Exception lastError = null;
for (int i = 0; i < 10; ++ i) {
Object object = query.first();
if (object != null) {
setValues(State.getInstance(object).getValues());
return;
} else {
try {
saveImmediately();
return;
} catch (Exception error) {
lastError = error;
}
}
}
ErrorUtils.rethrow(lastError);
}
/**
* {@linkplain Database#index Indexes} this state data in the
* {@linkplain #getDatabase originating database}.
*/
public void index() {
getDatabase().index(this);
}
/**
* {@linkplain Database#delete Deletes} this state from the
* {@linkplain #getDatabase originating database}.
*/
public void delete() {
getDatabase().delete(this);
}
/**
* Deletes this state {@linkplain Database#beginIsolatedWrites immediately}
* from the {@linkplain #getDatabase originating database}.
*/
public void deleteImmediately() {
Database database = getDatabase();
database.beginIsolatedWrites();
try {
database.delete(this);
database.commitWrites();
} finally {
database.endWrites();
}
}
public abstract static class Listener {
public void beforeFieldGet(State state, String name) {
}
}
/** {@link State} utility methods. */
public static final class Static {
public static void addListener(Listener listener) {
List<Listener> listeners = LISTENERS_LOCAL.get();
if (listeners == null) {
listeners = new ArrayList<Listener>();
LISTENERS_LOCAL.set(listeners);
}
listeners.add(listener);
}
public static void removeListener(Listener listener) {
List<Listener> listeners = LISTENERS_LOCAL.get();
if (listeners != null) {
listeners.remove(listener);
if (listeners.isEmpty()) {
LISTENERS_LOCAL.remove();
}
}
}
}
/** @deprecated Use {@link #getSimpleValues} instead. */
@Deprecated
public Map<String, Object> getJsonObject() {
return getSimpleValues();
}
/** @deprecated Use {@link #getSimpleValues} and {@link ObjectUtils#toJson} instead. */
@Deprecated
public String getJsonString() {
return ObjectUtils.toJson(getSimpleValues());
}
/** @deprecated Use {@link #setValues} and {@link ObjectUtils#fromJson} instead. */
@Deprecated
@SuppressWarnings("unchecked")
public void setJsonString(String json) {
setValues((Map<String, Object>) ObjectUtils.fromJson(json));
}
/** @deprecated Use {@link #setStatus} instead. */
@Deprecated
public void markSaved() {
setStatus(StateStatus.SAVED);
}
/** @deprecated Use {@link #setStatus} instead. */
@Deprecated
public void markDeleted() {
setStatus(StateStatus.DELETED);
}
/** @deprecated Use {@link #setStatus} instead. */
@Deprecated
public void markReadonly() {
setStatus(StateStatus.REFERENCE_ONLY);
}
/** @deprecated Use {@link #isResolveReferenceOnly} instead. */
@Deprecated
public boolean isResolveReferenceOnly() {
return isResolveToReferenceOnly();
}
/** @deprecated Use {@link #isResolveReferenceOnly} instead. */
@Deprecated
public void setResolveReferenceOnly(boolean isResolveReferenceOnly) {
setResolveToReferenceOnly(isResolveReferenceOnly);
}
/** @deprecated Use {@link #incrementAtomically} instead. */
@Deprecated
public void incrementValue(String name, double value) {
incrementAtomically(name, value);
}
/** @deprecated Use {@link #decrementAtomically} instead. */
@Deprecated
public void decrementValue(String name, double value) {
decrementAtomically(name, value);
}
/** @deprecated Use {@link #addAtomically} instead. */
@Deprecated
public void addValue(String name, Object value) {
addAtomically(name, value);
}
/** @deprecated Use {@link #removeAtomically} instead. */
@Deprecated
public void removeValue(String name, Object value) {
removeAtomically(name, value);
}
/** @deprecated Use {@link #replaceAtomically} instead. */
@Deprecated
public void replaceValue(String name, Object value) {
replaceAtomically(name, value);
}
/** @deprecated Use {@link #getByPath} instead. */
@Deprecated
public Object getValue(String path) {
return getByPath(path);
}
/** @deprecated Use {@link #putByPath} instead. */
@Deprecated
public void putValue(String path, Object value) {
putByPath(path, value);
}
} |
package xyz.brassgoggledcoders.steamagerevolution.modules.processing.multiblock.furnace;
import net.minecraft.world.World;
import net.minecraftforge.fluids.Fluid;
import xyz.brassgoggledcoders.steamagerevolution.utils.fluids.FluidTankSingleSmart;
import xyz.brassgoggledcoders.steamagerevolution.utils.inventory.InventoryPiece.InventoryPieceFluid;
import xyz.brassgoggledcoders.steamagerevolution.utils.inventory.InventoryPiece.InventoryPieceItem;
import xyz.brassgoggledcoders.steamagerevolution.utils.inventory.InventoryPiece.InventoryPieceProgressBar;
import xyz.brassgoggledcoders.steamagerevolution.utils.inventory.InventoryRecipeMachine;
import xyz.brassgoggledcoders.steamagerevolution.utils.items.ItemStackHandlerSmart;
import xyz.brassgoggledcoders.steamagerevolution.utils.multiblock.SARMultiblockInventory;
public class ControllerSteamFurnace extends SARMultiblockInventory<InventoryRecipeMachine> {
public ControllerSteamFurnace(World world) {
super(world);
setInventory(new InventoryRecipeMachine(new InventoryPieceItem(new ItemStackHandlerSmart(1, this), 48, 33), null,
new InventoryPieceItem(new ItemStackHandlerSmart(1, this), 108, 33), null,
new InventoryPieceFluid(new FluidTankSingleSmart(Fluid.BUCKET_VOLUME * 16, "steam", this), 13, 9)).setProgressBar(new InventoryPieceProgressBar(72, 33)));
}
@Override
protected int getMinimumNumberOfBlocksForAssembledMachine() {
return 26;
}
@Override
public int getMinimumXSize() {
return 3;
}
@Override
public int getMinimumZSize() {
return 3;
}
@Override
public int getMinimumYSize() {
return 3;
}
@Override
public int getMaximumXSize() {
return 6;
}
@Override
public int getMaximumZSize() {
return 6;
}
@Override
public int getMaximumYSize() {
return 6;
}
@Override
public String getName() {
return "Steam Furnace";
}
} |
package com.thinkaurelius.titan.diskstorage.hbase;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.thinkaurelius.titan.diskstorage.*;
import com.thinkaurelius.titan.diskstorage.keycolumnvalue.*;
import com.thinkaurelius.titan.diskstorage.util.RecordIterator;
import com.thinkaurelius.titan.diskstorage.util.StaticArrayBuffer;
import com.thinkaurelius.titan.diskstorage.util.StaticArrayEntry;
import com.thinkaurelius.titan.diskstorage.util.StaticArrayEntryList;
import com.thinkaurelius.titan.util.system.IOUtils;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.ColumnPaginationFilter;
import org.apache.hadoop.hbase.filter.ColumnRangeFilter;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.FilterList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.io.Closeable;
import java.io.IOException;
import java.util.*;
/**
* Here are some areas that might need work:
* <p/>
* - batching? (consider HTable#batch, HTable#setAutoFlush(false)
* - tuning HTable#setWriteBufferSize (?)
* - writing a server-side filter to replace ColumnCountGetFilter, which drops
* all columns on the row where it reaches its limit. This requires getSlice,
* currently, to impose its limit on the client side. That obviously won't
* scale.
* - RowMutations for combining Puts+Deletes (need a newer HBase than 0.92 for this)
* - (maybe) fiddle with HTable#setRegionCachePrefetch and/or #prewarmRegionCache
* <p/>
* There may be other problem areas. These are just the ones of which I'm aware.
*/
public class HBaseKeyColumnValueStore implements KeyColumnValueStore {
private static final Logger logger = LoggerFactory.getLogger(HBaseKeyColumnValueStore.class);
private final String tableName;
private final HBaseStoreManager storeManager;
// When using shortened CF names, columnFamily is the shortname and storeName is the longname
// When not using shortened CF names, they are the same
//private final String columnFamily;
private final String storeName;
// This is columnFamily.getBytes()
private final byte[] columnFamilyBytes;
private final HBaseGetter entryGetter;
private final ConnectionMask cnx;
HBaseKeyColumnValueStore(HBaseStoreManager storeManager, ConnectionMask cnx, String tableName, String columnFamily, String storeName) {
this.storeManager = storeManager;
this.cnx = cnx;
this.tableName = tableName;
//this.columnFamily = columnFamily;
this.storeName = storeName;
this.columnFamilyBytes = columnFamily.getBytes();
this.entryGetter = new HBaseGetter(storeManager.getMetaDataSchema(storeName));
}
@Override
public void close() throws BackendException {
}
@Override
public EntryList getSlice(KeySliceQuery query, StoreTransaction txh) throws BackendException {
Map<StaticBuffer, EntryList> result = getHelper(Arrays.asList(query.getKey()), getFilter(query));
return Iterables.getOnlyElement(result.values(), EntryList.EMPTY_LIST);
}
@Override
public Map<StaticBuffer,EntryList> getSlice(List<StaticBuffer> keys, SliceQuery query, StoreTransaction txh) throws BackendException {
return getHelper(keys, getFilter(query));
}
@Override
public void mutate(StaticBuffer key, List<Entry> additions, List<StaticBuffer> deletions, StoreTransaction txh) throws BackendException {
Map<StaticBuffer, KCVMutation> mutations = ImmutableMap.of(key, new KCVMutation(additions, deletions));
mutateMany(mutations, txh);
}
@Override
public void acquireLock(StaticBuffer key,
StaticBuffer column,
StaticBuffer expectedValue,
StoreTransaction txh) throws BackendException {
throw new UnsupportedOperationException();
}
@Override
public KeyIterator getKeys(KeyRangeQuery query, StoreTransaction txh) throws BackendException {
return executeKeySliceQuery(query.getKeyStart().as(StaticBuffer.ARRAY_FACTORY),
query.getKeyEnd().as(StaticBuffer.ARRAY_FACTORY),
new FilterList(FilterList.Operator.MUST_PASS_ALL),
query);
}
@Override
public String getName() {
return storeName;
}
@Override
public KeyIterator getKeys(SliceQuery query, StoreTransaction txh) throws BackendException {
return executeKeySliceQuery(new FilterList(FilterList.Operator.MUST_PASS_ALL), query);
}
public static Filter getFilter(SliceQuery query) {
byte[] colStartBytes = query.getSliceStart().length() > 0 ? query.getSliceStart().as(StaticBuffer.ARRAY_FACTORY) : null;
byte[] colEndBytes = query.getSliceEnd().length() > 0 ? query.getSliceEnd().as(StaticBuffer.ARRAY_FACTORY) : null;
Filter filter = new ColumnRangeFilter(colStartBytes, true, colEndBytes, false);
if (query.hasLimit()) {
filter = new FilterList(FilterList.Operator.MUST_PASS_ALL,
filter,
new ColumnPaginationFilter(query.getLimit(), 0));
}
logger.debug("Generated HBase Filter {}", filter);
return filter;
}
private Map<StaticBuffer,EntryList> getHelper(List<StaticBuffer> keys, Filter getFilter) throws BackendException {
List<Get> requests = new ArrayList<Get>(keys.size());
{
for (StaticBuffer key : keys) {
Get g = new Get(key.as(StaticBuffer.ARRAY_FACTORY)).addFamily(columnFamilyBytes).setFilter(getFilter);
try {
g.setTimeRange(0, Long.MAX_VALUE);
} catch (IOException e) {
throw new PermanentBackendException(e);
}
requests.add(g);
}
}
Map<StaticBuffer,EntryList> resultMap = new HashMap<StaticBuffer,EntryList>(keys.size());
try {
TableMask table = null;
Result[] results = null;
try {
table = cnx.getTable(tableName);
results = table.get(requests);
} finally {
IOUtils.closeQuietly(table);
}
if (results == null)
return KCVSUtil.emptyResults(keys);
assert results.length==keys.size();
for (int i = 0; i < results.length; i++) {
Result result = results[i];
NavigableMap<byte[], NavigableMap<byte[], NavigableMap<Long, byte[]>>> f = result.getMap();
if (f == null) { // no result for this key
resultMap.put(keys.get(i), EntryList.EMPTY_LIST);
continue;
}
// actual key with <timestamp, value>
NavigableMap<byte[], NavigableMap<Long, byte[]>> r = f.get(columnFamilyBytes);
resultMap.put(keys.get(i), (r == null)
? EntryList.EMPTY_LIST
: StaticArrayEntryList.ofBytes(r.entrySet(), entryGetter));
}
return resultMap;
} catch (IOException e) {
throw new TemporaryBackendException(e);
}
}
private void mutateMany(Map<StaticBuffer, KCVMutation> mutations, StoreTransaction txh) throws BackendException {
storeManager.mutateMany(ImmutableMap.of(storeName, mutations), txh);
}
private KeyIterator executeKeySliceQuery(FilterList filters, @Nullable SliceQuery columnSlice) throws BackendException {
return executeKeySliceQuery(null, null, filters, columnSlice);
}
private KeyIterator executeKeySliceQuery(@Nullable byte[] startKey,
@Nullable byte[] endKey,
FilterList filters,
@Nullable SliceQuery columnSlice) throws BackendException {
Scan scan = new Scan().addFamily(columnFamilyBytes);
try {
scan.setTimeRange(0, Long.MAX_VALUE);
} catch (IOException e) {
throw new PermanentBackendException(e);
}
if (startKey != null)
scan.setStartRow(startKey);
if (endKey != null)
scan.setStopRow(endKey);
if (columnSlice != null) {
filters.addFilter(getFilter(columnSlice));
}
TableMask table = null;
try {
table = cnx.getTable(tableName);
return new RowIterator(table, table.getScanner(scan.setFilter(filters)), columnFamilyBytes);
} catch (IOException e) {
IOUtils.closeQuietly(table);
throw new PermanentBackendException(e);
}
}
private class RowIterator implements KeyIterator {
private final Closeable table;
private final Iterator<Result> rows;
private final byte[] columnFamilyBytes;
private Result currentRow;
private boolean isClosed;
public RowIterator(Closeable table, ResultScanner rows, byte[] columnFamilyBytes) {
this.table = table;
this.columnFamilyBytes = Arrays.copyOf(columnFamilyBytes, columnFamilyBytes.length);
this.rows = Iterators.filter(rows.iterator(), result -> null != result && null != result.getRow());
}
@Override
public RecordIterator<Entry> getEntries() {
ensureOpen();
return new RecordIterator<Entry>() {
private final Iterator<Map.Entry<byte[], NavigableMap<Long, byte[]>>> kv = currentRow.getMap().get(columnFamilyBytes).entrySet().iterator();
@Override
public boolean hasNext() {
ensureOpen();
return kv.hasNext();
}
@Override
public Entry next() {
ensureOpen();
return StaticArrayEntry.ofBytes(kv.next(), entryGetter);
}
@Override
public void close() {
isClosed = true;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override
public boolean hasNext() {
ensureOpen();
return rows.hasNext();
}
@Override
public StaticBuffer next() {
ensureOpen();
currentRow = rows.next();
return StaticArrayBuffer.of(currentRow.getRow());
}
@Override
public void close() {
IOUtils.closeQuietly(table);
isClosed = true;
logger.debug("RowIterator closed table {}", table);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
private void ensureOpen() {
if (isClosed)
throw new IllegalStateException("Iterator has been closed.");
}
}
private static class HBaseGetter implements StaticArrayEntry.GetColVal<Map.Entry<byte[], NavigableMap<Long, byte[]>>, byte[]> {
private final EntryMetaData[] schema;
private HBaseGetter(EntryMetaData[] schema) {
this.schema = schema;
}
@Override
public byte[] getColumn(Map.Entry<byte[], NavigableMap<Long, byte[]>> element) {
return element.getKey();
}
@Override
public byte[] getValue(Map.Entry<byte[], NavigableMap<Long, byte[]>> element) {
return element.getValue().lastEntry().getValue();
}
@Override
public EntryMetaData[] getMetaSchema(Map.Entry<byte[], NavigableMap<Long, byte[]>> element) {
return schema;
}
@Override
public Object getMetaData(Map.Entry<byte[], NavigableMap<Long, byte[]>> element, EntryMetaData meta) {
switch(meta) {
case TIMESTAMP:
return element.getValue().lastEntry().getKey();
default:
throw new UnsupportedOperationException("Unsupported meta data: " + meta);
}
}
}
} |
package nodomain.freeyourgadget.gadgetbridge.service.devices.miband2.operations;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.widget.Toast;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.concurrent.TimeUnit;
import nodomain.freeyourgadget.gadgetbridge.GBApplication;
import nodomain.freeyourgadget.gadgetbridge.Logging;
import nodomain.freeyourgadget.gadgetbridge.database.DBHandler;
import nodomain.freeyourgadget.gadgetbridge.database.DBHelper;
import nodomain.freeyourgadget.gadgetbridge.devices.huami.amazfitbip.AmazfitBipService;
import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBand2Service;
import nodomain.freeyourgadget.gadgetbridge.entities.BaseActivitySummary;
import nodomain.freeyourgadget.gadgetbridge.entities.DaoSession;
import nodomain.freeyourgadget.gadgetbridge.entities.Device;
import nodomain.freeyourgadget.gadgetbridge.entities.User;
import nodomain.freeyourgadget.gadgetbridge.model.ActivityKind;
import nodomain.freeyourgadget.gadgetbridge.service.btle.BLETypeConversions;
import nodomain.freeyourgadget.gadgetbridge.service.btle.TransactionBuilder;
import nodomain.freeyourgadget.gadgetbridge.service.btle.actions.WaitAction;
import nodomain.freeyourgadget.gadgetbridge.service.devices.amazfitbip.BipActivityType;
import nodomain.freeyourgadget.gadgetbridge.service.devices.miband2.MiBand2Support;
import nodomain.freeyourgadget.gadgetbridge.util.GB;
/**
* An operation that fetches activity data. For every fetch, a new operation must
* be created, i.e. an operation may not be reused for multiple fetches.
*/
public class FetchSportsSummaryOperation extends AbstractFetchOperation {
private static final Logger LOG = LoggerFactory.getLogger(FetchSportsSummaryOperation.class);
private ByteArrayOutputStream buffer = new ByteArrayOutputStream(140);
public FetchSportsSummaryOperation(MiBand2Support support) {
super(support);
setName("fetching sport summaries");
}
@Override
protected void startFetching(TransactionBuilder builder) {
LOG.info("start" + getName());
GregorianCalendar sinceWhen = getLastSuccessfulSyncTime();
builder.write(characteristicFetch, BLETypeConversions.join(new byte[] {
MiBand2Service.COMMAND_ACTIVITY_DATA_START_DATE,
AmazfitBipService.COMMAND_ACTIVITY_DATA_TYPE_SPORTS_SUMMARIES},
getSupport().getTimeBytes(sinceWhen, TimeUnit.MINUTES)));
builder.add(new WaitAction(1000)); // TODO: actually wait for the success-reply
builder.notify(characteristicActivityData, true);
builder.write(characteristicFetch, new byte[] { MiBand2Service.COMMAND_FETCH_DATA });
}
@Override
protected void handleActivityFetchFinish(boolean success) {
LOG.info(getName() + " has finished round " + fetchCount);
// GregorianCalendar lastSyncTimestamp = saveSamples();
// if (lastSyncTimestamp != null && needsAnotherFetch(lastSyncTimestamp)) {
// try {
// startFetching();
// return;
// } catch (IOException ex) {
// LOG.error("Error starting another round of fetching activity data", ex);
BaseActivitySummary summary = null;
if (success) {
summary = parseSummary(buffer);
try (DBHandler dbHandler = GBApplication.acquireDB()) {
DaoSession session = dbHandler.getDaoSession();
Device device = DBHelper.getDevice(getDevice(), session);
User user = DBHelper.getUser(session);
summary.setDevice(device);
summary.setUser(user);
session.getBaseActivitySummaryDao().insertOrReplace(summary);
} catch (Exception ex) {
GB.toast(getContext(), "Error saving activity summary", Toast.LENGTH_LONG, GB.ERROR, ex);
}
}
super.handleActivityFetchFinish(success);
if (summary != null) {
FetchSportsDetailsOperation nextOperation = new FetchSportsDetailsOperation(summary, getSupport(), getLastSyncTimeKey());
try {
nextOperation.perform();
} catch (IOException ex) {
GB.toast(getContext(), "Unable to fetch activity details: " + ex.getMessage(), Toast.LENGTH_LONG, GB.ERROR, ex);
}
}
}
@Override
public boolean onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
LOG.warn("characteristic read: " + characteristic.getUuid() + ": " + Logging.formatBytes(characteristic.getValue()));
return super.onCharacteristicRead(gatt, characteristic, status);
}
/**
* Method to handle the incoming activity data.
* There are two kind of messages we currently know:
* - the first one is 11 bytes long and contains metadata (how many bytes to expect, when the data starts, etc.)
* - the second one is 20 bytes long and contains the actual activity data
* <p/>
* The first message type is parsed by this method, for every other length of the value param, bufferActivityData is called.
*
* @param value
*/
@Override
protected void handleActivityNotif(byte[] value) {
LOG.warn("sports summary data: " + Logging.formatBytes(value));
if (!isOperationRunning()) {
LOG.error("ignoring activity data notification because operation is not running. Data length: " + value.length);
getSupport().logMessageContent(value);
return;
}
if (value.length < 2) {
LOG.error("unexpected sports summary data length: " + value.length);
getSupport().logMessageContent(value);
return;
}
if ((byte) (lastPacketCounter + 1) == value[0] ) {
lastPacketCounter++;
bufferActivityData(value);
} else {
GB.toast("Error " + getName() + ", invalid package counter: " + value[0] + ", last was: " + lastPacketCounter, Toast.LENGTH_LONG, GB.ERROR);
handleActivityFetchFinish(false);
return;
}
}
/**
* Buffers the given activity summary data. If the total size is reached,
* it is converted to an object and saved in the database.
* @param value
*/
@Override
protected void bufferActivityData(byte[] value) {
buffer.write(value, 1, value.length - 1); // skip the counter
}
private BaseActivitySummary parseSummary(ByteArrayOutputStream stream) {
BaseActivitySummary summary = new BaseActivitySummary();
ByteBuffer buffer = ByteBuffer.wrap(stream.toByteArray()).order(ByteOrder.LITTLE_ENDIAN);
// summary.setVersion(BLETypeConversions.toUnsigned(buffer.getShort()));
buffer.getShort(); // version
int activityKind = ActivityKind.TYPE_UNKNOWN;
try {
int rawKind = BLETypeConversions.toUnsigned(buffer.getShort());
BipActivityType activityType = BipActivityType.fromCode(rawKind);
activityKind = activityType.toActivityKind();
} catch (Exception ex) {
LOG.error("Error mapping acivity kind: " + ex.getMessage(), ex);
}
summary.setActivityKind(activityKind);
// FIXME: should save timezone etc.
summary.setStartTime(new Date(BLETypeConversions.toUnsigned(buffer.getInt()) * 1000));
summary.setEndTime(new Date(BLETypeConversions.toUnsigned(buffer.getInt()) * 1000));
int baseLongitude = buffer.getInt();
int baseLatitude = buffer.getInt();
int baseAltitude = buffer.getInt();
summary.setBaseLongitude(baseLongitude);
summary.setBaseLatitude(baseLatitude);
summary.setBaseAltitude(baseAltitude);
// summary.setBaseCoordinate(new GPSCoordinate(baseLatitude, baseLongitude, baseAltitude));
// summary.setDistanceMeters(Float.intBitsToFloat(buffer.getInt()));
// summary.setAscentMeters(Float.intBitsToFloat(buffer.getInt()));
// summary.setDescentMeters(Float.intBitsToFloat(buffer.getInt()));
// summary.setMinAltitude(Float.intBitsToFloat(buffer.getInt()));
// summary.setMaxAltitude(Float.intBitsToFloat(buffer.getInt()));
// summary.setMinLatitude(buffer.getInt());
// summary.setMaxLatitude(buffer.getInt());
// summary.setMinLongitude(buffer.getInt());
// summary.setMaxLongitude(buffer.getInt());
// summary.setSteps(BLETypeConversions.toUnsigned(buffer.getInt()));
// summary.setActiveTimeSeconds(BLETypeConversions.toUnsigned(buffer.getInt()));
// summary.setCaloriesBurnt(Float.intBitsToFloat(buffer.get()));
// summary.setMaxSpeed(Float.intBitsToFloat(buffer.get()));
// summary.setMinPace(Float.intBitsToFloat(buffer.get()));
// summary.setMaxPace(Float.intBitsToFloat(buffer.get()));
// summary.setTotalStride(Float.intBitsToFloat(buffer.get()));
buffer.getInt();
buffer.getInt();
buffer.getInt();
// summary.setTimeAscent(BLETypeConversions.toUnsigned(buffer.getInt()));
// buffer.getInt(); //
// summary.setTimeDescent(BLETypeConversions.toUnsigned(buffer.getInt()));
// buffer.getInt(); //
// summary.setTimeFlat(BLETypeConversions.toUnsigned(buffer.getInt()));
// summary.setAverageHR(BLETypeConversions.toUnsigned(buffer.getShort()));
// summary.setAveragePace(BLETypeConversions.toUnsigned(buffer.getShort()));
// summary.setAverageStride(BLETypeConversions.toUnsigned(buffer.getShort()));
buffer.getShort();
return summary;
}
@Override
protected String getLastSyncTimeKey() {
return getDevice().getAddress() + "_" + "lastSportsActivityTimeMillis";
}
} |
package org.csstudio.opibuilder.adl2boy.translator;
import java.util.List;
import org.csstudio.opibuilder.model.AbstractContainerModel;
import org.csstudio.opibuilder.model.AbstractPVWidgetModel;
import org.csstudio.opibuilder.model.AbstractWidgetModel;
import org.csstudio.opibuilder.properties.RulesProperty;
import org.csstudio.opibuilder.script.Expression;
import org.csstudio.opibuilder.script.PVTuple;
import org.csstudio.opibuilder.script.RuleData;
import org.csstudio.opibuilder.script.RuleScriptData;
import org.csstudio.opibuilder.script.RulesInput;
import org.csstudio.utility.adlparser.fileParser.ADLWidget;
import org.csstudio.utility.adlparser.fileParser.widgetParts.ADLBasicAttribute;
import org.csstudio.utility.adlparser.fileParser.widgetParts.ADLControl;
import org.csstudio.utility.adlparser.fileParser.widgetParts.ADLDynamicAttribute;
import org.csstudio.utility.adlparser.fileParser.widgetParts.ADLMonitor;
import org.csstudio.utility.adlparser.fileParser.widgetParts.ADLObject;
import org.csstudio.utility.adlparser.fileParser.widgets.ADLAbstractWidget;
import org.eclipse.swt.graphics.RGB;
public abstract class AbstractADL2Model {
AbstractWidgetModel widgetModel;
RGB colorMap[] = new RGB[0];
protected String className = new String();
public AbstractADL2Model(final ADLWidget adlWidget, RGB colorMap[], AbstractContainerModel parentWidget) {
this.colorMap = colorMap;
}
/**
*
* @return
*/
abstract public AbstractWidgetModel getWidgetModel() ;
/** set the properties contained in the ADL basic properties section in the
* created widgetModel
* @param adlWidget
* @param widgetModel
*/
protected void setADLObjectProps(ADLAbstractWidget adlWidget, AbstractWidgetModel widgetModel){
if (adlWidget.hasADLObject()){
ADLObject adlObj=adlWidget.getAdlObject();
widgetModel.setX(adlObj.getX());
widgetModel.setY(adlObj.getY());
widgetModel.setHeight(adlObj.getHeight());
widgetModel.setWidth(adlObj.getWidth());
}
}
/** set the properties contained in the ADL basic properties section in the
* created widgetModel
* @param adlWidget
* @param widgetModel
*/
protected void setADLBasicAttributeProps(ADLAbstractWidget adlWidget, AbstractWidgetModel widgetModel, boolean colorForeground){
ADLBasicAttribute basAttr;
if (adlWidget.hasADLBasicAttribute()){
basAttr = adlWidget.getAdlBasicAttribute();
}
else {
basAttr = TranslatorUtils.getDefaultBasicAttribute();
adlWidget.setAdlBasicAttribute(basAttr);
}
if (basAttr.isColorDefined()) {
if (colorForeground) {
widgetModel.setForegroundColor(colorMap[basAttr.getClr()]);
} else {
widgetModel.setBackgroundColor(colorMap[basAttr.getClr()]);
}
} else {
if (colorForeground) {
widgetModel.setForegroundColor(widgetModel.getParent()
.getForegroundColor());
} else {
widgetModel.setBackgroundColor(widgetModel.getParent()
.getBackgroundColor());
}
}
}
/**
*
* @param adlWidget
* @param widgetModel
*/
protected void setADLDynamicAttributeProps(ADLAbstractWidget adlWidget, AbstractWidgetModel widgetModel){
ADLDynamicAttribute dynAttr;
if (adlWidget.hasADLDynamicAttribute()) {
dynAttr = adlWidget.getAdlDynamicAttribute();
}
else {
dynAttr = TranslatorUtils.getDefaultDynamicAttribute();
adlWidget.setAdlDynamicAttribute(dynAttr);
}
if (!(dynAttr.get_vis().equals("static"))){
if (dynAttr.get_chan() != null) {
if (dynAttr.get_vis().equals("if not zero")){
RulesInput ruleInput = widgetModel.getRulesInput();
List<RuleData> ruleData = ruleInput.getRuleDataList();
RuleData newRule = new RuleData(widgetModel);
PVTuple pvs = new PVTuple(dynAttr.get_chan(), true);
newRule.addPV(pvs);
newRule.addExpression(new Expression("pv0==0", false));
ruleData.add(newRule);
newRule.setName("Visibility");
newRule.setPropId(AbstractWidgetModel.PROP_VISIBLE);
widgetModel.setPropertyValue(AbstractWidgetModel.PROP_RULES, ruleData);
}
else if (dynAttr.get_vis().equals("if zero")){
RulesInput ruleInput = widgetModel.getRulesInput();
List<RuleData> ruleData = ruleInput.getRuleDataList();
RuleData newRule = new RuleData(widgetModel);
PVTuple pvs = new PVTuple(dynAttr.get_chan(), true);
newRule.addPV(pvs);
newRule.addExpression(new Expression("!(pv0==0)", false));
newRule.setName("Visibility");
newRule.setPropId(AbstractWidgetModel.PROP_VISIBLE);
ruleData.add(newRule);
widgetModel.setPropertyValue(AbstractWidgetModel.PROP_RULES, ruleData);
}
else if (dynAttr.get_vis().equals("calc")){
//TODO Figure out calc option on dynamic attributes AbstractADL2Model
}
}
}
}
/** set the properties contained in the ADL basic properties section in the
* created widgetModel
* @param adlWidget
* @param widgetModel
*/
protected void setADLControlProps(ADLAbstractWidget adlWidget, AbstractWidgetModel widgetModel){
if (adlWidget.hasADLControl()){
ADLControl control = adlWidget.getAdlControl();
if (control.isForeColorDefined() ){
widgetModel.setForegroundColor(colorMap[control.getForegroundColor()]);
}
else {
widgetModel.setForegroundColor(widgetModel.getParent().getForegroundColor());
}
if (control.isBackColorDefined() ){
widgetModel.setBackgroundColor(colorMap[control.getBackgroundColor()]);
}
else {
widgetModel.setBackgroundColor(widgetModel.getParent().getBackgroundColor());
}
String channel = control.getChan();
if ((channel != null) && (!(channel.equals(""))) ){
widgetModel.setPropertyValue(AbstractPVWidgetModel.PROP_PVNAME, channel);
}
}
}
/** set the properties contained in the ADL basic properties section in the
* created widgetModel
* @param adlWidget
* @param widgetModel
*/
protected void setADLMonitorProps(ADLAbstractWidget adlWidget, AbstractWidgetModel widgetModel){
if (adlWidget.hasADLMonitor()){
ADLMonitor monitor = adlWidget.getAdlMonitor();
if (monitor.isForeColorDefined() ){
widgetModel.setForegroundColor(colorMap[monitor.getForegroundColor()]);
}
else {
widgetModel.setForegroundColor(widgetModel.getParent().getForegroundColor());
}
if (monitor.isBackColorDefined() ){
widgetModel.setBackgroundColor(colorMap[monitor.getBackgroundColor()]);
}
else {
widgetModel.setBackgroundColor(widgetModel.getParent().getBackgroundColor());
}
String channel = monitor.getChan();
if ((channel != null) && (!(channel.equals(""))) ){
widgetModel.setPropertyValue(AbstractPVWidgetModel.PROP_PVNAME, channel);
}
}
}
} |
package org.csstudio.opibuilder.widgets.editparts;
import org.csstudio.data.values.IDoubleValue;
import org.csstudio.data.values.IEnumeratedValue;
import org.csstudio.data.values.ILongValue;
import org.csstudio.data.values.INumericMetaData;
import org.csstudio.data.values.IValue;
import org.csstudio.data.values.IValue.Format;
import org.csstudio.data.values.ValueFactory;
import org.csstudio.opibuilder.editparts.AbstractPVWidgetEditPart;
import org.csstudio.opibuilder.editparts.ExecutionMode;
import org.csstudio.opibuilder.model.AbstractContainerModel;
import org.csstudio.opibuilder.model.AbstractPVWidgetModel;
import org.csstudio.opibuilder.model.AbstractWidgetModel;
import org.csstudio.opibuilder.properties.IWidgetPropertyChangeHandler;
import org.csstudio.opibuilder.util.OPIFont;
import org.csstudio.opibuilder.widgets.model.LabelModel;
import org.csstudio.opibuilder.widgets.model.TextUpdateModel;
import org.csstudio.opibuilder.widgets.model.TextUpdateModel.FormatEnum;
import org.csstudio.swt.widgets.figures.ITextFigure;
import org.csstudio.swt.widgets.figures.TextFigure;
import org.csstudio.swt.widgets.figures.TextFigure.H_ALIGN;
import org.csstudio.swt.widgets.figures.TextFigure.V_ALIGN;
import org.csstudio.swt.widgets.figures.WrappableTextFigure;
import org.csstudio.ui.util.CustomMediaFactory;
import org.eclipse.draw2d.IFigure;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.Request;
import org.eclipse.gef.RequestConstants;
import org.eclipse.swt.widgets.Display;
/**The editor for text indicator widget.
* @author Xihui Chen
*
*/
public class TextUpdateEditPart extends AbstractPVWidgetEditPart {
public static final String HEX_PREFIX = "0x"; //$NON-NLS-1$
private TextUpdateModel widgetModel;
private FormatEnum format;
private boolean isAutoSize;
private boolean isPrecisionFromDB;
private boolean isShowUnits;
private int precision;
@Override
protected IFigure doCreateFigure() {
initFields();
TextFigure labelFigure = createTextFigure();
labelFigure.setFont(CustomMediaFactory.getInstance().getFont(
widgetModel.getFont().getFontData()));
labelFigure.setOpaque(!widgetModel.isTransparent());
labelFigure.setHorizontalAlignment(widgetModel.getHorizontalAlignment());
labelFigure.setVerticalAlignment(widgetModel.getVerticalAlignment());
labelFigure.setRotate(widgetModel.getRotationAngle());
return labelFigure;
}
protected void initFields() {
//Initialize frequently used variables.
widgetModel = getWidgetModel();
format = widgetModel.getFormat();
isAutoSize = widgetModel.isAutoSize();
isPrecisionFromDB = widgetModel.isPrecisionFromDB();
isShowUnits = widgetModel.isShowUnits();
precision = widgetModel.getPrecision();
}
protected TextFigure createTextFigure(){
if(getWidgetModel().isWrapWords())
return new WrappableTextFigure(getExecutionMode() == ExecutionMode.RUN_MODE);
return new TextFigure(getExecutionMode() == ExecutionMode.RUN_MODE);
}
@Override
protected void createEditPolicies() {
super.createEditPolicies();
if(getExecutionMode() == ExecutionMode.EDIT_MODE)
installEditPolicy(EditPolicy.DIRECT_EDIT_ROLE, new TextUpdateDirectEditPolicy());
}
@Override
public void activate() {
super.activate();
setFigureText(getWidgetModel().getText());
if(getWidgetModel().isAutoSize()){
performAutoSize();
figure.revalidate();
}
}
/**
* @param text
*/
protected void setFigureText(String text) {
((TextFigure) getFigure()).setText(text);
}
@Override
protected void registerPropertyChangeHandlers() {
IWidgetPropertyChangeHandler handler = new IWidgetPropertyChangeHandler(){
public boolean handleChange(Object oldValue, Object newValue,
final IFigure figure) {
setFigureText((String)newValue);
if(isAutoSize){
Display.getCurrent().timerExec(10, new Runnable() {
public void run() {
performAutoSize();
}
});
}
return true;
}
};
setPropertyChangeHandler(TextUpdateModel.PROP_TEXT, handler);
IWidgetPropertyChangeHandler fontHandler = new IWidgetPropertyChangeHandler(){
public boolean handleChange(Object oldValue, Object newValue,
IFigure figure) {
figure.setFont(CustomMediaFactory.getInstance().getFont(
((OPIFont)newValue).getFontData()));
return true;
}
};
setPropertyChangeHandler(LabelModel.PROP_FONT, fontHandler);
handler = new IWidgetPropertyChangeHandler(){
public boolean handleChange(Object oldValue, Object newValue,
final IFigure figure) {
Display.getCurrent().timerExec(10, new Runnable() {
public void run() {
if(getWidgetModel().isAutoSize()){
performAutoSize();
figure.revalidate();
}
}
});
return true;
}
};
setPropertyChangeHandler(LabelModel.PROP_FONT, handler);
setPropertyChangeHandler(AbstractWidgetModel.PROP_BORDER_STYLE, handler);
setPropertyChangeHandler(AbstractWidgetModel.PROP_BORDER_WIDTH, handler);
handler = new IWidgetPropertyChangeHandler(){
public boolean handleChange(Object oldValue, Object newValue,
IFigure figure) {
((TextFigure)figure).setOpaque(!(Boolean)newValue);
return true;
}
};
setPropertyChangeHandler(LabelModel.PROP_TRANSPARENT, handler);
handler = new IWidgetPropertyChangeHandler(){
public boolean handleChange(Object oldValue, Object newValue,
IFigure figure) {
isAutoSize = (Boolean)newValue;
if((Boolean)newValue){
performAutoSize();
figure.revalidate();
}
return true;
}
};
setPropertyChangeHandler(LabelModel.PROP_AUTOSIZE, handler);
handler = new IWidgetPropertyChangeHandler(){
public boolean handleChange(Object oldValue, Object newValue,
IFigure figure) {
((TextFigure)figure).setHorizontalAlignment(H_ALIGN.values()[(Integer)newValue]);
return true;
}
};
setPropertyChangeHandler(LabelModel.PROP_ALIGN_H, handler);
handler = new IWidgetPropertyChangeHandler(){
public boolean handleChange(Object oldValue, Object newValue,
IFigure figure) {
((TextFigure)figure).setVerticalAlignment(V_ALIGN.values()[(Integer)newValue]);
return true;
}
};
setPropertyChangeHandler(LabelModel.PROP_ALIGN_V, handler);
handler = new IWidgetPropertyChangeHandler(){
public boolean handleChange(Object oldValue, Object newValue,
final IFigure figure) {
if(newValue == null)
return false;
formatValue(newValue, AbstractPVWidgetModel.PROP_PVVALUE);
return false;
}
};
setPropertyChangeHandler(AbstractPVWidgetModel.PROP_PVVALUE, handler);
handler = new IWidgetPropertyChangeHandler(){
public boolean handleChange(Object oldValue, Object newValue,
final IFigure figure) {
format = FormatEnum.values()[(Integer)newValue];
formatValue(newValue, TextUpdateModel.PROP_FORMAT_TYPE);
return true;
}
};
setPropertyChangeHandler(TextUpdateModel.PROP_FORMAT_TYPE, handler);
handler = new IWidgetPropertyChangeHandler(){
public boolean handleChange(Object oldValue, Object newValue,
final IFigure figure) {
precision = (Integer)newValue;
formatValue(newValue, TextUpdateModel.PROP_PRECISION);
return true;
}
};
setPropertyChangeHandler(TextUpdateModel.PROP_PRECISION, handler);
handler = new IWidgetPropertyChangeHandler(){
public boolean handleChange(Object oldValue, Object newValue,
final IFigure figure) {
isPrecisionFromDB = (Boolean)newValue;
formatValue(newValue, TextUpdateModel.PROP_PRECISION_FROM_DB);
return true;
}
};
setPropertyChangeHandler(TextUpdateModel.PROP_PRECISION_FROM_DB, handler);
handler = new IWidgetPropertyChangeHandler(){
public boolean handleChange(Object oldValue, Object newValue,
final IFigure figure) {
isShowUnits = (Boolean)newValue;
formatValue(newValue, TextUpdateModel.PROP_SHOW_UNITS);
return true;
}
};
setPropertyChangeHandler(TextUpdateModel.PROP_SHOW_UNITS, handler);
handler = new IWidgetPropertyChangeHandler(){
public boolean handleChange(Object oldValue, Object newValue,
final IFigure figure) {
((TextFigure)figure).setRotate((Double)newValue);
return true;
}
};
setPropertyChangeHandler(TextUpdateModel.PROP_ROTATION, handler);
handler = new IWidgetPropertyChangeHandler() {
@Override
public boolean handleChange(Object oldValue, Object newValue, IFigure figure) {
AbstractWidgetModel model = getWidgetModel();
AbstractContainerModel parent = model.getParent();
parent.removeChild(model);
parent.addChild(model);
parent.selectWidget(model, true);
return false;
}
};
setPropertyChangeHandler(TextUpdateModel.PROP_WRAP_WORDS, handler);
}
@Override
public TextUpdateModel getWidgetModel() {
return (TextUpdateModel)getModel();
}
protected void performDirectEdit(){
new TextEditManager(this, new LabelCellEditorLocator((TextFigure)getFigure())).show();
}
@Override
public void performRequest(Request request){
if (getExecutionMode() == ExecutionMode.EDIT_MODE &&(
request.getType() == RequestConstants.REQ_DIRECT_EDIT ||
request.getType() == RequestConstants.REQ_OPEN))
performDirectEdit();
}
/**
* @param figure
*/
protected void performAutoSize() {
getWidgetModel().setSize(((TextFigure)getFigure()).getAutoSizeDimension());
}
/**
* @param newValue
* @return
*/
protected String formatValue(Object newValue, String propId) {
if(getExecutionMode() != ExecutionMode.RUN_MODE)
return null;
IValue value = null;
int tempPrecision = precision;
if(isPrecisionFromDB)
tempPrecision = -1;
if(propId.equals(AbstractPVWidgetModel.PROP_PVVALUE))
value = (IValue)newValue;
else
value = getPVValue(AbstractPVWidgetModel.PROP_PVNAME);
String text;
switch (format) {
case DECIAML:
text = value.format(Format.Decimal, tempPrecision);
break;
case EXP:
text = value.format(Format.Exponential, tempPrecision);
break;
case HEX:
if(value instanceof IDoubleValue)
text = HEX_PREFIX + Integer.toHexString((int) ((IDoubleValue)value).getValue()).toUpperCase();
else if(value instanceof ILongValue)
text = HEX_PREFIX + Integer.toHexString((int) ((ILongValue)value).getValue()).toUpperCase();
else if(value instanceof IEnumeratedValue)
text = HEX_PREFIX + Integer.toHexString(((IEnumeratedValue)value).getValue()).toUpperCase();
else
text = value.format();
break;
case HEX64:
if(value instanceof IDoubleValue)
text = HEX_PREFIX + Long.toHexString((long) ((IDoubleValue)value).getValue()).toUpperCase();
else if(value instanceof ILongValue)
text = HEX_PREFIX + Long.toHexString((long) ((ILongValue)value).getValue()).toUpperCase();
else if(value instanceof IEnumeratedValue)
text = HEX_PREFIX + Long.toHexString(((IEnumeratedValue)value).getValue()).toUpperCase();
else
text = value.format();
break;
case COMPACT:
if (value instanceof IDoubleValue)
{
double dValue = ((IDoubleValue)value).getValue();
if ( ((dValue > 0.0001) && (dValue < 10000))||
((dValue < -0.0001) && (dValue > -10000)) ||
dValue == 0.0){
text = value.format(Format.Decimal, tempPrecision);
}
else{
text = value.format(Format.Exponential, tempPrecision);
}
}
else
text = value.format();
break;
case STRING:
text = value.format(Format.String, tempPrecision);
break;
case DEFAULT:
default:
text = value.format(Format.Default, tempPrecision);
break;
}
if(isShowUnits && value.getMetaData() instanceof INumericMetaData){
String units = ((INumericMetaData)value.getMetaData()).getUnits();
if(units != null && units.trim().length()>0)
text = text + " " + units; //$NON-NLS-1$
}
//synchronize the property value without fire listeners.
widgetModel.getProperty(
TextUpdateModel.PROP_TEXT).setPropertyValue(text, false);
setFigureText(text);
if(isAutoSize)
performAutoSize();
return text;
}
@Override
public String getValue() {
return ((TextFigure)getFigure()).getText();
}
@Override
public void setValue(Object value) {
String text;
if(value instanceof Number)
text = formatValue(ValueFactory.createDoubleValue(
null, ValueFactory.createOKSeverity(), null, null, null, new double[]{((Number)value).doubleValue()}),
AbstractPVWidgetModel.PROP_PVVALUE);
else
text = value.toString();
setFigureText(text);
}
@SuppressWarnings("rawtypes")
@Override
public Object getAdapter(Class key) {
if(key == ITextFigure.class)
return getFigure();
return super.getAdapter(key);
}
} |
package org.openhab.core.persistence.extensions;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.joda.time.base.AbstractInstant;
import org.openhab.core.items.Item;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.persistence.FilterCriteria;
import org.openhab.core.persistence.FilterCriteria.Ordering;
import org.openhab.core.persistence.HistoricItem;
import org.openhab.core.persistence.PersistenceService;
import org.openhab.core.persistence.QueryablePersistenceService;
import org.openhab.core.types.State;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class provides static methods that can be used in automation rules
* for using persistence services
*
* @author Thomas.Eichstaedt-Engelen
* @author Kai Kreuzer
* @author Chris Jackson
* @since 1.0.0
*
*/
public class PersistenceExtensions implements ManagedService {
private static final Logger logger = LoggerFactory.getLogger(PersistenceExtensions.class);
private static Map<String, PersistenceService> services = new HashMap<String, PersistenceService>();
private static String defaultService = null;
public PersistenceExtensions() {
// default constructor, necessary for osgi-ds
}
public void addPersistenceService(PersistenceService service) {
services.put(service.getName(), service);
}
public void removePersistenceService(PersistenceService service) {
services.remove(service.getName());
}
/**
* Persists the state of a given <code>item</code> through a {@link PersistenceService} identified
* by the <code>serviceName</code>.
*
* @param item the item to store
* @param serviceName the name of the {@link PersistenceService} to use
*/
static public void persist(Item item, String serviceName) {
PersistenceService service = services.get(serviceName);
if (service != null) {
service.store(item);
} else {
logger.warn("There is no persistence service registered with the name '{}'", serviceName);
}
}
/**
* Persists the state of a given <code>item</code> through the default persistence service.
*
* @param item the item to store
*/
static public void persist(Item item) {
if(isDefaultServiceAvailable()) {
persist(item, defaultService);
}
}
/**
* Retrieves the state of a given <code>item</code> to a certain point in time through the default persistence service.
*
* @param item the item to retrieve the state for
* @param the point in time for which the state should be retrieved
* @return the item state at the given point in time
*/
static public HistoricItem historicState(Item item, AbstractInstant timestamp) {
if(isDefaultServiceAvailable()) {
return historicState(item, timestamp, defaultService);
} else {
return null;
}
}
/**
* Retrieves the state of a given <code>item</code> to a certain point in time through a {@link PersistenceService} identified
* by the <code>serviceName</code>.
*
* @param item the item to retrieve the state for
* @param the point in time for which the state should be retrieved
* @param serviceName the name of the {@link PersistenceService} to use
* @return the item state at the given point in time
*/
static public HistoricItem historicState(Item item, AbstractInstant timestamp, String serviceName) {
PersistenceService service = services.get(serviceName);
if (service instanceof QueryablePersistenceService) {
QueryablePersistenceService qService = (QueryablePersistenceService) service;
FilterCriteria filter = new FilterCriteria();
filter.setEndDate(timestamp.toDate());
filter.setItemName(item.getName());
filter.setPageSize(1);
filter.setOrdering(Ordering.DESCENDING);
Iterable<HistoricItem> result = qService.query(filter);
if(result.iterator().hasNext()) {
return result.iterator().next();
} else {
return null;
}
} else {
logger.warn("There is no queryable persistence service registered with the name '{}'", serviceName);
return null;
}
}
/**
* Checks if the state of a given <code>item</code> has changed since a certain point in time.
* The default persistence service is used.
*
* @param item the item to check for state changes
* @param the point in time to start the check
* @return true, if item state had changed
*/
static public Boolean changedSince(Item item, AbstractInstant timestamp) {
if(isDefaultServiceAvailable()) {
return changedSince(item, timestamp, defaultService);
} else {
return null;
}
}
/**
* Checks if the state of a given <code>item</code> has changed since a certain point in time.
* The {@link PersistenceService} identified by the <code>serviceName</code> is used.
*
* @param item the item to check for state changes
* @param the point in time to start the check
* @param serviceName the name of the {@link PersistenceService} to use
* @return true, if item state had changed
*/
static public Boolean changedSince(Item item, AbstractInstant timestamp, String serviceName) {
Iterable<HistoricItem> result = getAllStatesSince(item, timestamp, serviceName);
Iterator<HistoricItem> it = result.iterator();
HistoricItem itemThen = historicState(item, timestamp);
if(itemThen == null) {
// Can't get the state at the start time
// If we've got results more recent that this, it must have changed
return(it.hasNext());
}
State state = itemThen.getState();
while(it.hasNext()) {
HistoricItem hItem = it.next();
if(state!=null && !hItem.getState().equals(state)) {
return true;
}
state = hItem.getState();
}
return false;
}
/**
* Checks if the state of a given <code>item</code> has been updated since a certain point in time.
* The default persistence service is used.
*
* @param item the item to check for state updates
* @param the point in time to start the check
* @return true, if item state was updated
*/
static public Boolean updatedSince(Item item, AbstractInstant timestamp) {
if(isDefaultServiceAvailable()) {
return updatedSince(item, timestamp, defaultService);
} else {
return null;
}
}
/**
* Checks if the state of a given <code>item</code> has changed since a certain point in time.
* The {@link PersistenceService} identified by the <code>serviceName</code> is used.
*
* @param item the item to check for state changes
* @param the point in time to start the check
* @param serviceName the name of the {@link PersistenceService} to use
* @return true, if item state was updated
*/
static public Boolean updatedSince(Item item, AbstractInstant timestamp, String serviceName) {
Iterable<HistoricItem> result = getAllStatesSince(item, timestamp, serviceName);
if(result.iterator().hasNext()) {
return true;
} else {
return false;
}
}
/**
* Gets the historic item with the maximum value of the state of a given <code>item</code> since
* a certain point in time.
* The default persistence service is used.
*
* @param item the item to get the maximum state value for
* @param the point in time to start the check
* @return a historic item with the maximum state value since the given point in time
*/
static public HistoricItem maximumSince(Item item, AbstractInstant timestamp) {
if(isDefaultServiceAvailable()) {
return maximumSince(item, timestamp, defaultService);
} else {
return null;
}
}
/**
* Gets the historic item with the maximum value of the state of a given <code>item</code> since
* a certain point in time.
* The {@link PersistenceService} identified by the <code>serviceName</code> is used.
*
* @param item the item to get the maximum state value for
* @param the point in time to start the check
* @param serviceName the name of the {@link PersistenceService} to use
* @return a historic item with the maximum state value since the given point in time
*/
static public HistoricItem maximumSince(final Item item, AbstractInstant timestamp, String serviceName) {
Iterable<HistoricItem> result = getAllStatesSince(item, timestamp, serviceName);
Iterator<HistoricItem> it = result.iterator();
HistoricItem maximumHistoricItem = null;
DecimalType maximum = (DecimalType) item.getStateAs(DecimalType.class);
while(it.hasNext()) {
HistoricItem historicItem = it.next();
State state = historicItem.getState();
if (state instanceof DecimalType) {
DecimalType value = (DecimalType) state;
if(maximum==null || value.compareTo(maximum)>0) {
maximum = value;
maximumHistoricItem = historicItem;
}
}
}
if(maximumHistoricItem==null && maximum!=null) {
// the maximum state is the current one, so construct a historic item on the fly
final DecimalType state = maximum;
return new HistoricItem() {
public Date getTimestamp() {
return Calendar.getInstance().getTime();
}
public State getState() {
return state;
}
public String getName() {
return item.getName();
}
};
} else {
return maximumHistoricItem;
}
}
/**
* Gets the historic item with the minimum value of the state of a given <code>item</code> since
* a certain point in time.
* The default persistence service is used.
*
* @param item the item to get the minimum state value for
* @param the point in time to start the check
* @return the historic item with the minimum state value since the given point in time
*/
static public HistoricItem minimumSince(Item item, AbstractInstant timestamp) {
if(isDefaultServiceAvailable()) {
return minimumSince(item, timestamp, defaultService);
} else {
return null;
}
}
/**
* Gets the historic item with the minimum value of the state of a given <code>item</code> since
* a certain point in time.
* The {@link PersistenceService} identified by the <code>serviceName</code> is used.
*
* @param item the item to get the minimum state value for
* @param the point in time to start the check
* @param serviceName the name of the {@link PersistenceService} to use
* @return the historic item with the minimum state value since the given point in time
*/
static public HistoricItem minimumSince(final Item item, AbstractInstant timestamp, String serviceName) {
Iterable<HistoricItem> result = getAllStatesSince(item, timestamp, serviceName);
Iterator<HistoricItem> it = result.iterator();
HistoricItem minimumHistoricItem = null;
DecimalType minimum = (DecimalType) item.getStateAs(DecimalType.class);
while(it.hasNext()) {
HistoricItem historicItem = it.next();
State state = historicItem.getState();
if (state instanceof DecimalType) {
DecimalType value = (DecimalType) state;
if(minimum==null || value.compareTo(minimum)<0) {
minimum = value;
minimumHistoricItem = historicItem;
}
}
}
if(minimumHistoricItem==null && minimum!=null) {
// the minimal state is the current one, so construct a historic item on the fly
final DecimalType state = minimum;
return new HistoricItem() {
public Date getTimestamp() {
return Calendar.getInstance().getTime();
}
public State getState() {
return state;
}
public String getName() {
return item.getName();
}
};
} else {
return minimumHistoricItem;
}
}
/**
* Gets the average value of the state of a given <code>item</code> since a certain point in time.
* The default persistence service is used.
*
* @param item the item to get the average state value for
* @param the point in time to start the check
* @return the average state value since the given point in time
*/
static public DecimalType averageSince(Item item, AbstractInstant timestamp) {
if(isDefaultServiceAvailable()) {
return averageSince(item, timestamp, defaultService);
} else {
return null;
}
}
/**
* Gets the average value of the state of a given <code>item</code> since a certain point in time.
* The {@link PersistenceService} identified by the <code>serviceName</code> is used.
*
* @param item the item to get the average state value for
* @param the point in time to start the check
* @param serviceName the name of the {@link PersistenceService} to use
* @return the average state value since the given point in time
*/
static public DecimalType averageSince(Item item, AbstractInstant timestamp, String serviceName) {
Iterable<HistoricItem> result = getAllStatesSince(item, timestamp, serviceName);
Iterator<HistoricItem> it = result.iterator();
DecimalType value = (DecimalType) item.getStateAs(DecimalType.class);
if (value == null) {
value = DecimalType.ZERO;
}
double average = value.doubleValue();
int quantity = 1;
while(it.hasNext()) {
State state = it.next().getState();
if (state instanceof DecimalType) {
value = (DecimalType) state;
average += value.doubleValue();
quantity++;
}
}
average /= quantity;
return new DecimalType(average);
}
/**
* Query for the last update timestamp of a given <code>item</code>.
* The default persistence service is used.
*
* @param item the item to check for state updates
* @return point in time of the last update or null if none available
*/
static public Date lastUpdate(Item item) {
if(isDefaultServiceAvailable()) {
return lastUpdate(item, defaultService);
} else {
return null;
}
}
/**
* Query for the last update timestamp of a given <code>item</code>.
*
* @param item the item to check for state updates
* @param serviceName the name of the {@link PersistenceService} to use
* @return point in time of the last update or null if none available
*/
static public Date lastUpdate(Item item, String serviceName) {
PersistenceService service = services.get(serviceName);
if (service instanceof QueryablePersistenceService) {
QueryablePersistenceService qService = (QueryablePersistenceService) service;
FilterCriteria filter = new FilterCriteria();
filter.setItemName(item.getName());
filter.setOrdering(Ordering.DESCENDING);
filter.setPageSize(1);
Iterable<HistoricItem> result = qService.query(filter);
if (result.iterator().hasNext()) {
return result.iterator().next().getTimestamp();
} else {
return null;
}
} else {
logger.warn("There is no queryable persistence service registered with the name '{}'", serviceName);
return null;
}
}
/**
* Gets the difference value of the state of a given <code>item</code> since a certain point in time.
* The default persistence service is used.
*
* @param item the item to get the average state value for
* @param the point in time to start the check
* @return the difference between now and then, null if not calculable
*/
static public DecimalType deltaSince(Item item, AbstractInstant timestamp) {
if(isDefaultServiceAvailable()) {
return deltaSince(item, timestamp, defaultService);
} else {
return null;
}
}
/**
* Gets the difference value of the state of a given <code>item</code> since a certain point in time.
* The {@link PersistenceService} identified by the <code>serviceName</code> is used.
*
* @param item the item to get the average state value for
* @param the point in time to start the check
* @param serviceName the name of the {@link PersistenceService} to use
* @return the difference between now and then, null if not calculable
*/
static public DecimalType deltaSince(Item item, AbstractInstant timestamp, String serviceName) {
HistoricItem itemThen = historicState(item, timestamp);
DecimalType valueThen = (DecimalType) itemThen.getState();
DecimalType valueNow = (DecimalType) item.getStateAs(DecimalType.class);
DecimalType result = null;
if (( valueThen != null) && ( valueNow != null)) {
result = new DecimalType(valueNow.doubleValue() - valueThen.doubleValue());
};
return result;
}
/**
* Gets the evolution rate of the state of a given <code>item</code> since a certain point in time.
* The {@link PersistenceService} identified by the <code>serviceName</code> is used.
*
* @param item the item to get the average state value for
* @param the point in time to start the check
* @param serviceName the name of the {@link PersistenceService} to use
* @return the evolution rate in percent (positive and negative) between now and then,
* null if not calculable
*/
static public DecimalType evolutionRate(Item item, AbstractInstant timestamp) {
if(isDefaultServiceAvailable()) {
return evolutionRate(item, timestamp, defaultService);
} else {
return null;
}
}
/**
* Gets the evolution rate of the state of a given <code>item</code> since a certain point in time.
* The {@link PersistenceService} identified by the <code>serviceName</code> is used.
*
* @param item the item to get the average state value for
* @param the point in time to start the check
* @param serviceName the name of the {@link PersistenceService} to use
* @return the evolution rate in percent (positive and negative) between now and then,
* null if not calculable
*/
static public DecimalType evolutionRate(Item item, AbstractInstant timestamp, String serviceName) {
HistoricItem itemThen = historicState(item, timestamp);
DecimalType valueThen = (DecimalType) itemThen.getState();
DecimalType valueNow = (DecimalType) item.getStateAs(DecimalType.class);
DecimalType result = null;
if (( valueThen != null) && ( valueNow != null)) {
result = new DecimalType(100 * (valueNow.doubleValue() - valueThen.doubleValue()) / valueThen.doubleValue());
};
return result;
}
/**
* Returns the previous state of a given <code>item</code>.
* If the item is uninitialized/undefined, the last saved state is returned.
*
* @param item the item to get the average state value for
* @return the parent state not equal the current state
*/
static public HistoricItem previousState(Item item) {
if (isDefaultServiceAvailable()) {
return previousState(item, defaultService);
} else {
return null;
}
}
/**
* Returns the previous state of a given <code>item</code>.
* The {@link PersistenceService} identified by the <code>serviceName</code> is used.
* If the item is uninitialized/undefined, the last saved state is returned.
*
* @param item the item to get the average state value for
* @return the parent state not equal the current state
*/
static public HistoricItem previousState(Item item, String serviceName) {
PersistenceService service = services.get(serviceName);
if (service instanceof QueryablePersistenceService) {
QueryablePersistenceService qService = (QueryablePersistenceService) service;
FilterCriteria filter = new FilterCriteria();
filter.setItemName(item.getName());
filter.setOrdering(Ordering.DESCENDING);
filter.setPageSize(1000);
int startPage = 0;
filter.setPageNumber(startPage);
Iterable<HistoricItem> items = qService.query(filter);
while (items != null) {
Iterator<HistoricItem> itemIterator = items.iterator();
int itemCount = 0;
while (itemIterator.hasNext()) {
HistoricItem historicItem = itemIterator.next();
itemCount++;
if (!historicItem.getState().equals(item.getState())) {
return historicItem;
}
}
if (itemCount == filter.getPageSize()) {
filter.setPageNumber(++startPage);
items = qService.query(filter);
}
else {
items = null;
}
}
return null;
} else {
logger.warn("There is no queryable persistence service registered with the name '{}'", serviceName);
return null;
}
}
static private Iterable<HistoricItem> getAllStatesSince(Item item, AbstractInstant timestamp, String serviceName) {
PersistenceService service = services.get(serviceName);
if (service instanceof QueryablePersistenceService) {
QueryablePersistenceService qService = (QueryablePersistenceService) service;
FilterCriteria filter = new FilterCriteria();
filter.setBeginDate(timestamp.toDate());
filter.setItemName(item.getName());
filter.setOrdering(Ordering.ASCENDING);
return qService.query(filter);
} else {
logger.warn("There is no queryable persistence service registered with the name '{}'", serviceName);
return Collections.emptySet();
}
}
/**
* Returns <code>true</code>, if a default service is configured and returns <code>false</code> and logs a warning otherwise.
* @return true, if a default service is available
*/
static private boolean isDefaultServiceAvailable() {
if(defaultService!=null) {
return true;
} else {
logger.warn("No default persistence service is configured in openhab.cfg!");
return false;
}
}
@SuppressWarnings("rawtypes")
public void updated(Dictionary config) throws ConfigurationException {
if (config!=null) {
PersistenceExtensions.defaultService = (String) config.get("default");
}
}
} |
package org.csstudio.platform.internal.jaasauthentication;
import org.csstudio.platform.AbstractCssPlugin;
import org.osgi.framework.BundleContext;
/** The activator class controls the plug-in life cycle
* @author Original author unknown
* @author Kay Kasemir
*/
public class Activator extends AbstractCssPlugin {
/** The plug-in ID as defined in MANIFEST.MF */
public static final String PLUGIN_ID = "org.csstudio.platform.jaasAuthentication";
// The shared instance
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
plugin = this;
}
@Override
protected void doStart(BundleContext context) throws Exception {
}
@Override
protected void doStop(BundleContext context) throws Exception {
plugin = null;
}
@Override
public String getPluginId() {
return PLUGIN_ID;
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
} |
package net.safedata.springboot.training.d01.s05.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.Arrays;
/**
* A simple product {@link Service}, which wires the configured properties using the {@link Value} annotation
*
* @author bogdan.solga
*/
@Service
public class ProductService {
@Value("${remote.endpoint.url:let's see a default value with spaces}")
private String remoteEndpointURL;
@Value("${metrics.enabled}")
private boolean metricsEnabled;
@Value("${connection.timeout}")
private int connectionTimeout;
@Value("${version.number:2.5}")
private Double versionNumber;
@Value("${external.property}")
private String externalProperty;
@Value("${array.of.strings}")
private String[] arrayOfStrings;
public void displayLoadedProperties() {
System.out.println("The remote endpoint is '" + remoteEndpointURL + "'");
System.out.println("The metrics are enabled: " + metricsEnabled);
System.out.println("The connection timeout is " + connectionTimeout);
System.out.println("The version number is " + versionNumber);
System.out.println("An array of Strings: " + Arrays.asList(arrayOfStrings));
System.out.println();
System.out.println("The external property is '" + externalProperty + "'");
}
} |
package org.innovateuk.ifs.activitylog.transactional;
import org.innovateuk.ifs.activitylog.domain.ActivityLog;
import org.innovateuk.ifs.activitylog.repository.ActivityLogRepository;
import org.innovateuk.ifs.activitylog.resource.ActivityLogResource;
import org.innovateuk.ifs.activitylog.resource.ActivityType;
import org.innovateuk.ifs.application.domain.Application;
import org.innovateuk.ifs.application.repository.ApplicationRepository;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.competitionsetup.domain.CompetitionDocument;
import org.innovateuk.ifs.competitionsetup.repository.CompetitionDocumentConfigRepository;
import org.innovateuk.ifs.finance.domain.ProjectFinance;
import org.innovateuk.ifs.finance.repository.ProjectFinanceRepository;
import org.innovateuk.ifs.organisation.domain.Organisation;
import org.innovateuk.ifs.organisation.repository.OrganisationRepository;
import org.innovateuk.ifs.project.core.domain.Project;
import org.innovateuk.ifs.project.core.repository.ProjectRepository;
import org.innovateuk.ifs.threads.domain.Query;
import org.innovateuk.ifs.threads.repository.QueryRepository;
import org.innovateuk.ifs.threads.resource.FinanceChecksSectionType;
import org.innovateuk.ifs.user.domain.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.time.ZonedDateTime;
import java.util.List;
import java.util.Optional;
import static java.time.ZonedDateTime.now;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import static org.innovateuk.ifs.application.builder.ApplicationBuilder.newApplication;
import static org.innovateuk.ifs.competition.builder.CompetitionDocumentBuilder.newCompetitionDocument;
import static org.innovateuk.ifs.finance.domain.builder.ProjectFinanceBuilder.newProjectFinance;
import static org.innovateuk.ifs.organisation.builder.OrganisationBuilder.newOrganisation;
import static org.innovateuk.ifs.project.core.builder.ProjectBuilder.newProject;
import static org.innovateuk.ifs.user.builder.UserBuilder.newUser;
import static org.innovateuk.ifs.user.resource.Role.PROJECT_FINANCE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.util.ReflectionTestUtils.setField;
@RunWith(MockitoJUnitRunner.class)
public class ActivityLogServiceImplTest {
private static final ActivityType TEST_ACTIVITY_TYPE = ActivityType.APPLICATION_SUBMITTED;
@InjectMocks
private ActivityLogServiceImpl activityLogService;
@Mock
private ActivityLogRepository activityLogRepository;
@Mock
private ApplicationRepository applicationRepository;
@Mock
private QueryRepository queryRepository;
@Mock
private ProjectFinanceRepository projectFinanceRepository;
@Mock
private CompetitionDocumentConfigRepository competitionDocumentConfigRepository;
@Mock
private ProjectRepository projectRepository;
@Mock
private OrganisationRepository organisationRepository;
@Test
public void recordActivityByApplicationId() {
Application application = newApplication().build();
when(applicationRepository.findById(application.getId())).thenReturn(Optional.of(application));
activityLogService.recordActivityByApplicationId(application.getId(), TEST_ACTIVITY_TYPE);
verify(activityLogRepository).save(new ActivityLog(application, TEST_ACTIVITY_TYPE));
}
@Test
public void recordActivityByProjectId() {
Application application = newApplication().build();
Project project = newProject().withApplication(application).build();
when(projectRepository.findById(project.getId())).thenReturn(Optional.of(project));
activityLogService.recordActivityByProjectId(project.getId(), TEST_ACTIVITY_TYPE);
verify(activityLogRepository).save(new ActivityLog(application, TEST_ACTIVITY_TYPE));
}
@Test
public void recordActivityByProjectIdAndOrganisationId() {
Application application = newApplication().build();
Project project = newProject().withApplication(application).build();
Organisation organisation = newOrganisation().build();
when(projectRepository.findById(project.getId())).thenReturn(Optional.of(project));
when(organisationRepository.findById(organisation.getId())).thenReturn(Optional.of(organisation));
activityLogService.recordActivityByProjectIdAndOrganisationId(project.getId(), organisation.getId(), TEST_ACTIVITY_TYPE);
verify(activityLogRepository).save(new ActivityLog(application, TEST_ACTIVITY_TYPE, organisation));
}
@Test
public void recordDocumentActivityByProjectId() {
Application application = newApplication().build();
Project project = newProject().withApplication(application).build();
CompetitionDocument documentConfig = newCompetitionDocument().build();
when(projectRepository.findById(project.getId())).thenReturn(Optional.of(project));
when(competitionDocumentConfigRepository.findById(documentConfig.getId())).thenReturn(Optional.of(documentConfig));
activityLogService.recordDocumentActivityByProjectId(project.getId(), TEST_ACTIVITY_TYPE, documentConfig.getId());
verify(activityLogRepository).save(new ActivityLog(application, TEST_ACTIVITY_TYPE, documentConfig));
}
@Test
public void recordQueryActivityByProjectFinanceId() {
Application application = newApplication().build();
Project project = newProject().withApplication(application).build();
Organisation organisation = newOrganisation().build();
ProjectFinance projectFinance = newProjectFinance()
.withProject(project)
.withOrganisation(organisation)
.build();
Query query = new Query(1L, null, null, null, null, null, null);
when(projectFinanceRepository.findById(projectFinance.getId())).thenReturn(Optional.of(projectFinance));
when(queryRepository.findById(query.id())).thenReturn(Optional.of(query));
activityLogService.recordQueryActivityByProjectFinanceId(projectFinance.getId(),TEST_ACTIVITY_TYPE, query.id());
verify(activityLogRepository).save(new ActivityLog(application, TEST_ACTIVITY_TYPE, query, organisation));
}
@Test
public void findByApplicationId() {
long applicationId = 1L;
Application application = newApplication().build();
Organisation organisation = newOrganisation()
.withName("My organisation")
.build();
Query query = new Query(1L, null, null, null, FinanceChecksSectionType.VIABILITY, null, null);
CompetitionDocument competitionDocument = newCompetitionDocument()
.withTitle("My document")
.build();
User createdBy = newUser()
.withFirstName("Bob")
.withLastName("Name")
.withRoles(singleton(PROJECT_FINANCE))
.build();
ZonedDateTime createdOn = now();
ActivityLog activityLog = new ActivityLog(application, TEST_ACTIVITY_TYPE, query, organisation);
setField(activityLog, "createdOn", createdOn);
setField(activityLog, "createdBy", createdBy);
setField(activityLog, "competitionDocument", competitionDocument);
when(activityLogRepository.findByApplicationIdOrderByCreatedOnDesc(applicationId)).thenReturn(singletonList(activityLog));
ServiceResult<List<ActivityLogResource>> result = activityLogService.findByApplicationId(applicationId);
assertTrue(result.isSuccess());
assertEquals(1, result.getSuccess().size());
ActivityLogResource activityLogResource = result.getSuccess().get(0);
assertEquals(TEST_ACTIVITY_TYPE, activityLogResource.getActivityType());
assertEquals(createdBy.getId().longValue(), activityLogResource.getAuthoredBy());
assertEquals("Bob Name", activityLogResource.getAuthoredByName());
assertEquals(singleton(PROJECT_FINANCE), activityLogResource.getAuthoredByRoles());
assertEquals(createdOn, activityLogResource.getCreatedOn());
assertEquals(competitionDocument.getId(), activityLogResource.getDocumentConfig());
assertEquals("My document", activityLogResource.getDocumentConfigName());
assertEquals(organisation.getId(), activityLogResource.getOrganisation());
assertEquals("My organisation", activityLogResource.getOrganisationName());
assertEquals(query.id(), activityLogResource.getQuery());
assertEquals(FinanceChecksSectionType.VIABILITY, activityLogResource.getQueryType());
assertTrue(activityLogResource.isOrganisationRemoved());
}
} |
package org.motechproject.scheduletracking.api.service.impl;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.motechproject.event.MotechEvent;
import org.motechproject.event.listener.EventRelay;
import org.motechproject.scheduler.MotechSchedulerService;
import org.motechproject.scheduler.domain.RepeatingSchedulableJob;
import org.motechproject.scheduletracking.api.domain.Alert;
import org.motechproject.scheduletracking.api.domain.AlertWindow;
import org.motechproject.scheduletracking.api.domain.Enrollment;
import org.motechproject.scheduletracking.api.domain.Milestone;
import org.motechproject.scheduletracking.api.domain.MilestoneAlert;
import org.motechproject.scheduletracking.api.domain.MilestoneWindow;
import org.motechproject.scheduletracking.api.domain.Schedule;
import org.motechproject.scheduletracking.api.events.MilestoneEvent;
import org.motechproject.scheduletracking.api.events.constants.EventSubjects;
import org.motechproject.scheduletracking.api.service.MilestoneAlerts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import static org.motechproject.commons.date.util.DateUtil.now;
@Component
public class EnrollmentAlertService {
public static final int MILLIS_IN_A_SEC = 1000;
private MotechSchedulerService schedulerService;
private EventRelay eventRelay;
@Autowired
public EnrollmentAlertService(MotechSchedulerService schedulerService, EventRelay eventRelay) {
this.schedulerService = schedulerService;
this.eventRelay = eventRelay;
}
public void scheduleAlertsForCurrentMilestone(Enrollment enrollment) {
Schedule schedule = enrollment.getSchedule();
Milestone currentMilestone = schedule.getMilestone(enrollment.getCurrentMilestoneName());
if (currentMilestone == null) {
return;
}
DateTime currentMilestoneStartDate = enrollment.getCurrentMilestoneStartDate();
for (MilestoneWindow milestoneWindow : currentMilestone.getMilestoneWindows()) {
if (currentMilestone.windowElapsed(milestoneWindow.getName(), currentMilestoneStartDate)) {
continue;
}
MilestoneAlert milestoneAlert = MilestoneAlert.fromMilestone(currentMilestone, currentMilestoneStartDate);
for (Alert alert : milestoneWindow.getAlerts()) {
scheduleAlertJob(alert, enrollment, currentMilestone, milestoneWindow, milestoneAlert);
}
}
}
public MilestoneAlerts getAlertTimings(Enrollment enrollment) {
Schedule schedule = enrollment.getSchedule();
Milestone currentMilestone = schedule.getMilestone(enrollment.getCurrentMilestoneName());
MilestoneAlerts milestoneAlerts = new MilestoneAlerts();
if (currentMilestone == null) {
return milestoneAlerts;
}
for (MilestoneWindow milestoneWindow : currentMilestone.getMilestoneWindows()) {
List<DateTime> alertTimingsForWindow = new ArrayList<DateTime>();
for (Alert alert : milestoneWindow.getAlerts()) {
AlertWindow alertWindow = createAlertWindowFor(alert, enrollment, currentMilestone, milestoneWindow);
alertTimingsForWindow.addAll(alertWindow.allPossibleAlerts());
}
milestoneAlerts.getAlertTimings().put(milestoneWindow.getName().toString(), alertTimingsForWindow);
}
return milestoneAlerts;
}
private void scheduleAlertJob(Alert alert, Enrollment enrollment, Milestone currentMilestone, MilestoneWindow milestoneWindow, MilestoneAlert milestoneAlert) {
MotechEvent event = new MilestoneEvent(enrollment, milestoneAlert, milestoneWindow).toMotechEvent();
event.getParameters().put(MotechSchedulerService.JOB_ID_KEY, String.format("%s.%d", enrollment.getId(), alert.getIndex()));
long repeatIntervalInMillis = (long) alert.getInterval().toStandardSeconds().getSeconds() * MILLIS_IN_A_SEC;
AlertWindow alertWindow = createAlertWindowFor(alert, enrollment, currentMilestone, milestoneWindow);
if (alertWindow.numberOfAlertsToSchedule() > 0) {
int numberOfAlertsToFire = alertWindow.numberOfAlertsToSchedule() - 1;
DateTime alertsStartTime = alertWindow.scheduledAlertStartDate();
if (alertsStartTime.isBefore(now())) {
alertsStartTime = alertsStartTime.plus(repeatIntervalInMillis);
numberOfAlertsToFire = numberOfAlertsToFire - 1;
eventRelay.sendEventMessage(event);
}
RepeatingSchedulableJob job = new RepeatingSchedulableJob()
.setMotechEvent(event)
.setStartTime(alertsStartTime.toDate())
.setEndTime(null)
.setRepeatCount(numberOfAlertsToFire)
.setRepeatIntervalInMilliSeconds(repeatIntervalInMillis)
.setIgnorePastFiresAtStart(false);
schedulerService.safeScheduleRepeatingJob(job);
}
}
private AlertWindow createAlertWindowFor(Alert alert, Enrollment enrollment, Milestone currentMilestone, MilestoneWindow milestoneWindow) {
Period windowStart = currentMilestone.getWindowStart(milestoneWindow.getName());
Period windowEnd = currentMilestone.getWindowEnd(milestoneWindow.getName());
DateTime currentMilestoneStartDate = enrollment.getCurrentMilestoneStartDate();
DateTime windowStartDateTime = currentMilestoneStartDate.plus(windowStart);
DateTime windowEndDateTime = currentMilestoneStartDate.plus(windowEnd);
return new AlertWindow(windowStartDateTime, windowEndDateTime, enrollment.getEnrolledOn(), enrollment.getPreferredAlertTime(), alert);
}
public void unscheduleAllAlerts(Enrollment enrollment) {
schedulerService.safeUnscheduleAllJobs(String.format("%s-%s", EventSubjects.MILESTONE_ALERT, enrollment.getId()));
}
} |
package org.opendaylight.controller.messagebus.app.impl;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.regex.Pattern;
import org.opendaylight.controller.md.sal.binding.api.DataBroker;
import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
import org.opendaylight.controller.messagebus.spi.EventSource;
import org.opendaylight.controller.messagebus.spi.EventSourceRegistration;
import org.opendaylight.controller.messagebus.spi.EventSourceRegistry;
import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration;
import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RpcRegistration;
import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.CreateTopicInput;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.CreateTopicOutput;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.CreateTopicOutputBuilder;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.DestroyTopicInput;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.EventAggregatorService;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventaggregator.rev141202.NotificationPattern;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.EventSourceService;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.Node1;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.Node1Builder;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.TopologyTypes1;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.TopologyTypes1Builder;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.topology.event.source.type.TopologyEventSource;
import org.opendaylight.yang.gen.v1.urn.cisco.params.xml.ns.yang.messagebus.eventsource.rev141202.topology.event.source.type.TopologyEventSourceBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeContext;
import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.TopologyTypes;
import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
public class EventSourceTopology implements EventAggregatorService, EventSourceRegistry {
private static final Logger LOG = LoggerFactory.getLogger(EventSourceTopology.class);
private static final String TOPOLOGY_ID = "EVENT-SOURCE-TOPOLOGY" ;
private static final TopologyKey EVENT_SOURCE_TOPOLOGY_KEY = new TopologyKey(new TopologyId(TOPOLOGY_ID));
private static final LogicalDatastoreType OPERATIONAL = LogicalDatastoreType.OPERATIONAL;
private static final InstanceIdentifier<Topology> EVENT_SOURCE_TOPOLOGY_PATH =
InstanceIdentifier.create(NetworkTopology.class)
.child(Topology.class, EVENT_SOURCE_TOPOLOGY_KEY);
private static final InstanceIdentifier<TopologyTypes1> TOPOLOGY_TYPE_PATH =
EVENT_SOURCE_TOPOLOGY_PATH
.child(TopologyTypes.class)
.augmentation(TopologyTypes1.class);
private final Map<EventSourceTopic, ListenerRegistration<DataChangeListener>> topicListenerRegistrations =
new ConcurrentHashMap<>();
private final Map<NodeKey, RoutedRpcRegistration<EventSourceService>> routedRpcRegistrations =
new ConcurrentHashMap<>();
private final DataBroker dataBroker;
private final RpcRegistration<EventAggregatorService> aggregatorRpcReg;
private final EventSourceService eventSourceService;
private final RpcProviderRegistry rpcRegistry;
public EventSourceTopology(final DataBroker dataBroker, final RpcProviderRegistry rpcRegistry) {
this.dataBroker = dataBroker;
this.rpcRegistry = rpcRegistry;
aggregatorRpcReg = rpcRegistry.addRpcImplementation(EventAggregatorService.class, this);
eventSourceService = rpcRegistry.getRpcService(EventSourceService.class);
final TopologyEventSource topologySource = new TopologyEventSourceBuilder().build();
final TopologyTypes1 topologyTypeAugment = new TopologyTypes1Builder().setTopologyEventSource(topologySource).build();
putData(OPERATIONAL, TOPOLOGY_TYPE_PATH, topologyTypeAugment);
LOG.info("EventSourceRegistry has been initialized");
}
private <T extends DataObject> void putData(final LogicalDatastoreType store,
final InstanceIdentifier<T> path,
final T data){
final WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
tx.put(store, path, data, true);
tx.submit();
}
private <T extends DataObject> void deleteData(final LogicalDatastoreType store, final InstanceIdentifier<T> path){
final WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
tx.delete(OPERATIONAL, path);
tx.submit();
}
private void insert(final KeyedInstanceIdentifier<Node, NodeKey> sourcePath) {
final NodeKey nodeKey = sourcePath.getKey();
final InstanceIdentifier<Node1> augmentPath = sourcePath.augmentation(Node1.class);
final Node1 nodeAgument = new Node1Builder().setEventSourceNode(new NodeId(nodeKey.getNodeId().getValue())).build();
putData(OPERATIONAL, augmentPath, nodeAgument);
}
private void remove(final KeyedInstanceIdentifier<Node, NodeKey> sourcePath){
final InstanceIdentifier<Node1> augmentPath = sourcePath.augmentation(Node1.class);
deleteData(OPERATIONAL, augmentPath);
}
private void notifyExistingNodes(final Pattern nodeIdPatternRegex, final EventSourceTopic eventSourceTopic){
final ReadOnlyTransaction tx = dataBroker.newReadOnlyTransaction();
final CheckedFuture<Optional<Topology>, ReadFailedException> future = tx.read(OPERATIONAL, EVENT_SOURCE_TOPOLOGY_PATH);
Futures.addCallback(future, new FutureCallback<Optional<Topology>>(){
@Override
public void onSuccess(Optional<Topology> data) {
if(data.isPresent()) {
final List<Node> nodes = data.get().getNode();
for (final Node node : nodes) {
if (nodeIdPatternRegex.matcher(node.getNodeId().getValue()).matches()) {
eventSourceTopic.notifyNode(EVENT_SOURCE_TOPOLOGY_PATH.child(Node.class, node.getKey()));
}
}
}
tx.close();
}
@Override
public void onFailure(Throwable t) {
LOG.error("Can not notify existing nodes {}", t);
tx.close();
}
});
}
@Override
public Future<RpcResult<CreateTopicOutput>> createTopic(final CreateTopicInput input) {
LOG.info("Received Topic creation request: NotificationPattern -> {}, NodeIdPattern -> {}",
input.getNotificationPattern(),
input.getNodeIdPattern());
final NotificationPattern notificationPattern = new NotificationPattern(input.getNotificationPattern());
final String nodeIdPattern = input.getNodeIdPattern().getValue();
final Pattern nodeIdPatternRegex = Pattern.compile(Util.wildcardToRegex(nodeIdPattern));
final EventSourceTopic eventSourceTopic = new EventSourceTopic(notificationPattern, nodeIdPattern, eventSourceService);
registerTopic(eventSourceTopic);
notifyExistingNodes(nodeIdPatternRegex, eventSourceTopic);
final CreateTopicOutput cto = new CreateTopicOutputBuilder()
.setTopicId(eventSourceTopic.getTopicId())
.build();
return Util.resultRpcSuccessFor(cto);
}
@Override
public Future<RpcResult<Void>> destroyTopic(final DestroyTopicInput input) {
return Futures.immediateFailedFuture(new UnsupportedOperationException("Not Implemented"));
}
@Override
public void close() {
aggregatorRpcReg.close();
for(ListenerRegistration<DataChangeListener> reg : topicListenerRegistrations.values()){
reg.close();
}
}
private void registerTopic(final EventSourceTopic listener) {
final ListenerRegistration<DataChangeListener> listenerRegistration = dataBroker.registerDataChangeListener(OPERATIONAL,
EVENT_SOURCE_TOPOLOGY_PATH,
listener,
DataBroker.DataChangeScope.SUBTREE);
topicListenerRegistrations.put(listener, listenerRegistration);
}
public void register(final EventSource eventSource){
NodeKey nodeKey = eventSource.getSourceNodeKey();
final KeyedInstanceIdentifier<Node, NodeKey> sourcePath = EVENT_SOURCE_TOPOLOGY_PATH.child(Node.class, nodeKey);
RoutedRpcRegistration<EventSourceService> reg = rpcRegistry.addRoutedRpcImplementation(EventSourceService.class, eventSource);
reg.registerPath(NodeContext.class, sourcePath);
routedRpcRegistrations.put(nodeKey,reg);
insert(sourcePath);
for(EventSourceTopic est : topicListenerRegistrations.keySet()){
est.notifyNode(EVENT_SOURCE_TOPOLOGY_PATH.child(Node.class, nodeKey));
}
}
public void unRegister(final EventSource eventSource){
final NodeKey nodeKey = eventSource.getSourceNodeKey();
final KeyedInstanceIdentifier<Node, NodeKey> sourcePath = EVENT_SOURCE_TOPOLOGY_PATH.child(Node.class, nodeKey);
final RoutedRpcRegistration<EventSourceService> removeRegistration = routedRpcRegistrations.remove(nodeKey);
if(removeRegistration != null){
removeRegistration.close();
remove(sourcePath);
}
}
@Override
public <T extends EventSource> EventSourceRegistration<T> registerEventSource(
T eventSource) {
EventSourceRegistrationImpl<T> esr = new EventSourceRegistrationImpl<>(eventSource, this);
register(eventSource);
return esr;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.