answer
stringlengths
17
10.2M
package seedu.whatnow.model.task; import java.text.DateFormat; import java.text.SimpleDateFormat; import org.ocpsoft.prettytime.PrettyTime; import seedu.whatnow.commons.exceptions.IllegalValueException; public class TaskTime { // public static final String TWENTY_FOUR_HOUR_FORMAT = "HHmm"; //E.g. 2359 public static final String TWELVE_HOUR_WITH_MINUTES_COLON_FORMAT = "h:mm a"; //E.g. 1:50 pm public static final String TWELVE_HOUR_WITH_MINUTES_DOT_FORMAT = "h.mm a"; //E.g. 1.45 pm public static final String TWELVE_HOUR_WITHOUT_MINUTES_FORMAT = "ha"; //E.g. 2pm public static final String DATE_NUM_SLASH_WITH_YEAR_FORMAT = "dd/MM/yyyy"; public static final String DATE_NUM_SLASH_WITH_YEAR_SHORTENED_DAY_FORMAT = "d/MM/yyyy"; public static final String DATE_NUM_SLASH_WITH_YEAR_SHORTENED_MONTH_FORMAT = "dd/M/yyyy"; public static final String DATE_NUM_SLASH_WITH_YEAR_SHORTENED_DAY_AND_MONTH_FORMAT = "d/M/yyyy"; public static final String DATE_NUM_SLASH_WITHOUT_YEAR_FORMAT = "dd/MM"; public static final String DATE_NUM_SLASH_WITHOUT_YEAR_SHORTENED_DAY_FORMAT = "d/MM"; public static final String DATE_NUM_SLASH_WITHOUT_YEAR_SHORTEND_DAY_MONTH_FORMAT = "d/M"; public static final String DATE_AlPHA_WHITESPACE_WITH_YEAR_FORMAT = "dd MMMM yyyy "; public static final String DATE_ALPHA_WHITESPACE_WITHOUT_YEAR_FORMAT = "dd MMMM"; public final String INVALID_TIME_MESSAGE = "Entered an invalid time format"; public final String INVALID_TIME_RANGE_MESSAGE = "Entered an invalid time range format"; public final String INVALID_DATE_MESSAGE = "Entered an invalid date format"; public final String INVALID_DATE_RANGE_MESSAGE = "Entered and invalid date range format"; private final String time; private final String startTime; private final String endTime; private final String date; private final String startDate; private final String endDate; public TaskTime(String time, String startTime, String endTime, String date, String startDate, String endDate) throws IllegalValueException{ PrettyTime p = new PrettyTime(); if(!isValidTime(time)) { throw new IllegalValueException(INVALID_TIME_MESSAGE); } this.time = time; if(!isValidTimeRange(startTime, endTime)) { throw new IllegalValueException(INVALID_TIME_RANGE_MESSAGE); } this.startTime = startTime; this.endTime = endTime; if(!isValidDate(date)) { throw new IllegalValueException(INVALID_DATE_MESSAGE); } this.date = date; if(!isValidDateRange(startDate, endDate)) { throw new IllegalValueException(INVALID_DATE_RANGE_MESSAGE); } this.startDate = startDate; this.endDate = endDate; } /** returns time */ public String getTime() { return this.time; } /** returns startTime */ public String getStartTime() { return this.startTime; } /** returns endTime */ public String getEndTime() { return this.endTime; } /** returns currentDate */ public String getDate() { return this.date; } /** returns startDate */ public String getStartDate() { return this.startDate; } /** returns endDate */ public String getEndDate() { return this.endDate; } /** * Checks if a particular time is valid i.e. time is not before current time and is of valid sequence * @return true if valid, else return false */ public boolean isValidTime(String reqTime) { //i.e. not a deadline but a schedule if(reqTime == null) { return true; }else { return false; } } /** * Checks if a particular time range is valid i.e. startTime is before endTime * @return true if valid, else return false */ public boolean isValidTimeRange(String beforeTime, String afterTime) { return false; } /** * Checks if a particular date is valid i.e. not before currentDate and is a valid sequence * @return true if valid, else return false */ public boolean isValidDate(String reqDate) { if(reqDate == null) { return true; } else if(reqDate.toLowerCase().equals("today")) { return true; } else if(reqDate.toLowerCase().equals("tomorrow")) { return true; } else { DateFormat df1 = new SimpleDateFormat(DATE_NUM_SLASH_WITH_YEAR_FORMAT); //e.g. 19/10/2016 DateFormat df2 = new SimpleDateFormat(DATE_NUM_SLASH_WITH_YEAR_SHORTENED_DAY_FORMAT); //e.g. 1/10/2017 DateFormat df3 = new SimpleDateFormat(DATE_NUM_SLASH_WITH_YEAR_SHORTENED_MONTH_FORMAT); //e.g. 01/1/2017 DateFormat df4 = new SimpleDateFormat(DATE_NUM_SLASH_WITH_YEAR_SHORTENED_DAY_AND_MONTH_FORMAT); //e.g. 2/2/2017 DateFormat df5 = new SimpleDateFormat(DATE_NUM_SLASH_WITHOUT_YEAR_FORMAT); //e.g. 10/12 DateFormat df6 = new SimpleDateFormat(DATE_NUM_SLASH_WITHOUT_YEAR_SHORTENED_DAY_FORMAT); // e.g. 1/12 DateFormat df7 = new SimpleDateFormat(DATE_NUM_SLASH_WITHOUT_YEAR_SHORTEND_DAY_MONTH_FORMAT); //e.g. 1/1 return false; } } /** * Checks if a particular Date range is valid i.e. startDate is before endDate * @return true if range is valid, false if range is invalid */ public boolean isValidDateRange(String beforeDate, String afterDate) { return false; } }
package net.hearthstats.state; /** * Defines pixel tests that aren't in the standard locations. * They are usually used to identify elements on specific screens, * rather than to identify a screen itself. */ public enum UniquePixel { OPPONENT_DRUID_1 (1161, 185, 175, 225, 212, 235, 255, 255), OPPONENT_DRUID_2 (1379, 221, 201, 225, 222, 255, 255, 255), OPPONENT_DRUID_3 (1197, 336, 173, 130, 168, 233, 190, 228), OPPONENT_HUNTER_1 (1290, 104, 143, 148, 153, 203, 208, 213), OPPONENT_HUNTER_2 (1279, 274, 111, 7, 0, 171, 67, 30), OPPONENT_HUNTER_3 (1155, 483, 186, 184, 181, 246, 244, 241), OPPONENT_MAGE_1 (1235, 107, 58, 0, 69, 118, 53, 129), OPPONENT_MAGE_2 (1232, 488, 185, 158, 147, 245, 218, 207), OPPONENT_MAGE_3 (1282, 386, 23, 34, 52, 83, 94, 112), OPPONENT_PALADIN_1 (1399, 333, 225, 217, 117, 255, 255, 177), OPPONENT_PALADIN_2 (1275, 471, 95, 207, 225, 155, 255, 255), OPPONENT_PALADIN_3 (1199, 129, 103, 77, 138, 163, 137, 198), OPPONENT_PRIEST_1 (1132, 296, 225, 206, 71, 255, 255, 131), OPPONENT_PRIEST_2 (1244, 380, 28, 42, 108, 88, 102, 168), OPPONENT_PRIEST_3 (1379, 232, 0, 0, 8, 57, 50, 68), OPPONENT_ROGUE_1 (1390, 397, 102, 166, 42, 162, 226, 102), OPPONENT_ROGUE_2 (1235, 427, 58, 0, 4, 118, 51, 64), OPPONENT_ROGUE_3 (1315, 115, 70, 79, 153, 130, 139, 213), OPPONENT_SHAMAN_1 (1169, 147, 0, 20, 70, 35, 80, 130), OPPONENT_SHAMAN_2 (1386, 265, 204, 20, 2, 255, 80, 62), OPPONENT_SHAMAN_3 (1146, 322, 156, 225, 225, 216, 255, 255), OPPONENT_WARLOCK_1 (1111, 318, 97, 112, 6, 157, 172, 66), OPPONENT_WARLOCK_2 (1300, 413, 210, 214, 222, 255, 255, 255), OPPONENT_WARLOCK_3 (1300, 102, 68, 99, 0, 128, 159, 30), OPPONENT_WARRIOR_1 (1243, 100, 7, 0, 0, 67, 34, 30), OPPONENT_WARRIOR_2 (1219, 130, 137, 0, 0, 197, 53, 34), OPPONENT_WARRIOR_3 (1265, 144, 225, 217, 197, 255, 255, 255), YOUR_DRUID_1 ( 352, 750, 180, 225, 216, 240, 255, 255), YOUR_DRUID_2 ( 544, 797, 204, 225, 221, 255, 255, 255), YOUR_DRUID_3 ( 311, 888, 145, 40, 165, 200, 100, 205), YOUR_HUNTER_1 ( 365, 779, 10, 10, 10, 60, 60, 60), YOUR_HUNTER_2 ( 605, 1013, 0, 0, 0, 50, 50, 50), YOUR_HUNTER_3 ( 463, 680, 158, 158, 158, 190, 200, 210), YOUR_HUNTER_GOLDEN_1( 365, 779, 10, 10, 10, 60, 60, 60), YOUR_HUNTER_GOLDEN_2( 605, 1013, 63, 60, 50, 123, 120, 110), YOUR_HUNTER_GOLDEN_3( 463, 682, 155, 155, 155, 195, 195, 195), YOUR_MAGE_1 ( 405, 686, 66, 1, 72, 126, 61, 132), YOUR_MAGE_2 ( 457, 1059, 189, 180, 155, 249, 240, 200), YOUR_MAGE_3 ( 338, 924, 0, 0, 26, 30 , 30, 86), YOUR_PALADIN_1 ( 390, 699, 103, 75, 135, 163, 135, 195), YOUR_PALADIN_2 ( 475, 1049, 44, 116, 204, 104, 176, 255), YOUR_PALADIN_3 ( 573, 906, 220, 215, 110, 255, 255, 180), YOUR_PRIEST_1 ( 358, 768, 150, 148, 136, 210, 208, 196), YOUR_PRIEST_2 ( 400, 941, 52, 74, 174, 112, 134, 234), YOUR_PRIEST_3 ( 547, 955, 0, 0, 0, 45, 45, 45), YOUR_ROGUE_1 ( 483, 697, 61, 77, 145, 121, 137, 205), YOUR_ROGUE_2 ( 442, 718, 110, 0, 0, 180, 40, 50), YOUR_ROGUE_3 ( 566, 974, 92, 156, 37, 152, 216, 97), YOUR_SHAMAN_1 ( 349, 716, 0, 16, 63, 34, 76, 123), YOUR_SHAMAN_2 ( 563, 833, 180, 10, 0, 250, 50, 20), YOUR_SHAMAN_3 ( 324, 904, 147, 215, 219, 207, 255, 255), YOUR_WARLOCK_1 ( 471, 680, 74, 108, 0, 134, 168, 38), YOUR_WARLOCK_2 ( 414, 768, 180, 10, 0, 255, 80, 50), YOUR_WARLOCK_3 ( 460, 1063, 30, 45, 152, 90, 105, 212), YOUR_WARRIOR_1 ( 394, 707, 133, 0, 0, 193, 40, 30), YOUR_WARRIOR_2 ( 455, 905, 204, 162, 25, 255, 222, 90), YOUR_WARRIOR_3 ( 438, 721, 225, 215, 195, 255, 255, 255), COIN_1 (1358, 608, 125, 220, 73, 185, 255, 133), COIN_2 (1350, 513, 100, 225, 55, 160, 255, 115), COIN_3 (1360, 532, 97, 225, 53, 157, 255, 113), COIN_4 (1202, 438, 95, 225, 52, 155, 255, 112), COIN_5 (1350, 593, 96, 225, 52, 156, 255, 112), DECK_SLOT_1A ( 255, 281, 25, 115, 212, 63, 255, 255), DECK_SLOT_1B ( 286, 281, 25, 115, 212, 63, 255, 255), DECK_SLOT_2A ( 544, 281, 25, 115, 212, 66, 255, 255), DECK_SLOT_2B ( 575, 281, 25, 115, 212, 66, 255, 255), DECK_SLOT_3A ( 791, 281, 25, 115, 212, 66, 255, 255), DECK_SLOT_3B ( 822, 281, 25, 115, 212, 66, 255, 255), DECK_SLOT_4A ( 255, 527, 25, 115, 212, 63, 255, 255), DECK_SLOT_4B ( 286, 527, 25, 115, 212, 63, 255, 255), DECK_SLOT_5A ( 544, 527, 25, 115, 212, 66, 255, 255), DECK_SLOT_5B ( 575, 527, 25, 115, 212, 66, 255, 255), DECK_SLOT_6A ( 791, 527, 25, 115, 212, 66, 255, 255), DECK_SLOT_6B ( 822, 527, 25, 115, 212, 66, 255, 255), DECK_SLOT_7A ( 255, 775, 25, 115, 212, 63, 255, 255), DECK_SLOT_7B ( 286, 775, 25, 115, 212, 63, 255, 255), DECK_SLOT_8A ( 544, 775, 25, 115, 212, 66, 255, 255), DECK_SLOT_8B ( 575, 775, 25, 115, 212, 66, 255, 255), DECK_SLOT_9A ( 791, 775, 25, 115, 212, 66, 255, 255), DECK_SLOT_9B ( 822, 775, 25, 115, 212, 66, 255, 255), MODE_CASUAL_1A (1088, 150, 60, 200, 230, 220, 255, 255), MODE_CASUAL_1B (1088, 250, 60, 200, 230, 220, 255, 255), MODE_CASUAL_2A (1093, 120, 60, 200, 230, 220, 255, 255), MODE_CASUAL_2B (1093, 200, 60, 200, 230, 220, 255, 255), MODE_CASUAL_3A (1099, 290, 60, 200, 230, 220, 255, 255), MODE_CASUAL_3B (1266, 290, 60, 200, 230, 220, 255, 255), MODE_RANKED_1A (1298, 150, 60, 200, 230, 220, 255, 255), MODE_RANKED_1B (1298, 250, 60, 200, 230, 220, 255, 255), MODE_RANKED_2A (1303, 120, 60, 200, 230, 220, 255, 255), MODE_RANKED_2B (1303, 200, 60, 200, 230, 220, 255, 255), MODE_RANKED_3A (1309, 290, 60, 200, 230, 220, 255, 255), MODE_RANKED_3B (1476, 290, 60, 200, 230, 220, 255, 255), NAME_OPPONENT_1A ( 599, 182, 157, 117, 49, 217, 177, 109), NAME_OPPONENT_1B ( 986, 168, 143, 100, 40, 203, 160, 100), NAME_OPPONENT_1C ( 790, 930, 99, 169, 225, 159, 229, 255), NAME_OPPONENT_2A ( 593, 185, 159, 116, 52, 219, 176, 112), NAME_OPPONENT_2B (1002, 186, 167, 124, 56, 227, 184, 116), NAME_OPPONENT_2C ( 805, 972, 91, 161, 225, 151, 221, 255), NEW_ARENA_RUN_A ( 466, 266, 225, 209, 118, 255, 255, 178), NEW_ARENA_RUN_B ( 769, 319, 98, 49, 17, 158, 109, 77), NEW_ARENA_RUN_C ( 597, 460, 225, 225, 225, 255, 255, 255), NEW_ARENA_RUN_D ( 615, 440, 225, 225, 225, 255, 255, 255), NEW_ARENA_RUN_E ( 502, 624, 179, 149, 97, 239, 209, 157), VICTORY_1A ( 522, 788, 58, 71, 162, 118, 131, 222), VICTORY_1B (1068, 797, 44, 58, 143, 104, 118, 203), VICTORY_1C ( 858, 254, 225, 194, 89, 255, 254, 149), VICTORY_2A ( 543, 733, 55, 72, 173, 115, 132, 233), VICTORY_2B (1152, 530, 33, 46, 118, 93, 106, 178), VICTORY_2C (1210, 335, 223, 213, 155, 255, 255, 215), VICTORY_3A ( 579, 825, 36, 51, 135, 96, 111, 195), VICTORY_3B (1079, 865, 33, 46, 132, 93, 106, 192), VICTORY_3C (1190, 357, 219, 204, 133, 255, 255, 193), DEFEAT_1A (1165, 343, 134, 132, 125, 194, 192, 185), DEFEAT_1B ( 538, 599, 104, 123, 209, 164, 183, 255), DEFEAT_1C (1088, 558, 171, 167, 158, 231, 227, 218), DEFEAT_2A ( 543, 597, 99, 118, 206, 159, 178, 255), DEFEAT_2B ( 430, 540, 107, 108, 104, 167, 168, 164), DEFEAT_2C ( 840, 243, 205, 196, 37, 255, 255, 97), DEFEAT_3A ( 543, 597, 99, 118, 206, 159, 178, 255), DEFEAT_3B ( 430, 540, 107, 108, 104, 167, 168, 164), DEFEAT_3C ( 840, 243, 205, 196, 37, 255, 255, 97), TURN_OPPONENT_1A (PixelLocation.I, 66, 61, 52, 129, 135, 136), TURN_OPPONENT_1B (PixelLocation.J, 106, 93, 73, 176, 175, 168), TURN_OPPONENT_2A (1444, 535, 104, 107, 111, 164, 167, 171), TURN_OPPONENT_2B (1468, 563, 104, 107, 110, 164, 167, 170), TURN_OPPONENT_3A (1457, 525, 76, 60, 50, 136, 120, 110), TURN_OPPONENT_3B (1449, 561, 163, 88, 66, 223, 148, 126), TURN_YOUR_1A (PixelLocation.I, 15, 180, 0, 76, 255, 37), TURN_YOUR_1B (PixelLocation.J, 45, 170, 10, 100, 255, 70), TURN_YOUR_2A (PixelLocation.I, 210, 180, 0, 255, 255, 10), TURN_YOUR_2B (PixelLocation.J, 195, 160, 10, 255, 255, 80), BACKGROUND_PLAY_1 ( 260, 434, 0, 0, 0, 30, 30, 30), BACKGROUND_PLAY_2 ( 526, 434, 0, 0, 0, 30, 30, 30), BACKGROUND_PLAY_3 ( 790, 434, 0, 0, 0, 30, 30, 30), BACKGROUND_PLAY_4 ( 260, 680, 0, 0, 0, 40, 40, 40), BACKGROUND_PLAY_5 ( 526, 680, 0, 0, 0, 30, 30, 30), BACKGROUND_PLAY_6 ( 790, 680, 0, 0, 0, 30, 30, 30), BACKGROUND_PLAY_7 ( 260, 927, 0, 0, 0, 30, 30, 30), BACKGROUND_PLAY_8 ( 526, 927, 0, 0, 0, 30, 30, 30), BACKGROUND_PLAY_9 ( 790, 927, 0, 0, 0, 30, 30, 30), // The top-left (tl) and bottom-right (br) points to look for the reference pixel for victory or defeat VICTORY_DEFEAT_REFBOX_TL ( 418, 218, 110, 80, 35, 200, 140, 60 ), VICTORY_DEFEAT_REFBOX_BR ( 488, 328, 170, 130, 50, 230, 190, 100 ), // At least one of 1A or 1B must match for a victory. Coordinates are relative to the reference pixel above VICTORY_REL_1A ( 740, 5, 110, 80, 35, 230, 190, 90 ), // Gold VICTORY_REL_1B ( 745, -5, 110, 80, 35, 230, 190, 90 ), // Gold // All of 2A, 2B & 2C must match for a victory. Coordinates are relative to the reference pixel above VICTORY_REL_2A ( 765, 50, 120, 90, 30, 235, 195, 90 ), // Gold VICTORY_REL_2B ( 680, 305, 40, 50, 90, 70, 80, 180), // Dark blue VICTORY_REL_2C ( 43, 255, 40, 50, 90, 90, 110, 210), // Dark blue // At least one of 1A-1E must match for a defeat. Coordinates are relative to the reference pixel above DEFEAT_REL_1A ( 760, 120, 60, 40, 20, 115, 95, 55 ), // Dark gold DEFEAT_REL_1B ( 766, 129, 60, 40, 20, 115, 95, 55 ), // Dark gold DEFEAT_REL_1C ( 773, 138, 60, 40, 20, 115, 95, 55 ), // Dark gold DEFEAT_REL_1D ( 779, 147, 60, 40, 20, 115, 95, 55 ), // Dark gold DEFEAT_REL_1E ( 786, 156, 60, 40, 20, 115, 95, 55 ), // Dark gold // 2A must match for a defeat. Coordinates are relative to the reference pixel above DEFEAT_REL_2A ( 120, 315, 60, 70, 140, 140, 160, 250 ), // blue ; public final int x; public final int y; public final int minRed; public final int minGreen; public final int minBlue; public final int maxRed; public final int maxGreen; public final int maxBlue; public int x() { return x; } public int y() { return y; } UniquePixel(int x, int y, int minRed, int minGreen, int minBlue, int maxRed, int maxGreen, int maxBlue) { this.x = x; this.y = y; this.minRed = minRed; this.minGreen = minGreen; this.minBlue = minBlue; this.maxRed = maxRed; this.maxGreen = maxGreen; this.maxBlue = maxBlue; } UniquePixel(PixelLocation pixelLocation, int minRed, int minGreen, int minBlue, int maxRed, int maxGreen, int maxBlue) { this.x = pixelLocation.x; this.y = pixelLocation.y; this.minRed = minRed; this.minGreen = minGreen; this.minBlue = minBlue; this.maxRed = maxRed; this.maxGreen = maxGreen; this.maxBlue = maxBlue; } }
package tigase.collections; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; public class TwoHashBidiMap<K, V> implements BidiMap<K, V> { private final Map<K, V> keyValueMap = new ConcurrentHashMap<K, V>(); private final Map<V, K> valueKeyMap = new ConcurrentHashMap<V, K>(); @Override public void clear() { keyValueMap.clear(); valueKeyMap.clear(); } @Override public boolean containsKey(Object key) { return keyValueMap.containsKey(key); } @Override public boolean containsValue(Object value) { return valueKeyMap.containsKey(value); } @Override public Set<java.util.Map.Entry<K, V>> entrySet() { return Collections.unmodifiableSet(keyValueMap.entrySet()); } @Override public V get(Object key) { if (key == null) return null; return keyValueMap.get(key); } @Override public K getKey(Object value) { return this.valueKeyMap.get(value); } @Override public boolean isEmpty() { return keyValueMap.isEmpty(); } @Override public Set<K> keySet() { return Collections.unmodifiableSet(keyValueMap.keySet()); } @Override public V put(K key, V value) { remove(key); removeValue(value); this.valueKeyMap.put(value, key); return this.keyValueMap.put(key, value); } @Override public void putAll(Map<? extends K, ? extends V> m) { for (java.util.Map.Entry<? extends K, ? extends V> en : m.entrySet()) { put(en.getKey(), en.getValue()); } } @Override public V remove(Object key) { V v = this.keyValueMap.remove(key); if (v != null) this.valueKeyMap.remove(v); return v; } @Override public K removeValue(Object value) { K k = this.valueKeyMap.remove(value); if (k != null) this.keyValueMap.remove(k); return k; } @Override public int size() { int kvs = keyValueMap.size(); int vks = valueKeyMap.size(); if (vks != kvs) { throw new Error("Errors in " + this.getClass().getName() + ". Desyncronized!"); } return kvs; } @Override public Collection<V> values() { return Collections.unmodifiableCollection(keyValueMap.values()); } }
package tigase.xmpp; import java.util.Arrays; import java.util.EmptyStackException; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import java.util.Stack; import java.util.TreeMap; import java.util.logging.Logger; import tigase.xml.DefaultElementFactory; import tigase.xml.Element; import tigase.xml.ElementFactory; import tigase.xml.SimpleHandler; public class XMPPDomBuilderHandler implements SimpleHandler { private static Logger log = Logger.getLogger("tigase.xmpp.XMPPDomBuilderHandler"); private static final String ELEM_STREAM_STREAM = "stream:stream"; private static ElementFactory defaultFactory = new DefaultElementFactory(); private ElementFactory customFactory = null; private Object parserState = null; private String top_xmlns = null; private String def_xmlns = null; private XMPPIOService service = null; private LinkedList<Element> all_roots = new LinkedList<Element>(); private Stack<Element> el_stack = new Stack<Element>(); private Map<String, String> namespaces = new TreeMap<String, String>(); public XMPPDomBuilderHandler(XMPPIOService ioserv, ElementFactory factory) { customFactory = factory; service = ioserv; } public XMPPDomBuilderHandler(XMPPIOService ioserv) { customFactory = defaultFactory; service = ioserv; } public Queue<Element> getParsedElements() { return all_roots; } public void error(String errorMessage) { log.warning("XML content parse error."); log.warning(errorMessage); } private Element newElement(String name, String cdata, StringBuilder[] attnames, StringBuilder[] attvals) { return customFactory.elementInstance(name, cdata, attnames, attvals); } public void startElement(StringBuilder name, StringBuilder[] attr_names, StringBuilder[] attr_values) { log.finest("Start element name: "+name); log.finest("Element attributes names: "+Arrays.toString(attr_names)); log.finest("Element attributes values: "+Arrays.toString(attr_values)); // Look for 'xmlns:' declarations: if (attr_names != null) { for (int i = 0; i < attr_names.length; ++i) { // Exit the loop as soon as we reach end of attributes set if (attr_names[i] == null) { break; } if (attr_names[i].toString().startsWith("xmlns:")) { namespaces.put(attr_names[i].substring("xmlns:".length(), attr_names[i].length()), attr_values[i].toString()); } // end of if (att_name.startsWith("xmlns:")) } // end of for (String att_name : attnames) } // end of if (attr_names != null) String tmp_name = name.toString(); if (tmp_name.equals(ELEM_STREAM_STREAM)) { Map<String, String> attribs = new HashMap<String, String>(); if (attr_names != null) { for (int i = 0; i < attr_names.length; i++) { if (attr_names[i] != null && attr_values[i] != null) { attribs.put(attr_names[i].toString(), attr_values[i].toString()); } else { break; } // end of else } // end of for (int i = 0; i < attr_names.length; i++) } // end of if (attr_name != null) service.xmppStreamOpened(attribs); return; } // end of if (tmp_name.equals(ELEM_STREAM_STREAM)) String new_xmlns = null; String prefix = null; for (String pref: namespaces.keySet()) { if (tmp_name.startsWith(pref)) { new_xmlns = namespaces.get(pref); tmp_name = tmp_name.substring(pref.length()+1, tmp_name.length()); prefix = pref; } // end of if (tmp_name.startsWith(xmlns)) } // end of for (String xmlns: namespaces.keys()) Element elem = newElement(tmp_name, null, attr_names, attr_values); String ns = elem.getXMLNS(); if (ns == null) { elem.setDefXMLNS(def_xmlns); } else { def_xmlns = ns; } // end of if (ns == null) else if (new_xmlns != null) { elem.setXMLNS(new_xmlns); elem.removeAttribute("xmlns:" + prefix); } el_stack.push(elem); } public void elementCData(StringBuilder cdata) { log.finest("Element CDATA: "+cdata); try { el_stack.peek().setCData(cdata.toString()); } catch (EmptyStackException e) { // Do nothing here, it happens sometimes that client sends // some white characters after sending open stream data.... } } public void endElement(StringBuilder name) { log.finest("End element name: "+name); String tmp_name = name.toString(); if (tmp_name.equals(ELEM_STREAM_STREAM)) { service.xmppStreamClosed(); return; } // end of if (tmp_name.equals(ELEM_STREAM_STREAM)) if (el_stack.isEmpty()) { el_stack.push(newElement(tmp_name, null, null, null)); } // end of if (tmp_name.equals()) Element elem = el_stack.pop(); if (el_stack.isEmpty()) { all_roots.offer(elem); def_xmlns = top_xmlns; log.finest("Adding new request: "+elem.toString()); } // end of if (el_stack.isEmpty()) else { el_stack.peek().addChild(elem); } // end of if (el_stack.isEmpty()) else } public void otherXML(StringBuilder other) { log.finest("Other XML content: "+other); // Just ignore } public void saveParserState(Object state) { parserState = state; } public Object restoreParserState() { return parserState; } }// XMPPDomBuilderHandler
package org.jboss.jca.validator.cli; import org.jboss.jca.validator.Validation; import java.io.File; import java.net.MalformedURLException; /** * A Main. * * @author Jeff Zhang</a> * @version $Revision: $ */ public class Main { private static final int SUCCESS = 0; private static final int FAIL = 1; private static final int OTHER = 2; /** * Validator standalone tool * * @param args command line arguments */ public static void main(String[] args) { boolean quiet = false; String outputDir = "."; //put report into current directory by default int arg = 0; String[] classpath = null; if (args.length > 0) { while (args.length > arg + 1) { if (args[arg].startsWith("-")) { if (args[arg].endsWith("quiet")) { quiet = true; } else if (args[arg].endsWith("output")) { arg++; if (arg + 1 >= args.length) { usage(); System.exit(OTHER); } outputDir = args[arg]; } else if (args[arg].endsWith("classpath")) { arg++; classpath = args[arg].split(System.getProperty("path.separator")); } } else { usage(); System.exit(OTHER); } arg++; } try { int systemExitCode = Validation.validate(new File(args[arg]).toURI().toURL(), outputDir, classpath); if (!quiet) { if (systemExitCode == SUCCESS) { System.out.println("Validation sucessful"); } else if (systemExitCode == FAIL) { System.out.println("Validation errors"); } else if (systemExitCode == OTHER) { System.out.println("Validation unknown"); } } System.exit(systemExitCode); } catch (ArrayIndexOutOfBoundsException oe) { usage(); System.exit(OTHER); } catch (MalformedURLException e) { e.printStackTrace(); } } else { usage(); } System.exit(SUCCESS); } /** * Tool usage */ private static void usage() { System.out.println("Usage: validator [-quiet] [-output directory] [-classpath thirdparty.jar] <file>"); } }
package yanagishima.servlet; import com.facebook.presto.client.ClientException; import com.facebook.presto.client.ErrorLocation; import com.facebook.presto.client.QueryError; import com.fasterxml.jackson.databind.ObjectMapper; import me.geso.tinyorm.TinyORM; import org.apache.http.client.fluent.Request; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import yanagishima.config.YanagishimaConfig; import yanagishima.exception.QueryErrorException; import yanagishima.result.PrestoQueryResult; import yanagishima.row.Query; import yanagishima.service.PrestoService; import yanagishima.util.AccessControlUtil; import yanagishima.util.HttpRequestUtil; import yanagishima.util.JsonUtil; import yanagishima.util.MetadataUtil; import javax.inject.Inject; import javax.inject.Singleton; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoUnit; import java.util.*; import java.util.stream.Collectors; import static java.nio.charset.StandardCharsets.UTF_8; import static javax.servlet.http.HttpServletResponse.SC_FORBIDDEN; import static yanagishima.util.Constants.YANAGISHIMA_COMMENT; @Singleton public class PrestoServlet extends HttpServlet { private static Logger LOGGER = LoggerFactory.getLogger(PrestoServlet.class); private static final long serialVersionUID = 1L; private final PrestoService prestoService; private final YanagishimaConfig yanagishimaConfig; @Inject private TinyORM db; @Inject public PrestoServlet(PrestoService prestoService, YanagishimaConfig yanagishimaConfig) { this.prestoService = prestoService; this.yanagishimaConfig = yanagishimaConfig; } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HashMap<String, Object> retVal = new HashMap<String, Object>(); try { Optional<String> queryOptional = Optional.ofNullable(request.getParameter("query")); queryOptional.ifPresent(query -> { String userName = null; Optional<String> prestoUser = Optional.ofNullable(request.getParameter("user")); Optional<String> prestoPassword = Optional.ofNullable(request.getParameter("password")); if(yanagishimaConfig.isUseAuditHttpHeaderName()) { userName = request.getHeader(yanagishimaConfig.getAuditHttpHeaderName()); } else { if (prestoUser.isPresent() && prestoPassword.isPresent()) { userName = prestoUser.get(); } } if(yanagishimaConfig.isUserRequired() && userName == null) { try { response.sendError(SC_FORBIDDEN); return; } catch (IOException e) { throw new RuntimeException(e); } } try { String datasource = HttpRequestUtil.getParam(request, "datasource"); String prestoCoordinatorServer = yanagishimaConfig.getPrestoCoordinatorServerOrNull(datasource); if(prestoCoordinatorServer == null) { JsonUtil.writeJSON(response, retVal); return; } if(yanagishimaConfig.isCheckDatasource()) { if(!AccessControlUtil.validateDatasource(request, datasource)) { try { response.sendError(SC_FORBIDDEN); return; } catch (IOException e) { throw new RuntimeException(e); } } } if(userName != null) { LOGGER.info(String.format("%s executed %s in %s", userName, query, datasource)); } boolean storeFlag = Boolean.parseBoolean(Optional.ofNullable(request.getParameter("store")).orElse("false")); if (prestoUser.isPresent() && prestoPassword.isPresent()) { if(prestoUser.get().length() == 0) { retVal.put("error", "user is empty"); JsonUtil.writeJSON(response, retVal); return; } } PrestoQueryResult prestoQueryResult; if(query.startsWith(YANAGISHIMA_COMMENT + "SELECT table_name, table_type FROM hive.information_schema.tables")) { prestoQueryResult = prestoService.doQuery(datasource, query, userName, prestoUser, prestoPassword, storeFlag, Integer.MAX_VALUE); } else { prestoQueryResult = prestoService.doQuery(datasource, query, userName, prestoUser, prestoPassword, storeFlag, yanagishimaConfig.getSelectLimit()); } String queryid = prestoQueryResult.getQueryId(); retVal.put("queryid", queryid); if (prestoQueryResult.getUpdateType() == null) { retVal.put("headers", prestoQueryResult.getColumns()); if(query.startsWith(YANAGISHIMA_COMMENT + "SHOW schemas from")) { String catalog = query.substring((YANAGISHIMA_COMMENT + "SHOW schemas from").length()).trim(); List<String> invisibleSchemas = yanagishimaConfig.getInvisibleSchemas(datasource, catalog); retVal.put("results", prestoQueryResult.getRecords().stream().filter(list -> !invisibleSchemas.contains(list.get(0))).collect(Collectors.toList())); } else { retVal.put("results", prestoQueryResult.getRecords()); } retVal.put("lineNumber", Integer.toString(prestoQueryResult.getLineNumber())); retVal.put("rawDataSize", prestoQueryResult.getRawDataSize().toString()); Optional<String> warningMessageOptinal = Optional.ofNullable(prestoQueryResult.getWarningMessage()); warningMessageOptinal.ifPresent(warningMessage -> { retVal.put("warn", warningMessage); }); if(query.startsWith(YANAGISHIMA_COMMENT + "DESCRIBE")) { if(yanagishimaConfig.getMetadataServiceUrl(datasource).isPresent()) { String[] strings = query.substring(YANAGISHIMA_COMMENT.length() + "DESCRIBE ".length()).split("\\."); String schema = strings[1]; String table = strings[2].substring(1, strings[2].length() - 1); MetadataUtil.setMetadata(yanagishimaConfig.getMetadataServiceUrl(datasource).get(), retVal, schema, table, prestoQueryResult.getRecords()); } } } } catch (QueryErrorException e) { LOGGER.error(e.getMessage(), e); Optional<QueryError> queryErrorOptional = Optional.ofNullable(e.getQueryError()); queryErrorOptional.ifPresent(queryError -> { Optional<ErrorLocation> errorLocationOptional = Optional.ofNullable(queryError.getErrorLocation()); errorLocationOptional.ifPresent(errorLocation -> { int errorLineNumber = errorLocation.getLineNumber(); retVal.put("errorLineNumber", errorLineNumber); }); }); retVal.put("error", e.getCause().getMessage()); retVal.put("queryid", e.getQueryId()); } catch (ClientException e) { if(prestoUser.isPresent()) { LOGGER.error(String.format("%s failed to be authenticated. message=%s", prestoUser.get(), e.getMessage())); } else { LOGGER.error(e.getMessage()); } retVal.put("error", e.getMessage()); } catch (Throwable e) { LOGGER.error(e.getMessage(), e); retVal.put("error", e.getMessage()); } }); } catch (Throwable e) { LOGGER.error(e.getMessage(), e); retVal.put("error", e.getMessage()); } JsonUtil.writeJSON(response, retVal); } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // 3. All advertising materials mentioning features or use of this software // must display the following acknowledgement: // This product includes software developed by CDS Networks, Inc. // 4. The name of CDS Networks, Inc. may not be used to endorse or promote // products derived from this software without specific prior // THIS SOFTWARE IS PROVIDED BY CDS NETWORKS, INC. ``AS IS'' AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL CDS NETWORKS, INC. BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. /** * A Statement object is used for executing a static SQL statement and * obtaining the results produced by it. * * <p>Only one ResultSet per Statement can be open at any point in time. * Therefore, if the reading of one ResultSet is interleaved with the * reading of another, each must have been generated by different * Statements. All statement execute methods implicitly close a * statement's current ResultSet if an open one exists. * * @see java.sql.Statement * @see ResultSet * @version $Id: TdsStatement.java,v 1.10 2004-01-29 23:30:32 bheineman Exp $ */ package net.sourceforge.jtds.jdbc; import java.sql.*; public class TdsStatement implements java.sql.Statement { public static final String cvsVersion = "$Id: TdsStatement.java,v 1.10 2004-01-29 23:30:32 bheineman Exp $"; private TdsConnection connection; // The connection that created us SQLWarningChain warningChain = new SQLWarningChain(); // The warning chain TdsResultSet results = null; private Tds actTds = null; private boolean escapeProcessing = true; private int updateCount = -1; private int maxFieldSize = (1<<31)-1; private int maxRows = 0; private int timeout = 0; // The timeout for a query private int fetchSize = AbstractResultSet.DEFAULT_FETCH_SIZE; private int fetchDir = ResultSet.FETCH_FORWARD; private int type = ResultSet.TYPE_FORWARD_ONLY; private int concurrency = ResultSet.CONCUR_READ_ONLY; private boolean isClosed = false; public TdsStatement(TdsConnection con, int type, int concurrency) throws SQLException { this.connection = con; this.type = type; this.concurrency = concurrency; } /** * Constructor for a Statement. It simply sets the connection * that created us. * * @param con the Connection instance that creates us */ public TdsStatement(TdsConnection con) throws SQLException { this(con, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } /** * Releases <code>actTds</code> IF there are no outstanding results. */ protected synchronized void releaseTds() throws SQLException { // MJH remove test of autoCommit if( actTds == null ) return; // Don't free the Tds if there are any results left. /** @todo Check if this is correct in case an IOException occurs */ if( actTds.moreResults() ) return; try { connection.freeTds(actTds); actTds = null; } catch (TdsException e) { throw new SQLException("Confusion in freeing Tds: " + e); } } protected void NotImplemented() throws java.sql.SQLException { throw new SQLException("Not Implemented"); } /** * Execute an SQL statement that returns a single <code>ResultSet</code>. * * @param sql typically a static SQL SELECT statement * @return a <code>ResultSet</code> that contains the data produced by * the query; never <code>null</code> * @exception SQLException if a database access error occurs */ public ResultSet executeQuery(String sql) throws SQLException { checkClosed(); if( type == ResultSet.TYPE_FORWARD_ONLY && concurrency == ResultSet.CONCUR_READ_ONLY ) { if( internalExecute(sql) ) return results; else throw new SQLException("No ResultSet was produced."); } else return new CursorResultSet(this, sql, fetchDir); } /** * This is the internal function that all subclasses should call. * It is not executeQuery() to allow subclasses (in particular * CursorResultSet) to override that functionality without * breaking the internal methods. * * @param sql any SQL statement * @return true if the next result is a ResulSet, false if it is * an update count or there are no more results * @exception SQLException if a database access error occurs */ public final synchronized boolean internalExecute(String sql) throws SQLException { checkClosed(); return executeImpl(getTds(false), sql, warningChain); } public final synchronized boolean internalExecute(String sql, Tds tds, SQLWarningChain wChain) throws SQLException { checkClosed(); return executeImpl(tds, sql, wChain); } private final boolean executeImpl(Tds tds, String sql, SQLWarningChain wChain) throws SQLException { // Clear warnings, otherwise the last exception will be thrown. wChain.clearWarnings(); updateCount = -1; // Consume all outstanding results. Otherwise it will either deadlock, // crash or return results from the previous query. skipToEnd(); try { if (escapeProcessing) { sql = EscapeProcessor.nativeSQL(sql);; } tds.executeQuery(sql, this, wChain, timeout); } catch(java.io.IOException e) { throw new SQLException("Network error: " + e.getMessage()); } catch(net.sourceforge.jtds.jdbc.TdsException e) { throw new SQLException("TDS error: " + e.getMessage()); } // SAfe We must do this to ensure we throw SQLExceptions on timed out // statements wChain.checkForExceptions(); return getMoreResults(tds, wChain, true); } public final synchronized boolean internalExecuteCall(String name, ParameterListItem[] formalParameterList, ParameterListItem[] actualParameterList, Tds tds, SQLWarningChain wChain) throws SQLException { checkClosed(); return executeCallImpl(tds, name, formalParameterList, actualParameterList, wChain); } private boolean executeCallImpl(Tds tds, String name, ParameterListItem[] formalParameterList, ParameterListItem[] actualParameterList, SQLWarningChain wChain) throws SQLException { wChain.clearWarnings(); // SAfe This is where all outstanding results must be skipped, to make // sure they don't interfere with the the current ones. skipToEnd(); try { // execute the stored procedure. tds.executeProcedure(name, formalParameterList, actualParameterList, this, wChain, getQueryTimeout()); return getMoreResults(tds, warningChain, true); } catch (TdsException e) { throw new SQLException(e.toString()); } catch (java.io.IOException e) { throw new SQLException(e.toString()); } } /** * Execute a SQL INSERT, UPDATE or DELETE statement. In addition * SQL statements that return nothing such as SQL DDL statements * can be executed * * Any IDs generated for AUTO_INCREMENT fields can be retrieved * by looking through the SQLWarning chain of this statement * for warnings of the form "LAST_INSERTED_ID = 'some number', * COMMAND = 'your sql'". * * @param sql an SQL statement * @return either a row count, or 0 for SQL commands * @exception SQLException if a database access error occurs */ public synchronized int executeUpdate(String sql) throws SQLException { checkClosed(); if( internalExecute(sql) ) { skipToEnd(); throw new SQLException("executeUpdate can't return a result set"); } else { int res = getUpdateCount(); // We should return 0 (at least that's what the javadoc above says) return res==-1 ? 0 : res; } } protected synchronized void closeResults(boolean allowTdsRelease) throws java.sql.SQLException { if( results != null ) { results.close(allowTdsRelease); results = null; } } /** * Eats all available input from the server. Not very efficient (since it * reads in all data by creating <code>ResultSets</code> and processing * them), but at least it works (the old version would crash when reading in * a row because it didn't have any information about the row's Context). * <p> * This could be changed to use the <code>TdsComm</code> to read in all the * server response without processing it, but that requires some changes in * <code>TdsComm</code>, too. */ protected synchronized void skipToEnd() throws java.sql.SQLException { closeResults(false); if( actTds != null ) { actTds.skipToEnd(); // releaseTds(); // SAfe This is the only place we should send a CANCEL packet // ourselves. We can't do that in Tds.discardResultSet because // we could cancel other results when what we want is to only // close the ResultSet in order to get the other results. // SAfe On a second thought, we'd better not cancel the execution. // Someone could run a big update script and not process all // the results, thinking that as long as there were no // exceptions, all went right, but we would cancel the script. // Anyway, this was a good test for the cancel mechanism. :o) // try // if( actTds.moreResults() ) // actTds.cancel(); // catch( java.io.IOException ex ) // throw new SQLException(ex.toString()); // catch( TdsException ex ) // throw new SQLException(ex.toString()); // SAfe And now, keep consuming data and hope the server cancels // this as soon as possible (I'm not so sure, however, that // this will happen; I think that even if the data amount is // huge, the server sends it as soon as possible so the cancel // could come too late; or not?) // while( getMoreResults(actTds, warningChain, false) || updateCount!=-1 ); } } /** * In many cases, it is desirable to immediately release a * Statement's database and JDBC resources instead of waiting * for this to happen when it is automatically closed. The * close method provides this immediate release. * * <p><B>Note:</B> A Statement is automatically closed when it is * garbage collected. When a Statement is closed, its current * ResultSet, if one exists, is also closed. * * @exception SQLException if a database access error occurs (why?) */ public synchronized void close() throws SQLException { if( isClosed ) return; // SAfe Mark Statement as closed internally, too isClosed = true; if( actTds != null ) // Tds not yet released. try { // SAfe: Must do this to ensure no garbage is left behind closeResults(false); if( !connection.isClosed() ) actTds.skipToEnd(); // MJH Do not Rollback any pending transactions! connection.freeTds(actTds); actTds = null; } catch( net.sourceforge.jtds.jdbc.TdsException e ) { throw new SQLException(e.toString()); } } /** * Make sure we release the <code>Tds</code> when we're no longer in use. * This is safe to do even in the case of <code>DatabaseMetaData</code> or * other cases where the reference to the <code>Statement</code> is lost * and only a reference to a <code>ResultSet</code> is kept, because the * <code>TdsResultSet</code> has an internal reference to the * <code>Statement</code> so <code>finalize()</code> won't get called yet. * @throws SQLException */ public void finalize() throws SQLException { close(); } /** * The maxFieldSize limit (in bytes) is the maximum amount of * data returned for any column value; it only applies to * BINARY, VARBINARY, LONGVARBINARY, CHAR, VARCHAR and LONGVARCHAR * columns. If the limit is exceeded, the excess data is silently * discarded. * * @return the current max column size limit; zero means unlimited * @exception SQLException if a database access error occurs */ public synchronized int getMaxFieldSize() throws SQLException { checkClosed(); return maxFieldSize; } /** * Sets the maxFieldSize * * @param max the new max column size limit; zero means unlimited * @exception SQLException if size exceeds buffer size */ public synchronized void setMaxFieldSize(int max) throws SQLException { checkClosed(); maxFieldSize = max; } /** * The maxRows limit is set to limit the number of rows that * any ResultSet can contain. If the limit is exceeded, the * excess rows are silently dropped. * * @return the current maximum row limit; zero means unlimited * @exception SQLException if a database access error occurs */ public synchronized int getMaxRows() throws SQLException { checkClosed(); return maxRows; } /** * Set the maximum number of rows * * @param max the new max rows limit; zero means unlimited * @exception SQLException if a database access error occurs * @see #getMaxRows */ public synchronized void setMaxRows(int max) throws SQLException { checkClosed(); if( maxRows < 0 ) throw new SQLException("Negative row count"); maxRows = max; } /** * If escape scanning is on (the default), the driver will do escape * substitution before sending the SQL to the database. * * @param enable true to enable; false to disable * @exception SQLException if a database access error occurs */ public synchronized void setEscapeProcessing(boolean enable) throws SQLException { checkClosed(); escapeProcessing = enable; } /** * The queryTimeout limit is the number of seconds the driver * will wait for a Statement to execute. If the limit is * exceeded, a SQLException is thrown. * * @return the current query timeout limit in seconds; 0 = unlimited * @exception SQLException if a database access error occurs */ public synchronized int getQueryTimeout() throws SQLException { checkClosed(); return timeout; } /** * Sets the queryTimeout limit * * @param seconds - the new query timeout limit in seconds * @exception SQLException if a database access error occurs */ public synchronized void setQueryTimeout(int seconds) throws SQLException { checkClosed(); timeout = seconds; } /** * * @exception SQLException */ public void cancel() throws SQLException { checkClosed(); try { if( actTds != null ) actTds.cancel(); } catch(net.sourceforge.jtds.jdbc.TdsException e) { throw new SQLException(e.getMessage()); } catch(java.io.IOException e) { throw new SQLException(e.getMessage()); } } /** * The first warning reported by calls on this Statement is * returned. A Statement's execute methods clear its SQLWarning * chain. Subsequent Statement warnings will be chained to this * SQLWarning. * * <p>The Warning chain is automatically cleared each time a statement * is (re)executed. * * <p><B>Note:</B> If you are processing a ResultSet then any warnings * associated with ResultSet reads will be chained on the ResultSet * object. * * @return the first SQLWarning on null * @exception SQLException if a database access error occurs */ public synchronized SQLWarning getWarnings() throws SQLException { checkClosed(); return warningChain.getWarnings(); } /** * After this call, getWarnings returns null until a new warning * is reported for this Statement. * * @exception SQLException if a database access error occurs (why?) */ public synchronized void clearWarnings() throws SQLException { checkClosed(); warningChain.clearWarnings(); } /** * setCursorName defines the SQL cursor name that will be used by * subsequent execute methods. This name can then be used in SQL * positioned update/delete statements to identify the current row * in the ResultSet generated by this statement. If a database * doesn't support positioned update/delete, this method is a * no-op. * * @param name the new cursor name * @exception SQLException if a database access error occurs */ public void setCursorName(String name) throws SQLException { // SAfe As the javadoc above says, this should be a no-op. } public synchronized boolean execute(String sql) throws SQLException { checkClosed(); return internalExecute(sql); } synchronized Tds getTds(boolean mainTds) throws SQLException { // SAfe If the main Tds is requested, then simply return it if( mainTds ) return connection.allocateTds(mainTds); // SAfe Else, find one and assign it to this Statement if( actTds == null ) { actTds=connection.allocateTds(mainTds); actTds.setStatement(this); return actTds; } else return actTds; } /** * getResultSet returns the current result as a ResultSet. It * should only be called once per result. * * @return the current result set; null if there are no more * @exception SQLException if a database access error occurs */ public synchronized java.sql.ResultSet getResultSet() throws SQLException { checkClosed(); return results; } /** * getUpdateCount returns the current result as an update count, * if the result is a ResultSet or there are no more results, -1 * is returned. It should only be called once per result. * * @return the current result as an update count. * @exception SQLException if a database access error occurs */ public synchronized int getUpdateCount() throws SQLException { checkClosed(); return updateCount; } /** * getMoreResults moves to a Statement's next result. If it returns * true, this result is a ResulSet. * * @return true if the next ResultSet is valid * @exception SQLException if a database access error occurs */ public synchronized boolean getMoreResults() throws SQLException { checkClosed(); return getMoreResults(actTds, warningChain, true); } public boolean getMoreResults(int current) throws SQLException { NotImplemented(); return false; } void handleRetStat(PacketRetStatResult packet) { } void handleParamResult(PacketOutputParamResult packet) throws SQLException { } synchronized boolean getMoreResults(Tds tds, SQLWarningChain wChain, boolean allowTdsRelease) throws SQLException { updateCount = -1; if( tds == null ) return false; // Reset all internal variables (do it before checking for more results) closeResults(false); // SAfe Synchronize on the Tds to make sure noone else can call // Tds.skipToEnd while we're processing the results synchronized( tds ) { if( !tds.moreResults() ) { if( allowTdsRelease ) releaseTds(); return false; } try { // @todo SAfe Rewrite all the code below to no longer peek at the // packet type, as it always processes it afterwards, anyway // Keep eating garbage and warnings until we reach the next result while( true ) { if( tds.isResultSet() ) { results = new TdsResultSet(tds, this, wChain, fetchSize); break; } // SAfe: Only TDS_DONE should return row counts for Statements // TDS_DONEINPROC should return row counts for PreparedStatements else if( tds.peek()==Tds.TDS_DONE || (this instanceof PreparedStatement && !(this instanceof CallableStatement) && tds.peek()==Tds.TDS_DONEINPROC) ) { PacketEndTokenResult end = (PacketEndTokenResult)tds.processSubPacket(); updateCount = end.getRowCount(); // SAfe Eat up all packets until the next result or the end tds.goToNextResult(wChain, this); if( allowTdsRelease ) releaseTds(); break; } // SAfe: TDS_DONEPROC and TDS_DONEINPROC should *NOT* return // rowcounts otherwise else if( tds.isEndOfResults() ) { tds.processSubPacket(); // SAfe Eat up all packets until the next result or the end tds.goToNextResult(wChain, this); if( !tds.moreResults() ) { if( allowTdsRelease ) releaseTds(); break; // No more results but no update count either } } else if( tds.isMessagePacket() || tds.isErrorPacket() ) wChain.addOrReturn((PacketMsgResult)tds.processSubPacket()); else if (tds.isRetStat()) handleRetStat((PacketRetStatResult)tds.processSubPacket()); else if( tds.isParamResult() ) handleParamResult((PacketOutputParamResult)tds.processSubPacket()); else if( tds.isEnvChange() ) // Process the environment change. tds.processSubPacket(); else if( tds.isProcId() ) tds.processSubPacket(); else throw new SQLException("Protocol confusion. Got a 0x" + Integer.toHexString((tds.peek() & 0xff)) + " packet."); } // end while wChain.checkForExceptions(); return results != null; } catch( Exception ex ) { releaseTds(); if( ex instanceof SQLException ) throw (SQLException)ex; else throw new SQLException("Network error: " + ex.getMessage()); } } } /** * JDBC 2.0 * * Gives the driver a hint as to the direction in which * the rows in a result set * will be processed. The hint applies only to result sets created * using this Statement object. The default value is * ResultSet.FETCH_FORWARD. * <p>Note that this method sets the default fetch direction for * result sets generated by this <code>Statement</code> object. * Each result set has its own methods for getting and setting * its own fetch direction. * @param direction the initial direction for processing rows * @exception SQLException if a database access error occurs * or the given direction * is not one of ResultSet.FETCH_FORWARD, ResultSet.FETCH_REVERSE, or * ResultSet.FETCH_UNKNOWN */ public void setFetchDirection(int direction) throws SQLException { if( direction!=ResultSet.FETCH_FORWARD && direction!=ResultSet.FETCH_REVERSE && direction!=ResultSet.FETCH_UNKNOWN ) throw new SQLException("Invalid fetch direction."); fetchDir = direction; } /** * JDBC 2.0 * * Retrieves the direction for fetching rows from * database tables that is the default for result sets * generated from this <code>Statement</code> object. * If this <code>Statement</code> object has not set * a fetch direction by calling the method <code>setFetchDirection</code>, * the return value is implementation-specific. * * @return the default fetch direction for result sets generated * from this <code>Statement</code> object * @exception SQLException if a database access error occurs */ public int getFetchDirection() throws SQLException { return fetchDir; } /** * JDBC 2.0 * * Gives the JDBC driver a hint as to the number of rows that should * be fetched from the database when more rows are needed. The number * of rows specified affects only result sets created using this * statement. If the value specified is zero, then the hint is ignored. * The default value is zero. * * @param rows the number of rows to fetch * @exception SQLException if a database access error occurs, or the * condition 0 <= rows <= this.getMaxRows() is not satisfied. */ public void setFetchSize(int rows) throws SQLException { if( rows < 0 ) throw new SQLException("Invalid fetch size."); fetchSize = rows; } /** * JDBC 2.0 * * Retrieves the number of result set rows that is the default * fetch size for result sets * generated from this <code>Statement</code> object. * If this <code>Statement</code> object has not set * a fetch size by calling the method <code>setFetchSize</code>, * the return value is implementation-specific. * @return the default fetch size for result sets generated * from this <code>Statement</code> object * @exception SQLException if a database access error occurs */ public int getFetchSize() throws SQLException { return fetchSize; } /** * JDBC 2.0 * * Retrieves the result set concurrency. * <p> * <b>Note:</b> No need for synchronization. Value never changes. */ public int getResultSetConcurrency() throws SQLException { checkClosed(); return concurrency; } /** * JDBC 2.0 * * Determine the result set type. * <p> * <b>Note:</b> No need for synchronization. Value never changes. */ public int getResultSetType() throws SQLException { checkClosed(); return type; } /** * JDBC 2.0 * * Adds a SQL command to the current batch of commmands for the statement. * This method is optional. * * @param sql typically this is a static SQL INSERT or UPDATE statement * @exception SQLException if a database access error occurs, or the * driver does not support batch statements */ public void addBatch( String sql ) throws SQLException { NotImplemented(); } /** * JDBC 2.0 * * Makes the set of commands in the current batch empty. * This method is optional. * * @exception SQLException if a database access error occurs or the * driver does not support batch statements */ public void clearBatch() throws SQLException { NotImplemented(); } /** * JDBC 2.0 * * Submits a batch of commands to the database for execution. * This method is optional. * * @return an array of update counts containing one element for each * command in the batch. The array is ordered according * to the order in which commands were inserted into the batch. * @exception SQLException if a database access error occurs or the * driver does not support batch statements */ public int[] executeBatch() throws SQLException { NotImplemented(); return null; } /** * JDBC 2.0 * * Returns the <code>Connection</code> object * that produced this <code>Statement</code> object. * <p> * <b>Note:</b> No need for synchromization here. <code>connection</code> * doesn't change during execution (not even after <code>close()</code>. * * @return the connection that produced this statement * @exception SQLException if a database access error occurs */ public java.sql.Connection getConnection() throws SQLException { checkClosed(); return connection; } private void checkClosed() throws SQLException { if( isClosed || connection.isClosed() ) throw new SQLException("Statement already closed."); } public boolean execute(String str, int param) throws java.sql.SQLException { NotImplemented(); return false; } public boolean execute(String str, String[] str1) throws java.sql.SQLException { NotImplemented(); return false; } public boolean execute(String str, int[] values) throws java.sql.SQLException { NotImplemented(); return false; } public int executeUpdate(String str, String[] str1) throws java.sql.SQLException { NotImplemented(); return Integer.MIN_VALUE; } public int executeUpdate(String str, int[] values) throws java.sql.SQLException { NotImplemented(); return Integer.MIN_VALUE; } public int executeUpdate(String str, int param) throws java.sql.SQLException { NotImplemented(); return Integer.MIN_VALUE; } public java.sql.ResultSet getGeneratedKeys() throws java.sql.SQLException { NotImplemented(); return null; } public int getResultSetHoldability() throws java.sql.SQLException { NotImplemented(); return Integer.MIN_VALUE; } }
public class SquareWave extends Waveform { public SquareWave() { } protected double _at(double t) { return t > 0.5 ? 1 : -1; } }
package main.subtitle.subtitleObject; import main.srtFixer.config.SrtFixerConfig; import main.subtitle.fix.ChangeLsToIs; import main.subtitle.fix.FixAbbreviations; import main.subtitle.fix.FixAcronym; import main.subtitle.fix.FixAmpersand; import main.subtitle.fix.FixCapitalization; import main.subtitle.fix.FixCommonErrors; import main.subtitle.fix.FixContractions; import main.subtitle.fix.FixDashes; import main.subtitle.fix.FixEllipses; import main.subtitle.fix.FixEnding; import main.subtitle.fix.FixHeight; import main.subtitle.fix.FixLetterS; import main.subtitle.fix.FixMisplacedQuotes; import main.subtitle.fix.FixMultilineDashes; import main.subtitle.fix.FixMultilineQuotes; import main.subtitle.fix.FixNonTraditionalStrings; import main.subtitle.fix.FixNumbers; import main.subtitle.fix.FixSingleDoubleQuotes; import main.subtitle.fix.FixSpacing; import main.subtitle.fix.FixSpelling; import main.subtitle.fix.FixTime; import main.subtitle.fix.FixToUppercase; import main.subtitle.fix.FixWebsites; import main.subtitle.fix.PrepareLine; import main.subtitle.fix.fixMultipleLines.FixOneLine; import main.subtitle.fix.fixMultipleLines.FixThreeLines; import main.subtitle.fix.fixMultipleLines.FixTwoLines; import main.subtitle.fix.fixMultipleLines.FixUnbalancedDashes; import main.subtitle.fix.remove.RemoveCharacterName; import main.subtitle.fix.remove.RemoveEmpty; import main.subtitle.fix.remove.RemoveEndingCharacter; import main.subtitle.map.SplitMap; import main.subtitle.specialCases.DoNotFix; import main.subtitle.specialCases.ManuelFix; import main.subtitle.timeHolder.TimeHolder; import main.subtitle.util.SubtitleUtil; import main.util.regex.RegexEnum; import main.util.regex.RegexUtil; import main.util.string.StringUtil; /** * Container for all necessary components of a subtitle. * * @author budi */ public class SubtitleObject { /** * Unique id. */ private int id; /** * Start {@link TimeHolder}. */ private TimeHolder timeStart; /** * End {@link TimeHolder}. */ private TimeHolder timeEnd; /** * Subtitle text. */ private String text; /** * Original text. */ private String originalText; /** * {@link SplitMap}. */ private SplitMap splitMap; /** * Class constructor. * * @param id current id * @param timeStart starting time * @param timeEnd ending time * @param text text * @throws SubtitleObjectException Thrown if timeStart is greater than * timeEnd. */ public SubtitleObject(int id, TimeHolder timeStart, TimeHolder timeEnd, String text) throws SubtitleObjectException { this.id = id; this.timeStart = timeStart; this.timeEnd = timeEnd; this.text = text; this.originalText = RemoveEndingCharacter.fix(text, '<', '>', null); this.splitMap = new SplitMap(); if (timeStart != null && timeStart.calcTotalTimeMs() > timeEnd.calcTotalTimeMs()) { throw new SubtitleObjectException( String.format("[ID: %s] Start time is greater than end time. (%s > %s)", id, timeStart, timeEnd)); } } /** * Class constructor using only text. * * @param text text * @throws SubtitleObjectException */ public SubtitleObject(String text) throws SubtitleObjectException { this(-1, null, null, text); } /** * Apply fixes to text. */ public void fix() { if (text == null || text.isEmpty()) { return; } text = text.trim(); text = RemoveEmpty.fix(text, this); if (text.isEmpty()) { return; } // TODO: comment this text = RemoveEndingCharacter.fix(text, '<', '>', this); text = RemoveEndingCharacter.fix(text, '{', '}', this); text = RemoveEndingCharacter.fix(text, '[', ']', this); if (ManuelFix.MANUEL_FIX.containsKey(text)) { text = ManuelFix.MANUEL_FIX.get(text); return; } else if (DoNotFix.DO_NOT_FIX.contains(text)) { return; } text = RemoveEndingCharacter.fix(text, '(', ')', this); text = FixNonTraditionalStrings.fix(text, this); // TODO: messy (see "...with the .22?") if (text.startsWith("-") && !text.startsWith("- ")) { text = "- " + text.substring(1); splitMap.clear(); // TODO: clean up } text = FixEllipses.fix(text, this); text = FixSingleDoubleQuotes.fix(text, this); String result = ""; int removedNames = 0; String originalText = text; text = FixUnbalancedDashes.fix(text); boolean fixedUnbalancedDashes = !originalText.equals(text); if (!text.startsWith("-")) { //text = text.replace("\n", " "); // TODO: explain this } String temp; for (String line : RegexUtil.split(RegexEnum.NEWLINE, text)) { // TODO: if contains punctuation line = line.trim(); splitMap.clear(); line = PrepareLine.fix(line, this); split(RegexEnum.SPACE, line); temp = line; line = RemoveCharacterName.fix(line, this); if (!temp.equals(line)) { ++removedNames; } line = FixSpelling.fix(line, this); if (!SrtFixerConfig.isToggleCorrectCapitalization()) { line = FixToUppercase.fix(line, this); // TODO: remove this once all bugs in FixCapitalization is fixed } line = ChangeLsToIs.fix(line, this); line = FixDashes.fix(line, this); line = RemoveEmpty.fix(line, this); if (SrtFixerConfig.isToggleCorrectCapitalization()) { line = FixCapitalization.fix(line, this); } line = FixAmpersand.fix(line, this); line = FixHeight.fix(line, this); line = FixWebsites.fix(line, this); line = FixTime.fix(line, this); line = FixNumbers.fix(line, this); line = FixAbbreviations.fix(line, this); line = FixContractions.fix(line, this); line = FixAcronym.fix(line, this); line = FixLetterS.fix(line, this); line = FixMisplacedQuotes.fix(line, this); line = FixSpacing.fix(line, this); line = FixCommonErrors.fix(line, this); line = FixEnding.fix(line, this); if (!line.isEmpty()) { line = FixMultilineDashes.fix(result, line); // TODO: why doesn't this work??? if (!result.isEmpty()) { result = FixMultilineDashes.fix(line, result); } StringBuilder builder = new StringBuilder(); if (removedNames == 2) { builder.append("- "); builder.append(result); builder.append("- "); builder.append(line); result = builder.toString(); continue; } builder.append(result); builder.append(line); builder.append('\n'); result = builder.toString(); } } result = FixEllipses.fix(result, this); result = result.trim(); result = FixMultilineQuotes.fix(result, this); result = FixThreeLines.fix(result); result = FixTwoLines.fix(result); result = FixOneLine.fix(result); if (StringUtil.count(originalText, '\n') <= 1 && SubtitleUtil.isApproximatelyEqual(result, originalText) && !fixedUnbalancedDashes) { result = originalText; } text = result; } /* public void fix() { TokenizedText tt = new TokenizedText(text); RemoveHTMLTags.remove(tt); FixConsecutive.fix(tt); FixPunctuationSpacing.fix(tt); FixAbbreviation.fix(tt); DetectAbbreviation.detect(tt); FixLToI.fix(tt); FixTime.fix(tt); DetectTime.detect(tt); RemoveHearingImpaired.remove(tt); FixApostrophe.fix(tt); FixContraction.fix(tt); DetectContraction.detect(tt); FixWebsite.removeExcessSpace(tt); DetectWebsite.detect(tt); FixAcronym.removeExcessSpace(tt); DetectAcronym.detect(tt); FixAcronym.fixCapitalization(tt); FixCapitalization.fix(tt); FixDash.fix(tt); text = tt.toString(); } */ /** * Split line by regex. * * @param re {@link RegexEnum} * @param line line to split * @return list of strings split by regex */ public String[] split(RegexEnum re, String line) { return splitMap.getSplit(re, line); } /** * Replace all using pattern. * * @param re {@link RegexEnum} * @param split list to split * @param index index of word in split * @param replace string to replace * @return fixed string */ public String patternReplaceAll(RegexEnum re, String[] split, int index, String replace) { return splitMap.getPatternReplaceAll(re, split, index, replace); } /** * Clear {@link #splitMap}. */ public void clearSplitMap() { splitMap.clear(); } /** * Clear {@link SubtitleObject} splitMap only if temp does not equal line. * * @param so {@link SubtitleObject} * @param temp original string to compare against line * @param line new line * @return line */ public static String clearMapIfChanged(SubtitleObject so, String temp, String line) { if (so == null) { return line; } if (!temp.equals(line)) { so.getSplitMap().clear(); } return line; } /** * Clear {@link #text}. */ public void clearText() { text = ""; } /** * Trim {@link #text} */ public void trim() { text = text.trim(); } /** * Add time to {@link #timeStart} and {@link #timeEnd}. * * @param time time to add (in seconds) */ public void addTime(double time) { timeStart.addTime(time); timeEnd.addTime(time); } /** * Generate formatted time text using {@link #timeStart} and * {@link #timeEnd}. * * @return formatted time text. */ public String generateTimeText() { StringBuilder builder = new StringBuilder(); builder.append(timeStart.toString()); builder.append(" builder.append(timeEnd.toString()); return builder.toString(); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(Integer.toString(id)); builder.append('\n'); builder.append(generateTimeText()); builder.append('\n'); builder.append(text); builder.append('\n'); builder.append('\n'); return builder.toString(); } /** * @return {@link #id} */ public int getId() { return id; } /** * {@link #id} * * @param id new id */ public void setId(int id) { this.id = id; } /** * @return {@link #timeStart} */ public TimeHolder getTimeStart() { return timeStart; } /** * @return {@link #timeEnd} */ public TimeHolder getTimeEnd() { return timeEnd; } /** * @return {@link #text} */ public String getText() { return text; } /** * @return {@link #originalText} */ public String getOriginalText() { return originalText; } /** * @return {@link #splitMap} */ public SplitMap getSplitMap() { return splitMap; } }
package markehme.factionsplus.listeners; import java.io.File; import markehme.factionsplus.FactionsPlusPlugin; import markehme.factionsplus.Utilities; import markehme.factionsplus.config.Config; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import com.massivecraft.factions.event.FPlayerJoinEvent; public class BanListener implements Listener{ @EventHandler public void onFPlayerJoinEvent(FPlayerJoinEvent event) { if(event.isCancelled()) { return; } File banFile = new File(Config.folderFBans, event.getFaction().getId() + "." + event.getFPlayer().getName().toLowerCase()); if(banFile.exists()) { if(Utilities.isLeader(event.getFPlayer())) { if(banFile.delete()) { FactionsPlusPlugin.info("Removed old ban file from previous faction for user " +event.getFPlayer().getName()+ " of Faction id " + event.getFaction().getId()); } } else { event.getFPlayer().msg("You can't join this Faction as you have been banned!"); event.setCancelled(true); event.getFPlayer().leave(false); } return; } } }
package multicast.search.message; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import peer.message.MessageID; import peer.peerid.PeerID; /** * This class defines a message which is used to remove invalid routes * * @author Unai Aguilera (unai.aguilera@gmail.com) * */ public class RemoveRouteMessage extends RemoteMessage { private static final long serialVersionUID = 1L; private final Set<MessageID> lostRoutes = new HashSet<MessageID>(); public RemoveRouteMessage() { } /** * Constructor of the remove route message. * * @param source * the source of the message * @param lostRoutes * the routes which have to be removed */ public RemoveRouteMessage(final PeerID source, final Set<PeerID> expectedDestinations, final Set<MessageID> lostRoutes) { super(source, expectedDestinations); this.lostRoutes.addAll(lostRoutes); } /** * Constructor of the remove route message using another message as base, * * @param removeRouteMessage * the message used as base * @param sender * the new sender of the message * @param newDistance * the new distance traveled by the message */ public RemoveRouteMessage(final RemoveRouteMessage removeRouteMessage, final PeerID sender, final Set<PeerID> expectedDestinations, final Set<MessageID> lostRoutes, final int newDistance) { super(removeRouteMessage, sender, expectedDestinations, newDistance); this.lostRoutes.addAll(lostRoutes); } /** * Gets the routes which have been lost * * @return the lost routes */ public Set<MessageID> getLostRoutes() { return lostRoutes; } @Override public String toString() { return super.toString() + " (LR: " + lostRoutes + ")"; } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); lostRoutes.addAll(Arrays.asList((MessageID[])in.readObject())); } @Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); out.writeObject(lostRoutes.toArray(new MessageID[0])); } }
package net.elprespufferfish.rssreader; import java.io.InputStream; import java.net.URL; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.util.Log; public class MainActivity extends FragmentActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final ProgressDialog dialog = ProgressDialog.show(this, "", "Loading new articles...", true); new AsyncTask<Void, Void, List<Article>>() { @Override protected List<Article> doInBackground(Void... params) { Log.i("rss-reader", "Parsing feeds in the background"); final List<Article> allArticles = Collections.synchronizedList(new LinkedList<Article>()); ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); Set<AsyncTask<String, Void, Void>> tasks = new HashSet<AsyncTask<String, Void, Void>>(); for (final String feed : getFeeds()) { AsyncTask<String, Void, Void> articleFetchingTask = new AsyncTask<String, Void, Void>() { @Override protected Void doInBackground(String... feeds) { List<Article> articles = parseFeed(feeds[0]); allArticles.addAll(articles); return null; } }.executeOnExecutor(executor, feed); tasks.add(articleFetchingTask); } for (AsyncTask<String, Void, Void> task : tasks) { try { task.get(); } catch (InterruptedException e) { Log.e("rss-reader", "Could not get articles", e); } catch (ExecutionException e) { Log.e("rss-reader", "Could not get articles", e); } } // sort by date Collections.sort(allArticles); Log.i("rss-reader", "Done parsing feeds in the background"); return allArticles; } @Override protected void onPostExecute(List<Article> articles) { ViewPager viewPager = (ViewPager) findViewById(R.id.pager); viewPager.setAdapter(new ArticlePagerAdapter(MainActivity.this.getSupportFragmentManager(), articles)); dialog.dismiss(); } }.execute(); } private List<String> getFeeds() { List<String> feeds = new LinkedList<String>(); feeds.add("http://cuteoverload.com/feed/"); // content:encoded feeds.add("http://cabinporn.com/rss"); // no inline content return feeds; } private List<Article> parseFeed(String feedAddress) { Log.i("rss-reader", "Attempting to parse " + feedAddress); try { URL feedUrl = new URL(feedAddress); InputStream feedInput = feedUrl.openStream(); XmlPullParserFactory xmlPullParserFactory = XmlPullParserFactory.newInstance(); xmlPullParserFactory.setNamespaceAware(true); XmlPullParser xmlPullParser = xmlPullParserFactory.newPullParser(); xmlPullParser.setInput(feedInput, null); List<Article> articles = new LinkedList<Article>(); int eventType = xmlPullParser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_TAG: { if ("item".equals(xmlPullParser.getName())) { articles.add(Article.fromXml(xmlPullParser)); } break; } default: { // no-op } } eventType = xmlPullParser.next(); } Log.i("rss-reader", "Finished parsing " + feedAddress); feedInput.close(); return articles; } catch (Exception e) { throw new RuntimeException("Could not parse " + feedAddress, e); } } }
package net.kevxu.purdueassist.course; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import net.kevxu.purdueassist.course.elements.Predefined.Subject; import net.kevxu.purdueassist.course.elements.Predefined.Term; import net.kevxu.purdueassist.course.elements.Predefined.Type; import net.kevxu.purdueassist.course.shared.CourseNotFoundException; import net.kevxu.purdueassist.course.shared.HttpParseException; import net.kevxu.purdueassist.shared.httpclient.BasicHttpClientAsync; import net.kevxu.purdueassist.shared.httpclient.BasicHttpClientAsync.OnRequestFinishedListener; import net.kevxu.purdueassist.shared.httpclient.HttpClientAsync.HttpMethod; import net.kevxu.purdueassist.shared.httpclient.MethodNotPostException; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.message.BasicNameValuePair; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class CatalogDetail implements OnRequestFinishedListener { private static final String URL_HEAD = "https://selfservice.mypurdue.purdue.edu/prod/" + "bzwsrch.p_catalog_detail"; private Term term; private Subject subject; private int cnbr; private OnCatalogDetailFinishedListener mListener; private BasicHttpClientAsync httpClient; public interface OnCatalogDetailFinishedListener { public void onCatalogDetailFinished(CatalogDetailEntry entry); public void onCatalogDetailFinished(IOException e); public void onCatalogDetailFinished(HttpParseException e); public void onCatalogDetailFinished(CourseNotFoundException e); } public CatalogDetail(Subject subject, int cnbr, OnCatalogDetailFinishedListener onCatalogDetailFinishedListener) { this(Term.CURRENT, subject, cnbr, onCatalogDetailFinishedListener); } public CatalogDetail(Term term, Subject subject, int cnbr, OnCatalogDetailFinishedListener onCatalogDetailFinishedListener) { if (term != null) this.term = term; else this.term = Term.CURRENT; this.subject = subject; this.cnbr = cnbr; this.mListener = onCatalogDetailFinishedListener; } public void getResult() { List<NameValuePair> parameters = new ArrayList<NameValuePair>(); parameters.add(new BasicNameValuePair("term", term.getLinkName())); parameters.add(new BasicNameValuePair("subject", subject.name())); parameters.add(new BasicNameValuePair("cnbr", Integer.toString(cnbr))); httpClient = new BasicHttpClientAsync(URL_HEAD, HttpMethod.POST, this); try { httpClient.setParameters(parameters); httpClient.getResponse(); } catch (MethodNotPostException e) { e.printStackTrace(); } } @Override public void onRequestFinished(HttpResponse httpResponse) { try { InputStream stream = httpResponse.getEntity().getContent(); Header encoding = httpResponse.getEntity().getContentEncoding(); Document document; if (encoding == null) { document = Jsoup.parse(stream, null, URL_HEAD); } else { document = Jsoup.parse(stream, encoding.getValue(), URL_HEAD); } stream.close(); CatalogDetailEntry entry = parseDocument(document); mListener.onCatalogDetailFinished(entry); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { mListener.onCatalogDetailFinished(e); } catch (HttpParseException e) { mListener.onCatalogDetailFinished(e); } catch (CourseNotFoundException e) { mListener.onCatalogDetailFinished(e); } catch (Exception e) { e.printStackTrace(); } } @Override public void onRequestFinished(ClientProtocolException e) { e.printStackTrace(); } @Override public void onRequestFinished(IOException e) { mListener.onCatalogDetailFinished(e); } private CatalogDetailEntry parseDocument(Document document) throws HttpParseException, CourseNotFoundException, IOException { CatalogDetailEntry entry = new CatalogDetailEntry(subject, cnbr); Elements tableElements = document.getElementsByAttributeValue("summary", "This table lists the course detail for the selected term."); if (tableElements.isEmpty() != true) { // get name try { Element body = tableElements.first().select("tbody").first(); String nameBlock = body.select("tr td.nttitle").first().text(); String[] temp = nameBlock.split(subject.name() + " " + String.valueOf(cnbr)); String name = temp[temp.length - 1].substring(3); entry.setName(name); // get description body = body.select(".ntdefault").first(); String text = body.text(); int split = text.indexOf("Levels:"); String description = text.substring(0, split); description = description.substring(20); entry.setDescription(description); // get levels int begin = split; int end = text.indexOf("Schedule Types:"); String levels = text.substring(begin + 8, end); temp = levels.split("[ ,]"); List<String> lvs = new ArrayList<String>(); for (String s : temp) if (!s.equals("")) { lvs.add(s); } entry.setLevels(lvs); // get type and prerequisites List<Type> types = new ArrayList<Type>(); List<String> preq = new ArrayList<String>(); Elements parsing_A = body.select("a"); for (Element e : parsing_A) { if (e.attr("href").contains("schd_in") && !(e.attr("href").contains("%"))) { try { types.add(Type.valueOf(e.text().replace(" ", ""))); } catch (Exception exception) { throw new HttpParseException(); } } else if (e.attr("href").contains("sel_attr=")) { preq.add(e.text()); } } if (types.size() > 0) entry.setType(types); if (preq.size() > 0) entry.setPrerequisites(preq); // get offered by begin = text.indexOf("Offered By:"); end = text.indexOf("Department:"); if (end < 0) end = text.indexOf("Course Attributes:"); if(end>0){ entry.setOfferedBy(text.substring(begin + 12, end - 1)); } // get department begin = text.indexOf("Department:"); if (begin > 0) { end = text.indexOf("Course Attributes:"); entry.setDepartment((text.substring(begin + 12, end - 1))); } // get campus begin = text.indexOf("May be offered at any of the following campuses:"); String campuses; end = text.indexOf("Repeatable for Additional Credit:"); if (end < 0) end = text.indexOf("Learning Objectives:"); if (end < 0) end = text.indexOf("Restrictions:"); if (end < 0) end = text.indexOf("Corequisites:"); if (end < 0) end = text.indexOf("Prerequisites:"); if (end < 0) { campuses = text.substring(begin + "May be offered at any of the following campuses:".length() + 5); } else { campuses = text.substring(begin + "May be offered at any of the following campuses:".length() + 5, end - 1); } temp = campuses.replace(" ", "#").split("#"); List<String> camps = new ArrayList<String>(); for (String s : temp) { if (s.length() > 1) { camps.add(s); } } entry.setCampuses(camps); // get restrictions begin = text.indexOf("Restrictions:"); end=text.indexOf("Corequisites:"); if(end<0) end = text.indexOf("Prerequisites:"); if (begin > 0 && end < 0) { entry.setRestrictions(text.substring(begin + "Restrictions:".length()) .replace(" ", "\n")); } else if (begin > 0) { entry.setRestrictions(text.substring(begin + "Restrictions:".length(), end).replace(" ", "\n")); } } catch (StringIndexOutOfBoundsException e) { //no type, not available // System.out.println("Error for cnbr = " + cnbr); } } else { throw new CourseNotFoundException(); } return entry; } @SuppressWarnings("unused") public class CatalogDetailEntry { private Subject searchSubject; private int searchCnbr; public CatalogDetailEntry(Subject subject, int cnbr) { this.searchSubject = subject; this.searchCnbr = cnbr; this.cnbr = cnbr; this.subject = subject; name = null; description = null; levels = null; type = null; offeredBy = null; department = null; campuses = null; restrictions = null; prerequisites = null; } private Subject subject; private int cnbr; private String name; private String description; private List<String> levels; private List<Type> type; private String offeredBy; private String department; private List<String> campuses; private String restrictions; private List<String> prerequisites; public String toString() { String myStr = ""; myStr += "Subject: " + subject.toString() + "\n"; myStr += "CNBR: " + cnbr + "\n"; if (name != null) myStr += "Name: " + name + "\n"; if (description != null) myStr += "Description: " + description + "\n"; if (levels != null) { myStr += "Level: "; for (String s : levels) myStr += s + " ; "; myStr += "\n"; } if (type != null) { myStr += "Type: "; for (Type t : type) myStr += t.toString() + " ; "; myStr += "\n"; } if (offeredBy != null) myStr += "OfferedBy: " + offeredBy + "\n"; if (department != null) myStr += "Department: " + department + "\n"; if (campuses != null) { myStr += "Campuses: "; for (String s : campuses) myStr += s + " ; "; myStr += "\n"; } if (restrictions != null) myStr += "Restrictions: " + restrictions + "\n"; if (prerequisites != null) { myStr += "Prerequisites: "; for (String s : prerequisites) myStr += s + " ; "; myStr += "\n"; } return myStr; } private Subject getSearchSubject() { return searchSubject; } private int getSearchCnbr() { return searchCnbr; } public Subject getSubject() { return subject; } public int getCnbr() { return cnbr; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<String> getLevels() { return levels; } public void setLevels(List<String> levels) { this.levels = levels; } public List<Type> getType() { return type; } public void setType(List<Type> type) { this.type = type; } public String getOfferedBy() { return offeredBy; } public void setOfferedBy(String offeredBy) { this.offeredBy = offeredBy; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public List<String> getCampuses() { return campuses; } public void setCampuses(List<String> campuses) { this.campuses = campuses; } public String getRestrictions() { return restrictions; } public void setRestrictions(String restrictions) { this.restrictions = restrictions; } public List<String> getPrerequisites() { return prerequisites; } public void setPrerequisites(List<String> prerequisites) { this.prerequisites = prerequisites; } } }
package nl.mpi.arbil.templates; import nl.mpi.arbil.*; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.Hashtable; import javax.swing.ImageIcon; import nl.mpi.arbil.clarin.CmdiProfileReader; import nl.mpi.arbil.clarin.CmdiProfileReader.CmdiProfile; import nl.mpi.arbil.data.ImdiSchema; public class ArbilTemplateManager { //private String defaultArbilTemplateName; static private ArbilTemplateManager singleInstance = null; private Hashtable<String, ArbilTemplate> templatesHashTable; private String[] builtInTemplates2 = {"Default", "Sign Language"}; // the first item in this list is the default template // private ArbilTemplate defaultArbilTemplate; //public String[] builtInTemplates = {"Corpus Branch (internal)", "Session (internal)", "Catalogue (internal)", "Sign Language (internal)"}; static synchronized public ArbilTemplateManager getSingleInstance() { if (singleInstance == null) { singleInstance = new ArbilTemplateManager(); } return singleInstance; } public File createTemplate(String selectedTemplate) { if (selectedTemplate.length() == 0) { return null; } else if (Arrays.binarySearch(builtInTemplates2, selectedTemplate) > -1) { return null; } else { File selectedTemplateFile = getTemplateFile(selectedTemplate); selectedTemplateFile.getParentFile().mkdir(); LinorgSessionStorage.getSingleInstance().saveRemoteResource(ImdiSchema.class.getResource("/nl/mpi/arbil/resources/templates/template.xml"), selectedTemplateFile, null, true, new DownloadAbortFlag()); new File(selectedTemplateFile.getParentFile(), "components").mkdir(); // create the components directory File examplesDirectory = new File(selectedTemplateFile.getParentFile(), "example-components"); examplesDirectory.mkdir(); // create the example components directory // copy example components from the jar file for (String[] pathString : ArbilTemplateManager.getSingleInstance().getTemplate(builtInTemplates2[0]).templatesArray) { LinorgSessionStorage.getSingleInstance().saveRemoteResource(ImdiSchema.class.getResource("/nl/mpi/arbil/resources/templates/" + pathString[0]), new File(examplesDirectory, pathString[0]), null, true, new DownloadAbortFlag()); } // copy example "format.xsl" from the jar file which is used in the imdi to html conversion LinorgSessionStorage.getSingleInstance().saveRemoteResource(ImdiSchema.class.getResource("/nl/mpi/arbil/resources/xsl/imdi-viewer.xsl"), new File(selectedTemplateFile.getParentFile(), "example-format.xsl"), null, true, new DownloadAbortFlag()); return selectedTemplateFile; } } public File getTemplateFile(String currentTemplate) { File currentTemplateFile = new File(getTemplateDirectory().getAbsolutePath() + File.separatorChar + currentTemplate + File.separatorChar + "template.xml"); // if (!currentTemplateFile.getParentFile().exists()) { // currentTemplateFile.getParentFile().mkdir(); return currentTemplateFile; } // public boolean defaultTemplateIsCurrentTemplate() { // return defaultArbilTemplateName.equals(builtInTemplates2[0]); // public String getCurrentTemplateName() { // return defaultArbilTemplateName; // public void setCurrentTemplate(String currentTemplateLocal) { // defaultArbilTemplateName = currentTemplateLocal; // try { // LinorgSessionStorage.getSingleInstance().saveString("CurrentTemplate", currentTemplateLocal); // } catch (Exception ex) { // GuiHelper.linorgBugCatcher.logError(ex); public File getTemplateDirectory() { return new File(LinorgSessionStorage.getSingleInstance().storageDirectory, "templates"); } public void addSelectedTemplates(String templateString) { ArrayList<String> selectedTamplates = new ArrayList<String>(); try { selectedTamplates.addAll(Arrays.asList(LinorgSessionStorage.getSingleInstance().loadStringArray("selectedTemplates"))); } catch (Exception e) { GuiHelper.linorgBugCatcher.logError("No selectedTemplates file, will create one now.", e); } selectedTamplates.add(templateString); LinorgSessionStorage.getSingleInstance().saveStringArray("selectedTemplates", selectedTamplates.toArray(new String[]{})); } public void removeSelectedTemplates(String templateString) { ArrayList<String> selectedTamplates = new ArrayList<String>(); selectedTamplates.addAll(Arrays.asList(LinorgSessionStorage.getSingleInstance().loadStringArray("selectedTemplates"))); while (selectedTamplates.contains(templateString)) { selectedTamplates.remove(templateString); } LinorgSessionStorage.getSingleInstance().saveStringArray("selectedTemplates", selectedTamplates.toArray(new String[]{})); } public ArrayList<String> getSelectedTemplateArrayList() { ArrayList<String> selectedTamplates = new ArrayList<String>(); try { selectedTamplates.addAll(Arrays.asList(LinorgSessionStorage.getSingleInstance().loadStringArray("selectedTemplates"))); } catch (Exception e) { GuiHelper.linorgBugCatcher.logError("No selectedTemplates file, will create one now.", e); } return selectedTamplates; } public class MenuItemData { public String menuText; public String menuAction; public String menuToolTip; public ImageIcon menuIcon; } public MenuItemData[] getSelectedTemplates() { ImdiIcons imdiIcons = ImdiIcons.getSingleInstance(); String[] locationsArray = LinorgSessionStorage.getSingleInstance().loadStringArray("selectedTemplates"); if (locationsArray == null || locationsArray.length == 0) { addSelectedTemplates("builtin:METATRANSCRIPT.Corpus.xml"); addSelectedTemplates("builtin:METATRANSCRIPT.Catalogue.xml"); addSelectedTemplates("builtin:METATRANSCRIPT.Session.xml"); locationsArray = LinorgSessionStorage.getSingleInstance().loadStringArray("selectedTemplates"); } MenuItemData[] returnArray = new MenuItemData[locationsArray.length]; for (int insertableCounter = 0; insertableCounter < locationsArray.length; insertableCounter++) { returnArray[insertableCounter] = new MenuItemData(); if (locationsArray[insertableCounter].startsWith("builtin:")) { String currentString = locationsArray[insertableCounter].substring("builtin:".length()); for (String currentTemplateName[] : ArbilTemplateManager.getSingleInstance().getTemplate(null).rootTemplatesArray) { if (currentString.equals(currentTemplateName[0])) { returnArray[insertableCounter].menuText = currentTemplateName[1]; returnArray[insertableCounter].menuAction = "." + currentTemplateName[0].replaceFirst("\\.xml$", ""); returnArray[insertableCounter].menuToolTip = currentTemplateName[1]; if (returnArray[insertableCounter].menuText.contains("Corpus")) { returnArray[insertableCounter].menuIcon = imdiIcons.corpusnodeColorIcon; } else if (returnArray[insertableCounter].menuText.contains("Catalogue")) { returnArray[insertableCounter].menuIcon = imdiIcons.catalogueColorIcon; } else { returnArray[insertableCounter].menuIcon = imdiIcons.sessionColorIcon; } } } } if (locationsArray[insertableCounter].startsWith("template:")) { // todo: String currentString = locationsArray[insertableCounter].substring("template:".length()); returnArray[insertableCounter].menuText = currentString + " (not available)"; returnArray[insertableCounter].menuAction = currentString; returnArray[insertableCounter].menuToolTip = currentString; returnArray[insertableCounter].menuIcon = imdiIcons.sessionColorIcon; } if (locationsArray[insertableCounter].startsWith("clarin:")) { String currentString = locationsArray[insertableCounter].substring("clarin:".length()); CmdiProfile cmdiProfile = new CmdiProfileReader().getProfile(currentString); returnArray[insertableCounter].menuText = cmdiProfile.name; returnArray[insertableCounter].menuAction = cmdiProfile.getXsdHref(); returnArray[insertableCounter].menuToolTip = cmdiProfile.description; returnArray[insertableCounter].menuIcon = imdiIcons.clarinIcon; } } Arrays.sort(returnArray, new Comparator() { public int compare(Object firstItem, Object secondItem) { return (((MenuItemData) firstItem).menuText.compareToIgnoreCase(((MenuItemData) secondItem).menuText)); } }); return returnArray; // Vector childTypes = new Vector(); // if (targetNodeUserObject instanceof ImdiTreeObject) { // String xpath = ImdiSchema.getNodePath((ImdiTreeObject) targetNodeUserObject); // childTypes = getSubnodesFromTemplatesDir(xpath); // add the main entries based on the node path of the target // if (((ImdiTreeObject) targetNodeUserObject).isCorpus()) { // add any corpus node entries // for (String[] currentTemplate : rootTemplatesArray) { // boolean suppressEntry = false; // if (currentTemplate[1].equals("Catalogue")) { // if (((ImdiTreeObject) targetNodeUserObject).hasCatalogue()) { // // make sure the catalogue can only be added once // suppressEntry = true; // if (!suppressEntry) { // childTypes.add(new String[]{currentTemplate[1], "." + currentTemplate[0].replaceFirst("\\.xml$", "")}); //// System.out.println("childTypes: " + childTypes); // } else { // // add the the root node items // for (String[] currentTemplate : rootTemplatesArray) { // if (!currentTemplate[1].equals("Catalogue")) {// make sure the catalogue can not be added at the root level // childTypes.add(new String[]{"Unattached " + currentTemplate[1], "." + currentTemplate[0].replaceFirst("\\.xml$", "")}); // Collections.sort(childTypes, new Comparator() { // public int compare(Object o1, Object o2) { // String value1 = ((String[]) o1)[0]; // String value2 = ((String[]) o2)[0]; // return value1.compareTo(value2); // return childTypes.elements(); // HashSet<String> locationsSet = new HashSet<String>(); // for (ImdiTreeObject[] currentTreeArray : new ImdiTreeObject[][]{remoteCorpusNodes, localCorpusNodes, localFileNodes, favouriteNodes}) { // for (ImdiTreeObject currentLocation : currentTreeArray) { // locationsSet.add(currentLocation.getUrlString()); // if (nodesToAdd != null) { // for (ImdiTreeObject currentAddable : nodesToAdd) { // locationsSet.add(currentAddable.getUrlString()); // if (nodesToRemove != null) { // for (ImdiTreeObject currentRemoveable : nodesToRemove) { // locationsSet.remove(currentRemoveable.getUrlString()); // Vector<String> locationsList = new Vector<String>(); // this vector is kept for backwards compatability // for (String currentLocation : locationsSet) { // locationsList.add(URLDecoder.decode(currentLocation, "UTF-8")); // //LinorgSessionStorage.getSingleInstance().saveObject(locationsList, "locationsList"); // LinorgSessionStorage.getSingleInstance().saveStringArray("locationsList", locationsList.toArray(new String[]{})); } public String[] getAvailableTemplates() { File templatesDir = getTemplateDirectory(); if (!templatesDir.exists()) { templatesDir.mkdir(); } ArrayList<String> templateList = new ArrayList<String>(); String[] templatesList = templatesDir.list(); for (String currentTemplateName : templatesList) { // if the template file does not exist then remove from the array if (getTemplateFile(currentTemplateName).exists()) { templateList.add(currentTemplateName); } } // for (String currentTemplateName : builtInTemplates) { // // add the Default and SignLanguage built in templates // templateList.add(currentTemplateName); templatesList = templateList.toArray(new String[]{}); Arrays.sort(templatesList); return templatesList; } private ArbilTemplateManager() { templatesHashTable = new Hashtable<String, ArbilTemplate>(); // defaultArbilTemplateName = LinorgSessionStorage.getSingleInstance().loadString("CurrentTemplate"); // if (defaultArbilTemplateName == null) { // defaultArbilTemplateName = builtInTemplates2[0]; // LinorgSessionStorage.getSingleInstance().saveString("CurrentTemplate", defaultArbilTemplateName); } public ArbilTemplate getDefaultTemplate() { return getTemplate(builtInTemplates2[0]); } public ArbilTemplate getCmdiTemplate(String nameSpaceString) { if (nameSpaceString != null) { CmdiTemplate cmdiTemplate = (CmdiTemplate) templatesHashTable.get(nameSpaceString); if (cmdiTemplate == null) { cmdiTemplate = new CmdiTemplate(); cmdiTemplate.loadTemplate(nameSpaceString); templatesHashTable.put(nameSpaceString, cmdiTemplate); } return cmdiTemplate; } else { GuiHelper.linorgBugCatcher.logError(new Exception("Name space URL not provided, cannot load the CMDI template, please check the XML file and ensure that the name space is specified.")); return null; } } public ArbilTemplate getTemplate(String templateName) { ArbilTemplate returnTemplate = new ArbilTemplate(); if (templateName == null) { templateName = builtInTemplates2[0]; // if the template does not exist the default values will be loaded } if (!templatesHashTable.containsKey(templateName)) { // LinorgWindowManager.getSingleInstance().addMessageDialogToQueue("Template Not Found: " + templateName, "Arbil Template Manager"); returnTemplate.readTemplate(getTemplateFile(templateName), templateName); templatesHashTable.put(templateName, returnTemplate); } else { returnTemplate = templatesHashTable.get(templateName); } return returnTemplate; } }
package nu.validator.messages; import java.io.IOException; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import nu.validator.io.SystemIdIOException; import nu.validator.messages.types.MessageType; import nu.validator.saxtree.DocumentFragment; import nu.validator.saxtree.TreeParser; import nu.validator.servlet.imagereview.Image; import nu.validator.servlet.imagereview.ImageCollector; import nu.validator.source.Location; import nu.validator.source.SourceCode; import nu.validator.source.SourceHandler; import nu.validator.spec.EmptySpec; import nu.validator.spec.Spec; import nu.validator.spec.html5.Html5AttributeDatatypeBuilder; import nu.validator.spec.html5.ImageReportAdviceBuilder; import nu.validator.xml.AttributesImpl; import nu.validator.xml.CharacterUtil; import nu.validator.xml.XhtmlSaxEmitter; import org.apache.log4j.Logger; import org.relaxng.datatype.DatatypeException; import org.whattf.checker.NormalizationChecker; import org.whattf.datatype.Html5DatatypeException; import org.whattf.io.DataUri; import org.xml.sax.ContentHandler; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import com.ibm.icu.text.Normalizer; import com.thaiopensource.relaxng.exceptions.AbstractValidationException; import com.thaiopensource.relaxng.exceptions.BadAttributeValueException; import com.thaiopensource.relaxng.exceptions.ImpossibleAttributeIgnoredException; import com.thaiopensource.relaxng.exceptions.OnlyTextNotAllowedException; import com.thaiopensource.relaxng.exceptions.OutOfContextElementException; import com.thaiopensource.relaxng.exceptions.RequiredAttributesMissingException; import com.thaiopensource.relaxng.exceptions.RequiredElementsMissingException; import com.thaiopensource.relaxng.exceptions.StringNotAllowedException; import com.thaiopensource.relaxng.exceptions.TextNotAllowedException; import com.thaiopensource.relaxng.exceptions.UnfinishedElementException; import com.thaiopensource.relaxng.exceptions.UnknownElementException; import com.thaiopensource.xml.util.Name; public final class MessageEmitterAdapter implements ErrorHandler { private static final Logger log4j = Logger.getLogger(MessageEmitterAdapter.class); private final static Map<String, char[]> WELL_KNOWN_NAMESPACES = new HashMap<String, char[]>(); static { WELL_KNOWN_NAMESPACES.put("", "unnamespaced".toCharArray()); WELL_KNOWN_NAMESPACES.put("http: WELL_KNOWN_NAMESPACES.put("http: WELL_KNOWN_NAMESPACES.put("http: WELL_KNOWN_NAMESPACES.put("http: WELL_KNOWN_NAMESPACES.put("http: WELL_KNOWN_NAMESPACES.put("http://docbook.org/ns/docbook", "DocBook".toCharArray()); WELL_KNOWN_NAMESPACES.put("http://relaxng.org/ns/structure/1.0", "RELAX NG".toCharArray()); WELL_KNOWN_NAMESPACES.put("http: WELL_KNOWN_NAMESPACES.put("http: WELL_KNOWN_NAMESPACES.put("http: WELL_KNOWN_NAMESPACES.put("http: WELL_KNOWN_NAMESPACES.put("http://www.w3.org/1999/02/22-rdf-syntax-ns#", "RDF".toCharArray()); WELL_KNOWN_NAMESPACES.put("http://purl.org/dc/elements/1.1/", "Dublin Core".toCharArray()); WELL_KNOWN_NAMESPACES.put("http: WELL_KNOWN_NAMESPACES.put("http: WELL_KNOWN_NAMESPACES.put("http: WELL_KNOWN_NAMESPACES.put("http://purl.oclc.org/dsdl/schematron", "ISO Schematron".toCharArray()); WELL_KNOWN_NAMESPACES.put("http: WELL_KNOWN_NAMESPACES.put("http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd", "Sodipodi".toCharArray()); WELL_KNOWN_NAMESPACES.put("http: WELL_KNOWN_NAMESPACES.put("http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/", "Adobe SVG Viewer 3.0 extension".toCharArray()); WELL_KNOWN_NAMESPACES.put("http://ns.adobe.com/AdobeIllustrator/10.0/", "Adobe Illustrator 10.0".toCharArray()); WELL_KNOWN_NAMESPACES.put("adobe:ns:meta/", "XMP Container".toCharArray()); WELL_KNOWN_NAMESPACES.put("http://ns.adobe.com/xap/1.0/", "XMP".toCharArray()); WELL_KNOWN_NAMESPACES.put("http://ns.adobe.com/pdf/1.3/", "Adobe PDF 1.3".toCharArray()); WELL_KNOWN_NAMESPACES.put("http://ns.adobe.com/tiff/1.0/", "Adobe TIFF".toCharArray()); } private final static Map<Class, DocumentFragment> HTML5_DATATYPE_ADVICE = new HashMap<Class, DocumentFragment>(); private final static DocumentFragment IMAGE_REPORT_GENERAL; private final static DocumentFragment IMAGE_REPORT_EMPTY; private final static DocumentFragment NO_ALT_NO_LINK_ADVICE; private final static DocumentFragment NO_ALT_LINK_ADVICE; private final static DocumentFragment EMPTY_ALT_ADVICE; private final static DocumentFragment HAS_ALT_ADVICE; private final static DocumentFragment IMAGE_REPORT_FATAL; static { try { InputSource in = new InputSource(System.getProperty("nu.validator.spec.microsyntax-descriptions", "http://wiki.whatwg.org/wiki/MicrosyntaxDescriptions")); HTML5_DATATYPE_ADVICE.putAll(Html5AttributeDatatypeBuilder.parseSyntaxDescriptions(in)); in = new InputSource(System.getProperty("nu.validator.spec.alt-advice", "http://wiki.whatwg.org/wiki/Validator.nu_alt_advice")); List<DocumentFragment> list = ImageReportAdviceBuilder.parseAltAdvice(in); IMAGE_REPORT_GENERAL = list.get(0); NO_ALT_NO_LINK_ADVICE = list.get(1); NO_ALT_LINK_ADVICE = list.get(2); EMPTY_ALT_ADVICE = list.get(3); HAS_ALT_ADVICE = list.get(4); IMAGE_REPORT_EMPTY = list.get(5); IMAGE_REPORT_FATAL = list.get(6); } catch (IOException e) { throw new RuntimeException(e); } catch (SAXException e) { throw new RuntimeException(e); } } private final static char[] INDETERMINATE_MESSAGE = "The result cannot be determined due to a non-document-error.".toCharArray(); private final static char[] ELEMENT_SPECIFIC_ATTRIBUTES_BEFORE = "Element-specific attributes for element ".toCharArray(); private final static char[] ELEMENT_SPECIFIC_ATTRIBUTES_AFTER = ":".toCharArray(); private final static char[] CONTENT_MODEL_BEFORE = "Content model for element ".toCharArray(); private final static char[] CONTENT_MODEL_AFTER = ":".toCharArray(); private final static char[] CONTEXT_BEFORE = "Contexts in which element ".toCharArray(); private final static char[] CONTEXT_AFTER = " may be used:".toCharArray(); private final static char[] BAD_VALUE = "Bad value ".toCharArray(); private final static char[] FOR = " for ".toCharArray(); private final static char[] ATTRIBUTE = "attribute ".toCharArray(); private final static char[] FROM_NAMESPACE = " from namespace ".toCharArray(); private final static char[] SPACE = " ".toCharArray(); private final static char[] ON = " on ".toCharArray(); private final static char[] ELEMENT = "element ".toCharArray(); private final static char[] PERIOD = ".".toCharArray(); private final static char[] COLON = ":".toCharArray(); private final static char[] NOT_ALLOWED_ON = " not allowed on ".toCharArray(); private final static char[] AT_THIS_POINT = " at this point.".toCharArray(); private final static char[] ONLY_TEXT = " is not allowed to have content that consists solely of text.".toCharArray(); private final static char[] NOT_ALLOWED = " not allowed".toCharArray(); private final static char[] AS_CHILD_OF = " as child of ".toCharArray(); private final static char[] IN_THIS_CONTEXT_SUPPRESSING = " in this context. (Suppressing further errors from this subtree.)".toCharArray(); private final static char[] REQUIRED_ATTRIBUTES_MISSING = "Required attributes missing on ".toCharArray(); private final static char[] REQUIRED_ELEMENTS_MISSING = "Required elements missing.".toCharArray(); private final static char[] REQUIRED_CHILDREN_MISSING_FROM = "Required children missing from ".toCharArray(); private final static char[] BAD_CHARACTER_CONTENT = "Bad character content ".toCharArray(); private final static char[] IN_THIS_CONTEXT = " in this context.".toCharArray(); private final static char[] TEXT_NOT_ALLOWED_IN = "Text not allowed in ".toCharArray(); private final static char[] UNKNOWN = "Unknown ".toCharArray(); private static final char[] NO_ALT_NO_LINK_HEADING = "No textual alternative available, not linked".toCharArray(); private static final char[] NO_ALT_LINK_HEADING = "No textual alternative available, image linked".toCharArray(); private static final char[] EMPTY_ALT = "Empty textual alternative\u2014Omitted from non-graphical presentation".toCharArray(); private static final char[] HAS_ALT = "Images with textual alternative".toCharArray(); private final AttributesImpl attributesImpl = new AttributesImpl(); private final char[] oneChar = {'\u0000'}; private int warnings = 0; private int errors = 0; private int fatalErrors = 0; private int nonDocumentErrors = 0; private final SourceCode sourceCode; private final MessageEmitter emitter; private final ExactErrorHandler exactErrorHandler; private final boolean showSource; private final ImageCollector imageCollector; private final int lineOffset; private Spec spec = EmptySpec.THE_INSTANCE; private boolean html = false; private boolean loggingOk = false; private boolean errorsOnly = false; protected static String scrub(String s) throws SAXException { if (s == null) { return null; } s = CharacterUtil.prudentlyScrubCharacterData(s); if (NormalizationChecker.startsWithComposingChar(s)) { s = " " + s; } return Normalizer.normalize(s, Normalizer.NFC, 0); } private StringBuilder zapLf(StringBuilder builder) { int len = builder.length(); for (int i = 0; i < len; i++) { char c = builder.charAt(i); if (c == '\n' || c == '\r') { builder.setCharAt(i, ' '); } } return builder; } private void throwIfTooManyMessages() throws SAXException { if (warnings + errors > 1000) { throw new TooManyErrorsException("Too many messages."); } } public MessageEmitterAdapter(SourceCode sourceCode, boolean showSource, ImageCollector imageCollector, int lineOffset, MessageEmitter messageEmitter) { super(); this.sourceCode = sourceCode; this.emitter = messageEmitter; this.exactErrorHandler = new ExactErrorHandler(this); this.showSource = showSource; this.lineOffset = lineOffset; this.imageCollector = imageCollector; } /** * @return Returns the errors. */ public int getErrors() { return errors; } /** * @return Returns the fatalErrors. */ public int getFatalErrors() { return fatalErrors; } /** * @return Returns the warnings. */ public int getWarnings() { return warnings; } private boolean isErrors() { return !(errors == 0 && fatalErrors == 0); } /** * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException) */ public void warning(SAXParseException e) throws SAXException { warning(e, false); } /** * @param e * @throws SAXException */ private void warning(SAXParseException e, boolean exact) throws SAXException { if (fatalErrors > 0 || nonDocumentErrors > 0) { return; } this.warnings++; throwIfTooManyMessages(); messageFromSAXParseException(MessageType.WARNING, e, exact); } /** * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException) */ public void error(SAXParseException e) throws SAXException { error(e, false); } /** * @param e * @throws SAXException */ private void error(SAXParseException e, boolean exact) throws SAXException { if (fatalErrors > 0 || nonDocumentErrors > 0) { return; } if (e instanceof BadAttributeValueException) { BadAttributeValueException ex = (BadAttributeValueException) e; Map<String, DatatypeException> datatypeErrors = ex.getExceptions(); for (Map.Entry<String, DatatypeException> entry : datatypeErrors.entrySet()) { DatatypeException dex = entry.getValue(); if (dex instanceof Html5DatatypeException) { Html5DatatypeException ex5 = (Html5DatatypeException) dex; if (ex5.isWarning()) { this.warnings++; throwIfTooManyMessages(); messageFromSAXParseException(MessageType.WARNING, e, exact); return; } } } } this.errors++; throwIfTooManyMessages(); messageFromSAXParseException(MessageType.ERROR, e, exact); } /** * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException) */ public void fatalError(SAXParseException e) throws SAXException { fatalError(e, false); } /** * @param e * @throws SAXException */ private void fatalError(SAXParseException e, boolean exact) throws SAXException { if (fatalErrors > 0 || nonDocumentErrors > 0) { return; } this.fatalErrors++; Exception wrapped = e.getException(); if (wrapped instanceof IOException) { message(MessageType.IO, wrapped, null, -1, -1, false); } else { messageFromSAXParseException(MessageType.FATAL, e, exact); } } /** * @see nu.validator.servlet.InfoErrorHandler#info(java.lang.String) */ public void info(String str) throws SAXException { message(MessageType.INFO, new Exception(str), null, -1, -1, false); } /** * @see nu.validator.servlet.InfoErrorHandler#ioError(java.io.IOException) */ public void ioError(IOException e) throws SAXException { this.nonDocumentErrors++; String systemId = null; if (e instanceof SystemIdIOException) { SystemIdIOException siie = (SystemIdIOException) e; systemId = siie.getSystemId(); } message(MessageType.IO, e, systemId, -1, -1, false); } /** * @see nu.validator.servlet.InfoErrorHandler#internalError(java.lang.Throwable, * java.lang.String) */ public void internalError(Throwable e, String message) throws SAXException { this.nonDocumentErrors++; message(MessageType.INTERNAL, new Exception(message), null, -1, -1, false); } /** * @see nu.validator.servlet.InfoErrorHandler#schemaError(java.lang.Exception) */ public void schemaError(Exception e) throws SAXException { this.nonDocumentErrors++; message(MessageType.SCHEMA, e, null, -1, -1, false); } /** * @see nu.validator.servlet.InfoErrorHandler#start() */ public void start(String documentUri) throws SAXException { emitter.startMessages(scrub(shortenDataUri(documentUri)), showSource); } private String shortenDataUri(String uri) { if (DataUri.startsWithData(uri)) { return "data:\u2026"; } else { return uri; } } /** * @see nu.validator.servlet.InfoErrorHandler#end() */ public void end(String successMessage, String failureMessage) throws SAXException { ResultHandler resultHandler = emitter.startResult(); if (resultHandler != null) { if (isIndeterminate()) { resultHandler.startResult(Result.INDETERMINATE); resultHandler.characters(INDETERMINATE_MESSAGE, 0, INDETERMINATE_MESSAGE.length); resultHandler.endResult(); } else if (isErrors()) { resultHandler.startResult(Result.FAILURE); resultHandler.characters(failureMessage.toCharArray(), 0, failureMessage.length()); resultHandler.endResult(); } else { resultHandler.startResult(Result.SUCCESS); resultHandler.characters(successMessage.toCharArray(), 0, successMessage.length()); resultHandler.endResult(); } } emitter.endResult(); if (imageCollector != null) { DocumentFragment instruction = IMAGE_REPORT_GENERAL; boolean fatal = false; if (getFatalErrors() > 0) { fatal = true; instruction = IMAGE_REPORT_FATAL; } else if (imageCollector.isEmpty()) { instruction = IMAGE_REPORT_EMPTY; } ImageReviewHandler imageReviewHandler = emitter.startImageReview(instruction, fatal); if (imageReviewHandler != null && !fatal) { emitImageReview(imageReviewHandler); } emitter.endImageReview(); } if (showSource) { SourceHandler sourceHandler = emitter.startFullSource(lineOffset); if (sourceHandler != null) { sourceCode.emitSource(sourceHandler); } emitter.endFullSource(); } emitter.endMessages(); } private void emitImageReview(ImageReviewHandler imageReviewHandler) throws SAXException { List<Image> noAltNoLink = new LinkedList<Image>(); List<Image> noAltLink = new LinkedList<Image>(); List<Image> emptyAlt = new LinkedList<Image>(); List<Image> hasAlt = new LinkedList<Image>(); for (Image image : imageCollector) { String alt = image.getAlt(); if (alt == null) { if (image.isLinked()) { noAltLink.add(image); } else { noAltNoLink.add(image); } } else if ("".equals(alt)) { emptyAlt.add(image); } else { hasAlt.add(image); } } emitImageList(imageReviewHandler, noAltLink, NO_ALT_LINK_HEADING, NO_ALT_LINK_ADVICE, false); emitImageList(imageReviewHandler, noAltNoLink, NO_ALT_NO_LINK_HEADING, NO_ALT_NO_LINK_ADVICE, false); emitImageList(imageReviewHandler, emptyAlt, EMPTY_ALT, EMPTY_ALT_ADVICE, false); emitImageList(imageReviewHandler, hasAlt, HAS_ALT, HAS_ALT_ADVICE, true); } private void emitImageList(ImageReviewHandler imageReviewHandler, List<Image> list, char[] heading, DocumentFragment instruction, boolean hasAlt) throws SAXException { if (!list.isEmpty()) { imageReviewHandler.startImageGroup(heading, instruction, hasAlt); for (Image image : list) { String systemId = image.getSystemId(); int oneBasedLine = image.getLineNumber(); int oneBasedColumn = image.getColumnNumber(); Location rangeLast = sourceCode.newLocatorLocation(oneBasedLine, oneBasedColumn); if (sourceCode.isWithinKnownSource(rangeLast)) { Location rangeStart = sourceCode.rangeStartForRangeLast(rangeLast); imageReviewHandler.image(image, hasAlt, systemId, rangeStart.getLine() + 1, rangeStart.getColumn() + 1, oneBasedLine, oneBasedColumn); } else { imageReviewHandler.image(image, hasAlt, systemId, -1, -1, -1, -1); } } imageReviewHandler.endImageGroup(); } } private boolean isIndeterminate() { return nonDocumentErrors > 0; } private void messageFromSAXParseException(MessageType type, SAXParseException spe, boolean exact) throws SAXException { message(type, spe, spe.getSystemId(), spe.getLineNumber(), spe.getColumnNumber(), exact); } private void message(MessageType type, Exception message, String systemId, int oneBasedLine, int oneBasedColumn, boolean exact) throws SAXException { if (loggingOk && (type.getSuperType() == "error") && spec != EmptySpec.THE_INSTANCE && systemId != null && (systemId.startsWith("http:") || systemId.startsWith("https:"))) { log4j.info(zapLf(new StringBuilder().append(systemId).append('\t').append( message.getMessage()))); } if (errorsOnly && type.getSuperType() == "info") { return; } String uri = sourceCode.getUri(); if (oneBasedLine > -1 && (uri == systemId || (uri != null && uri.equals(systemId)))) { if (oneBasedColumn > -1) { if (exact) { messageWithExact(type, message, oneBasedLine, oneBasedColumn); } else { messageWithRange(type, message, oneBasedLine, oneBasedColumn); } } else { messageWithLine(type, message, oneBasedLine); } } else { messageWithoutExtract(type, message, systemId, oneBasedLine, oneBasedColumn); } } private void messageWithRange(MessageType type, Exception message, int oneBasedLine, int oneBasedColumn) throws SAXException { Location rangeLast = sourceCode.newLocatorLocation(oneBasedLine, oneBasedColumn); if (!sourceCode.isWithinKnownSource(rangeLast)) { messageWithoutExtract(type, message, null, oneBasedLine, oneBasedColumn); return; } Location rangeStart = sourceCode.rangeStartForRangeLast(rangeLast); startMessage(type, null, rangeStart.getLine() + 1, rangeStart.getColumn() + 1, oneBasedLine, oneBasedColumn, false); messageText(message); SourceHandler sourceHandler = emitter.startSource(); if (sourceHandler != null) { sourceCode.rangeEndError(rangeStart, rangeLast, sourceHandler); } emitter.endSource(); elaboration(message); endMessage(); } private void messageWithExact(MessageType type, Exception message, int oneBasedLine, int oneBasedColumn) throws SAXException { startMessage(type, null, oneBasedLine, oneBasedColumn, oneBasedLine, oneBasedColumn, true); messageText(message); Location location = sourceCode.newLocatorLocation(oneBasedLine, oneBasedColumn); if (sourceCode.isWithinKnownSource(location)) { SourceHandler sourceHandler = emitter.startSource(); if (sourceHandler != null) { sourceCode.exactError(location, sourceHandler); } emitter.endSource(); } else { sourceCode.rememberExactError(location); } elaboration(message); endMessage(); } private void messageWithLine(MessageType type, Exception message, int oneBasedLine) throws SAXException { if (!sourceCode.isWithinKnownSource(oneBasedLine)) { throw new RuntimeException("Bug. Line out of range!"); } startMessage(type, null, oneBasedLine, -1, oneBasedLine, -1, false); messageText(message); SourceHandler sourceHandler = emitter.startSource(); if (sourceHandler != null) { sourceCode.lineError(oneBasedLine, sourceHandler); } emitter.endSource(); elaboration(message); endMessage(); } private void messageWithoutExtract(MessageType type, Exception message, String systemId, int oneBasedLine, int oneBasedColumn) throws SAXException { startMessage(type, scrub(shortenDataUri(systemId)), oneBasedLine, oneBasedColumn, oneBasedLine, oneBasedColumn, false); messageText(message); elaboration(message); endMessage(); } /** * @param message * @throws SAXException */ private void messageText(Exception message) throws SAXException { if (message instanceof AbstractValidationException) { AbstractValidationException ave = (AbstractValidationException) message; rngMessageText(ave); } else { String msg = message.getMessage(); if (msg != null) { MessageTextHandler messageTextHandler = emitter.startText(); if (messageTextHandler != null) { emitStringWithQurlyQuotes(messageTextHandler, msg); } emitter.endText(); } } } @SuppressWarnings("unchecked") private void rngMessageText(AbstractValidationException e) throws SAXException { MessageTextHandler messageTextHandler = emitter.startText(); if (messageTextHandler != null) { if (e instanceof BadAttributeValueException) { BadAttributeValueException ex = (BadAttributeValueException) e; messageTextString(messageTextHandler, BAD_VALUE, false); codeString(messageTextHandler, ex.getAttributeValue()); messageTextString(messageTextHandler, FOR, false); attribute(messageTextHandler, ex.getAttributeName(), ex.getCurrentElement(), false); messageTextString(messageTextHandler, ON, false); element(messageTextHandler, ex.getCurrentElement(), false); emitDatatypeErrors(messageTextHandler, ex.getExceptions()); } else if (e instanceof ImpossibleAttributeIgnoredException) { ImpossibleAttributeIgnoredException ex = (ImpossibleAttributeIgnoredException) e; attribute(messageTextHandler, ex.getAttributeName(), ex.getCurrentElement(), true); messageTextString(messageTextHandler, NOT_ALLOWED_ON, false); element(messageTextHandler, ex.getCurrentElement(), false); messageTextString(messageTextHandler, AT_THIS_POINT, false); } else if (e instanceof OnlyTextNotAllowedException) { OnlyTextNotAllowedException ex = (OnlyTextNotAllowedException) e; element(messageTextHandler, ex.getCurrentElement(), true); messageTextString(messageTextHandler, ONLY_TEXT, false); } else if (e instanceof OutOfContextElementException) { OutOfContextElementException ex = (OutOfContextElementException) e; element(messageTextHandler, ex.getCurrentElement(), true); messageTextString(messageTextHandler, NOT_ALLOWED, false); if (ex.getParent() != null) { messageTextString(messageTextHandler, AS_CHILD_OF, false); element(messageTextHandler, ex.getParent(), false); } messageTextString(messageTextHandler, IN_THIS_CONTEXT_SUPPRESSING, false); } else if (e instanceof RequiredAttributesMissingException) { RequiredAttributesMissingException ex = (RequiredAttributesMissingException) e; messageTextString(messageTextHandler, REQUIRED_ATTRIBUTES_MISSING, false); element(messageTextHandler, ex.getCurrentElement(), false); messageTextString(messageTextHandler, PERIOD, false); } else if (e instanceof RequiredElementsMissingException) { RequiredElementsMissingException ex = (RequiredElementsMissingException) e; if (ex.getParent() == null) { messageTextString(messageTextHandler, REQUIRED_ELEMENTS_MISSING, false); } else { messageTextString(messageTextHandler, REQUIRED_CHILDREN_MISSING_FROM, false); element(messageTextHandler, ex.getParent(), false); messageTextString(messageTextHandler, PERIOD, false); } } else if (e instanceof StringNotAllowedException) { StringNotAllowedException ex = (StringNotAllowedException) e; messageTextString(messageTextHandler, BAD_CHARACTER_CONTENT, false); codeString(messageTextHandler, ex.getValue()); messageTextString(messageTextHandler, FOR, false); element(messageTextHandler, ex.getCurrentElement(), false); emitDatatypeErrors(messageTextHandler, ex.getExceptions()); } else if (e instanceof TextNotAllowedException) { TextNotAllowedException ex = (TextNotAllowedException) e; messageTextString(messageTextHandler, TEXT_NOT_ALLOWED_IN, false); element(messageTextHandler, ex.getCurrentElement(), false); messageTextString(messageTextHandler, IN_THIS_CONTEXT, false); } else if (e instanceof UnfinishedElementException) { UnfinishedElementException ex = (UnfinishedElementException) e; messageTextString(messageTextHandler, REQUIRED_CHILDREN_MISSING_FROM, false); element(messageTextHandler, ex.getCurrentElement(), false); messageTextString(messageTextHandler, PERIOD, false); } else if (e instanceof UnknownElementException) { UnknownElementException ex = (UnknownElementException) e; messageTextString(messageTextHandler, UNKNOWN, false); element(messageTextHandler, ex.getCurrentElement(), false); messageTextString(messageTextHandler, NOT_ALLOWED, false); if (ex.getParent() != null) { messageTextString(messageTextHandler, AS_CHILD_OF, false); element(messageTextHandler, ex.getParent(), false); } messageTextString(messageTextHandler, PERIOD, false); } } emitter.endText(); } /** * @param messageTextHandler * @param datatypeErrors * @throws SAXException */ private void emitDatatypeErrors(MessageTextHandler messageTextHandler, Map<String, DatatypeException> datatypeErrors) throws SAXException { if (datatypeErrors.isEmpty()) { messageTextString(messageTextHandler, PERIOD, false); } else { messageTextString(messageTextHandler, COLON, false); for (Map.Entry<String, DatatypeException> entry : datatypeErrors.entrySet()) { messageTextString(messageTextHandler, SPACE, false); DatatypeException ex = entry.getValue(); if (ex instanceof Html5DatatypeException) { Html5DatatypeException ex5 = (Html5DatatypeException) ex; String[] segments = ex5.getSegments(); for (int i = 0; i < segments.length; i++) { String segment = segments[i]; if (i % 2 == 0) { emitStringWithQurlyQuotes(messageTextHandler, segment); } else { String scrubbed = scrub(segment); messageTextHandler.startCode(); messageTextHandler.characters(scrubbed.toCharArray(), 0, scrubbed.length()); messageTextHandler.endCode(); } } } else { emitStringWithQurlyQuotes(messageTextHandler, ex.getMessage()); } } } } private void element(MessageTextHandler messageTextHandler, Name element, boolean atSentenceStart) throws SAXException { if (html) { messageTextString(messageTextHandler, ELEMENT, atSentenceStart); linkedCodeString(messageTextHandler, element.getLocalName(), spec.elementLink(element)); } else { String ns = element.getNamespaceUri(); char[] humanReadable = WELL_KNOWN_NAMESPACES.get(ns); if (humanReadable == null) { if (loggingOk) { log4j.info(new StringBuilder().append("UNKNOWN_NS:\t").append(ns)); } messageTextString(messageTextHandler, ELEMENT, atSentenceStart); linkedCodeString(messageTextHandler, element.getLocalName(), spec.elementLink(element)); messageTextString(messageTextHandler, FROM_NAMESPACE, false); codeString(messageTextHandler, ns); } else { messageTextString(messageTextHandler, humanReadable, atSentenceStart); messageTextString(messageTextHandler, SPACE, false); messageTextString(messageTextHandler, ELEMENT, false); linkedCodeString(messageTextHandler, element.getLocalName(), spec.elementLink(element)); } } } private void linkedCodeString(MessageTextHandler messageTextHandler, String str, String url) throws SAXException { if (url != null) { messageTextHandler.startLink(url, null); } codeString(messageTextHandler, str); if (url != null) { messageTextHandler.endLink(); } } private void attribute(MessageTextHandler messageTextHandler, Name attributeName, Name elementName, boolean atSentenceStart) throws SAXException { String ns = attributeName.getNamespaceUri(); if (html || "".equals(ns)) { messageTextString(messageTextHandler, ATTRIBUTE, atSentenceStart); codeString(messageTextHandler, attributeName.getLocalName()); } else if ("http: messageTextString(messageTextHandler, ATTRIBUTE, atSentenceStart); codeString(messageTextHandler, "xml:" + attributeName.getLocalName()); } else { char[] humanReadable = WELL_KNOWN_NAMESPACES.get(ns); if (humanReadable == null) { if (loggingOk) { log4j.info(new StringBuilder().append("UNKNOWN_NS:\t").append(ns)); } messageTextString(messageTextHandler, ATTRIBUTE, atSentenceStart); codeString(messageTextHandler, attributeName.getLocalName()); messageTextString(messageTextHandler, FROM_NAMESPACE, false); codeString(messageTextHandler, ns); } else { messageTextString(messageTextHandler, humanReadable, atSentenceStart); messageTextString(messageTextHandler, SPACE, false); messageTextString(messageTextHandler, ATTRIBUTE, false); codeString(messageTextHandler, attributeName.getLocalName()); } } } private void codeString(MessageTextHandler messageTextHandler, String str) throws SAXException { messageTextHandler.startCode(); messageTextHandler.characters(str.toCharArray(), 0, str.length()); messageTextHandler.endCode(); } private void messageTextString(MessageTextHandler messageTextHandler, char[] ch, boolean capitalize) throws SAXException { if (capitalize && ch[0] >= 'a' && ch[0] <= 'z') { oneChar[0] = (char) (ch[0] - 0x20); messageTextHandler.characters(oneChar, 0, 1); if (ch.length > 1) { messageTextHandler.characters(ch, 1, ch.length - 1); } } else { messageTextHandler.characters(ch, 0, ch.length); } } private void emitStringWithQurlyQuotes(MessageTextHandler messageTextHandler, String message) throws SAXException { if (message == null) { message = ""; } message = scrub(message); int len = message.length(); int start = 0; int startQuotes = 0; for (int i = 0; i < len; i++) { char c = message.charAt(i); if (c == '\u201C') { startQuotes++; if (startQuotes == 1) { char[] scrubbed = scrub(message.substring(start, i)).toCharArray(); messageTextHandler.characters(scrubbed, 0, scrubbed.length); start = i + 1; messageTextHandler.startCode(); } } else if (c == '\u201D' && startQuotes > 0) { startQuotes if (startQuotes == 0) { char[] scrubbed = scrub(message.substring(start, i)).toCharArray(); messageTextHandler.characters(scrubbed, 0, scrubbed.length); start = i + 1; messageTextHandler.endCode(); } } } if (start < len) { char[] scrubbed = scrub(message.substring(start, len)).toCharArray(); messageTextHandler.characters(scrubbed, 0, scrubbed.length); } if (startQuotes > 0) { messageTextHandler.endCode(); } } @SuppressWarnings("unchecked") private void elaboration(Exception e) throws SAXException { if (!(e instanceof AbstractValidationException)) { return; } if (e instanceof ImpossibleAttributeIgnoredException) { ImpossibleAttributeIgnoredException ex = (ImpossibleAttributeIgnoredException) e; Name elt = ex.getCurrentElement(); elaborateElementSpecificAttributes(elt); } else if (e instanceof OnlyTextNotAllowedException) { OnlyTextNotAllowedException ex = (OnlyTextNotAllowedException) e; Name elt = ex.getCurrentElement(); elaborateContentModel(elt); } else if (e instanceof OutOfContextElementException) { OutOfContextElementException ex = (OutOfContextElementException) e; Name parent = ex.getParent(); Name child = ex.getCurrentElement(); elaborateContentModelandContext(parent, child); } else if (e instanceof RequiredAttributesMissingException) { RequiredAttributesMissingException ex = (RequiredAttributesMissingException) e; Name elt = ex.getCurrentElement(); elaborateElementSpecificAttributes(elt); } else if (e instanceof RequiredElementsMissingException) { RequiredElementsMissingException ex = (RequiredElementsMissingException) e; Name elt = ex.getParent(); elaborateContentModel(elt); } else if (e instanceof StringNotAllowedException) { StringNotAllowedException ex = (StringNotAllowedException) e; Name elt = ex.getCurrentElement(); elaborateContentModel(elt); } else if (e instanceof TextNotAllowedException) { TextNotAllowedException ex = (TextNotAllowedException) e; Name elt = ex.getCurrentElement(); elaborateContentModel(elt); } else if (e instanceof UnfinishedElementException) { UnfinishedElementException ex = (UnfinishedElementException) e; Name elt = ex.getCurrentElement(); elaborateContentModel(elt); } else if (e instanceof UnknownElementException) { UnknownElementException ex = (UnknownElementException) e; Name elt = ex.getParent(); elaborateContentModel(elt); } else if (e instanceof BadAttributeValueException) { BadAttributeValueException ex = (BadAttributeValueException) e; Map<String, DatatypeException> map = ex.getExceptions(); elaborateDatatypes(map); } else if (e instanceof StringNotAllowedException) { StringNotAllowedException ex = (StringNotAllowedException) e; Map<String, DatatypeException> map = ex.getExceptions(); elaborateDatatypes(map); } } private void elaborateDatatypes(Map<String, DatatypeException> map) throws SAXException { Set<DocumentFragment> fragments = new HashSet<DocumentFragment>(); for (Map.Entry<String, DatatypeException> entry : map.entrySet()) { DatatypeException ex = entry.getValue(); if (ex instanceof Html5DatatypeException) { Html5DatatypeException ex5 = (Html5DatatypeException) ex; DocumentFragment fragment = HTML5_DATATYPE_ADVICE.get(ex5.getDatatypeClass()); if (fragment != null) { fragments.add(fragment); } } } if (!fragments.isEmpty()) { ContentHandler ch = emitter.startElaboration(); if (ch != null) { TreeParser treeParser = new TreeParser(ch, null); XhtmlSaxEmitter xhtmlSaxEmitter = new XhtmlSaxEmitter(ch); xhtmlSaxEmitter.startElement("dl"); for (DocumentFragment fragment : fragments) { treeParser.parse(fragment); } xhtmlSaxEmitter.endElement("dl"); } emitter.endElaboration(); } } /** * @param elt * @throws SAXException */ private void elaborateContentModel(Name elt) throws SAXException { DocumentFragment dds = spec.contentModelDescription(elt); if (dds != null) { ContentHandler ch = emitter.startElaboration(); if (ch != null) { TreeParser treeParser = new TreeParser(ch, null); XhtmlSaxEmitter xhtmlSaxEmitter = new XhtmlSaxEmitter(ch); xhtmlSaxEmitter.startElement("dl"); emitContentModelDt(xhtmlSaxEmitter, elt); treeParser.parse(dds); xhtmlSaxEmitter.endElement("dl"); } emitter.endElaboration(); } } private void elaborateContentModelandContext(Name parent, Name child) throws SAXException { DocumentFragment contentModelDds = spec.contentModelDescription(parent); DocumentFragment contextDds = spec.contextDescription(child); if (contentModelDds != null || contextDds != null) { ContentHandler ch = emitter.startElaboration(); if (ch != null) { TreeParser treeParser = new TreeParser(ch, null); XhtmlSaxEmitter xhtmlSaxEmitter = new XhtmlSaxEmitter(ch); xhtmlSaxEmitter.startElement("dl"); if (contextDds != null) { emitContextDt(xhtmlSaxEmitter, child); treeParser.parse(contextDds); } if (contentModelDds != null) { emitContentModelDt(xhtmlSaxEmitter, parent); treeParser.parse(contentModelDds); } xhtmlSaxEmitter.endElement("dl"); } emitter.endElaboration(); } } /** * @param elt * @throws SAXException */ private void elaborateElementSpecificAttributes(Name elt) throws SAXException { DocumentFragment dds = spec.elementSpecificAttributesDescription(elt); if (dds != null) { ContentHandler ch = emitter.startElaboration(); if (ch != null) { TreeParser treeParser = new TreeParser(ch, null); XhtmlSaxEmitter xhtmlSaxEmitter = new XhtmlSaxEmitter(ch); xhtmlSaxEmitter.startElement("dl"); emitElementSpecificAttributesDt(xhtmlSaxEmitter, elt); treeParser.parse(dds); xhtmlSaxEmitter.endElement("dl"); } emitter.endElaboration(); } } private void emitElementSpecificAttributesDt(XhtmlSaxEmitter xhtmlSaxEmitter, Name elt) throws SAXException { xhtmlSaxEmitter.startElement("dt"); xhtmlSaxEmitter.characters(ELEMENT_SPECIFIC_ATTRIBUTES_BEFORE); emitLinkifiedLocalName(xhtmlSaxEmitter, elt); xhtmlSaxEmitter.characters(ELEMENT_SPECIFIC_ATTRIBUTES_AFTER); xhtmlSaxEmitter.endElement("dt"); } private void emitContextDt(XhtmlSaxEmitter xhtmlSaxEmitter, Name elt) throws SAXException { xhtmlSaxEmitter.startElement("dt"); xhtmlSaxEmitter.characters(CONTEXT_BEFORE); emitLinkifiedLocalName(xhtmlSaxEmitter, elt); xhtmlSaxEmitter.characters(CONTEXT_AFTER); xhtmlSaxEmitter.endElement("dt"); } private void emitContentModelDt( XhtmlSaxEmitter xhtmlSaxEmitter, Name elt) throws SAXException { xhtmlSaxEmitter.startElement("dt"); xhtmlSaxEmitter.characters(CONTENT_MODEL_BEFORE); emitLinkifiedLocalName(xhtmlSaxEmitter, elt); xhtmlSaxEmitter.characters(CONTENT_MODEL_AFTER); xhtmlSaxEmitter.endElement("dt"); } private void emitLinkifiedLocalName(XhtmlSaxEmitter xhtmlSaxEmitter, Name elt) throws SAXException { String url = spec.elementLink(elt); if (url != null) { attributesImpl.clear(); attributesImpl.addAttribute("href", url); xhtmlSaxEmitter.startElement("a", attributesImpl); } xhtmlSaxEmitter.startElement("code"); xhtmlSaxEmitter.characters(elt.getLocalName()); xhtmlSaxEmitter.endElement("code"); if (url != null) { xhtmlSaxEmitter.endElement("a"); } } private final class ExactErrorHandler implements ErrorHandler { private final MessageEmitterAdapter owner; /** * @param owner */ ExactErrorHandler(final MessageEmitterAdapter owner) { this.owner = owner; } public void error(SAXParseException exception) throws SAXException { owner.error(exception, true); } public void fatalError(SAXParseException exception) throws SAXException { owner.fatalError(exception, true); } public void warning(SAXParseException exception) throws SAXException { owner.warning(exception, true); } } /** * Returns the exactErrorHandler. * * @return the exactErrorHandler */ public ErrorHandler getExactErrorHandler() { return exactErrorHandler; } /** * Sets the spec. * * @param spec the spec to set */ public void setSpec(Spec spec) { this.spec = spec; } /** * Sets the html. * * @param html the html to set */ public void setHtml(boolean html) { this.html = html; } public void setLoggingOk(boolean ok) { this.loggingOk = ok; } /** * Sets the errorsOnly. * * @param errorsOnly the errorsOnly to set */ public void setErrorsOnly(boolean errorsOnly) { this.errorsOnly = errorsOnly; } /** * @throws SAXException * @see nu.validator.messages.MessageEmitter#endMessage() */ public void endMessage() throws SAXException { emitter.endMessage(); } /** * @param type * @param systemId * @param oneBasedFirstLine * @param oneBasedFirstColumn * @param oneBasedLastLine * @param oneBasedLastColumn * @param exact * @throws SAXException * @see nu.validator.messages.MessageEmitter#startMessage(nu.validator.messages.types.MessageType, java.lang.String, int, int, int, int, boolean) */ public void startMessage(MessageType type, String systemId, int oneBasedFirstLine, int oneBasedFirstColumn, int oneBasedLastLine, int oneBasedLastColumn, boolean exact) throws SAXException { emitter.startMessage(type, systemId, (oneBasedFirstLine == -1) ? -1 : oneBasedFirstLine + lineOffset, oneBasedFirstColumn, (oneBasedLastLine == -1) ? -1 : oneBasedLastLine + lineOffset, oneBasedLastColumn, exact); } }
package org.adligo.models.core.client; import org.adligo.i.util.client.ClassUtils; import org.adligo.models.core.client.ids.I_StorageIdentifier; public class NamedIdMutant implements I_NamedIdMutant, I_Validateable { public static final String NULL_TO_CONSTRUCTOR = "a null was passed to the NamedIdMutant constructor "; private static final long serialVersionUID = 1L; public static final String SET_NAME = "setName"; private I_StorageIdentifier id; private String name; public NamedIdMutant() { } public NamedIdMutant(I_NamedId other) throws InvalidParameterException { I_StorageIdentifier id = other.getId(); if (id != null) { //allow a null id in the constructor, for objects that haven't been saved yet // and use this as the standard setId(other.getId()); } setName(other.getName()); } public I_StorageIdentifier getId() { return id; } /** * allow sub class to throw exception if necessary * * @param p_id * @throws InvalidParameterException */ public void setId(I_StorageIdentifier p_id) throws InvalidParameterException { if (p_id == null) { throw new InvalidParameterException(ModelsCoreConstantsObtainer.getConstants() .getStorageIdRequired(),SET_ID); } id = p_id; } public String getName() { return name; } /** * note no checks are done here because * the client classes (DomainName, Email exc) * will want to provide specific messages for nulls and empties * * @param p_name * @throws InvalidParameterException */ public void setName(String p_name) { name = p_name; } public String toString() { return toString(this.getClass(), id); } protected String toString(Class c, I_StorageIdentifier p_id) { StringBuffer sb = new StringBuffer(); sb.append(ClassUtils.getClassShortName(c)); sb.append(" [name="); sb.append(name); sb.append(",id="); sb.append(p_id); sb.append("]"); return sb.toString(); } public boolean isValid() throws ValidationException { // TODO Auto-generated method stub return false; } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; I_NamedId other = (I_NamedId) obj; if (id == null) { if (other.getId() != null) return false; } else if (!id.equals(other.getId())) return false; if (name == null) { if (other.getName() != null) return false; } else if (!name.equals(other.getName())) return false; return true; } }
package org.biojava.bio.alignment; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import org.biojava.bio.BioException; import org.biojava.bio.seq.Sequence; import org.biojava.bio.seq.SequenceIterator; import org.biojava.bio.seq.db.SequenceDB; import org.biojava.bio.symbol.Alignment; /** This Interface provides methods for the alignment of biosequences. * * @author Andreas Dr&auml;ger * */ public abstract class SequenceAlignment { /** * @return a string representation of the alignment * @throws BioException */ public abstract String getAlignmentString() throws Exception; /** * @param source a SequenceIterator containing a set of sequences to be aligned with * @param subjectDB the SequenceDB containing another set of sequences. * @return a list containing the results of all single alignments performed by this * method. * @throws NoSuchElementException * @throws Exception */ public abstract List alignAll(SequenceIterator source, SequenceDB subjectDB) throws Exception; /** Performs a pairwise sequence alignment of the two given sequences. * @param query * @param subject * @return score of the alignment or the distance. * @throws Exception */ public abstract double pairwiseAlignment(Sequence query, Sequence subject) throws Exception; /** This method also performs a sequence alignment of the two given sequences but it * returns an Alignment object instead of the score. * @param query * @param subject * @return Alignment */ public abstract Alignment getAlignment(Sequence query, Sequence subject) throws Exception; /** This method provides a BLAST-like formated alignment from the given <code>String</code>s, * in which the sequence coordinates and the information "Query" or "Target", respectively * is added to each line. * Each line contains 60 sequence characters including the gap symbols plus the meta information. * There is one white line between two pairs of sequences. * * @param queryName name of the query sequence * @param targetName name of the target sequence * @param align a <code>String</code>-array, where the index 0 is the query sequence and index 1 * the target sequence (for instance * <code>new String[] {myQuerySequence.seqString(), myTargetSequence.seqString()}</code>) * @param path the "path", that means a String containing white spaces and pipe ("|") symbols, * which makes matches visible. The two strings in <code>align</code> have to have the * same length and also the same length than this <code>path</code>. * @param queryStart the start position in the query, where the alignment starts. For example zero * for normal Needleman-Wunsch-Alignments. * @param queryEnd the end position, that means the sequence coordinate, which is the last symbol of * the query sequence. Counting starts at zero! * @param queryLength The length of the query sequence without gaps. * @param targetStart These are all the same for the target. Have a look at these above. * @param targetEnd * @param targetLength * @param editdistance * @param time The time in milliseconds, which was needed to generate the alignment. * @return formatierten String. */ public static String formatOutput(String queryName, String targetName, String[] align, String path, int queryStart, int queryEnd, long queryLength, int targetStart, int targetEnd, long targetLength, double editdistance, long time) { String output = "\n Time (ms):\t"+time+"\n Length:\t"+align[0].length()+"\n"; output += " Score:\t" +(-1)*editdistance+"\n"; output += " Query:\t" + queryName + ",\tLength:\t"+ queryLength +"\n"; output += " Target:\t" + targetName + ",\tLength:\t"+ targetLength +"\n\n"; int currline = Math.min(60, align[0].length()), i, j, k, l; // counts the absolute position within the String String space = " ", kspace = "", jspace = ""; for (k=0; k< new Integer(Math.max(queryEnd, targetEnd)).toString().length(); k++) space += " "; for (k=new Integer(queryStart+1).toString().length(); k<= new Integer(Math.max(queryEnd, targetEnd)).toString().length(); k++) kspace += " "; for (k= new Integer(targetStart+1).toString().length(); k<= new Integer(Math.max(queryEnd, targetEnd)).toString().length(); k++) jspace += " "; i = k = queryStart; j = l = targetStart; output += "\nQuery:\t" + kspace + (k+1) + " "; for (i=currline-Math.min(60, align[0].length()); i<currline; i++) { if ((align[0].charAt(i) != '-') && (align[0].charAt(i) != '~')) k++; if ((align[1].charAt(i) != '-') && (align[1].charAt(i) != '~')) j++; } output += align[0].substring(0, currline) + " " + k; output += " \n\t" + space + path.substring(0, currline); output += " \nTarget:\t" + jspace + (l+1) + " " + align[1].substring(0, currline) + " " + j + " \n"; for (; currline+60 < path.length(); currline+=60) { l = Math.min(j+1, targetEnd); kspace = jspace = ""; for (int n= new Integer(k+1).toString().length()-1; n< new Integer(Math.max(queryEnd, targetEnd)).toString().length(); n++) kspace += " "; for (int n= new Integer(j).toString().length()-1; n< new Integer(Math.max(queryEnd, targetEnd)).toString().length(); n++) jspace += " "; output += " \nQuery:\t" + kspace + Math.min(k+1, queryEnd) + " "; for (i=currline; i<currline+60; i++) { if ((align[0].charAt(i) != '-') && (align[0].charAt(i) != '~')) k++; if ((align[1].charAt(i) != '-') && (align[1].charAt(i) != '~')) j++; } output += align[0].substring(currline, currline+60) + " " + k; output += " \n\t" + space + path.substring(currline, currline+60); output += " \nTarget:\t" + jspace + l + " " + align[1].substring(currline, currline+60) + " " + j + " \n"; } align[0] += " " + queryEnd; align[1] += " " + targetEnd; if (currline+1 < path.length()) { kspace = jspace = ""; for (int n= new Integer(k).toString().length()-1; n< new Integer(Math.max(queryEnd, targetEnd)).toString().length(); n++) kspace += " "; for (int n= new Integer(j).toString().length()-1; n< new Integer(Math.max(queryEnd, targetEnd)).toString().length(); n++) jspace += " "; output += " \nQuery:\t" + kspace + Math.min(k+1, queryEnd) + " " + align[0].substring(currline, align[0].length()); output += " \n\t" + space + path.substring(currline, path.length()); output += " \nTarget:\t"+ jspace + Math.min(j+1, targetEnd) + " " + align[1].substring(currline, align[1].length())+"\n"; } return output += "\n"; } }
package org.bouncycastle.jce.examples; import java.io.FileOutputStream; import java.math.BigInteger; import java.security.KeyFactory; import java.security.KeyStore; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Security; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.security.spec.RSAPrivateCrtKeySpec; import java.security.spec.RSAPublicKeySpec; import java.util.Date; import java.util.Hashtable; import java.util.Vector; import org.bouncycastle.asn1.DERBMPString; import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers; import org.bouncycastle.asn1.x509.BasicConstraints; import org.bouncycastle.asn1.x509.X509Extensions; import org.bouncycastle.jce.PrincipalUtil; import org.bouncycastle.jce.X509Principal; import org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.x509.X509V1CertificateGenerator; import org.bouncycastle.x509.X509V3CertificateGenerator; import org.bouncycastle.x509.extension.AuthorityKeyIdentifierStructure; import org.bouncycastle.x509.extension.SubjectKeyIdentifierStructure; /** * Example of how to set up a certificiate chain and a PKCS 12 store for * a private individual - obviously you'll need to generate your own keys, * and you may need to add a NetscapeCertType extension or add a key * usage extension depending on your application, but you should get the * idea! As always this is just an example... */ public class PKCS12Example { static char[] passwd = { 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd' }; static X509V1CertificateGenerator v1CertGen = new X509V1CertificateGenerator(); static X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator(); /** * we generate the CA's certificate */ public static Certificate createMasterCert( PublicKey pubKey, PrivateKey privKey) throws Exception { // signers name String issuer = "C=AU, O=The Legion of the Bouncy Castle, OU=Bouncy Primary Certificate"; // subjects name - the same as we are self signed. String subject = "C=AU, O=The Legion of the Bouncy Castle, OU=Bouncy Primary Certificate"; // create the certificate - version 1 v1CertGen.setSerialNumber(BigInteger.valueOf(1)); v1CertGen.setIssuerDN(new X509Principal(issuer)); v1CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30)); v1CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30))); v1CertGen.setSubjectDN(new X509Principal(subject)); v1CertGen.setPublicKey(pubKey); v1CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); X509Certificate cert = v1CertGen.generateX509Certificate(privKey); cert.checkValidity(new Date()); cert.verify(pubKey); PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)cert; // this is actually optional - but if you want to have control // over setting the friendly name this is the way to do it... bagAttr.setBagAttribute( PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Bouncy Primary Certificate")); return cert; } /** * we generate an intermediate certificate signed by our CA */ public static Certificate createIntermediateCert( PublicKey pubKey, PrivateKey caPrivKey, X509Certificate caCert) throws Exception { // subject name table. Hashtable attrs = new Hashtable(); Vector order = new Vector(); attrs.put(X509Principal.C, "AU"); attrs.put(X509Principal.O, "The Legion of the Bouncy Castle"); attrs.put(X509Principal.OU, "Bouncy Intermediate Certificate"); attrs.put(X509Principal.EmailAddress, "feedback-crypto@bouncycastle.org"); order.addElement(X509Principal.C); order.addElement(X509Principal.O); order.addElement(X509Principal.OU); order.addElement(X509Principal.EmailAddress); // create the certificate - version 3 v3CertGen.reset(); v3CertGen.setSerialNumber(BigInteger.valueOf(2)); v3CertGen.setIssuerDN(PrincipalUtil.getSubjectX509Principal(caCert)); v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30)); v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30))); v3CertGen.setSubjectDN(new X509Principal(order, attrs)); v3CertGen.setPublicKey(pubKey); v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); // extensions v3CertGen.addExtension( X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey)); v3CertGen.addExtension( X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); v3CertGen.addExtension( X509Extensions.BasicConstraints, true, new BasicConstraints(0)); X509Certificate cert = v3CertGen.generateX509Certificate(caPrivKey); cert.checkValidity(new Date()); cert.verify(caCert.getPublicKey()); PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)cert; // this is actually optional - but if you want to have control // over setting the friendly name this is the way to do it... bagAttr.setBagAttribute( PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Bouncy Intermediate Certificate")); return cert; } /** * we generate a certificate signed by our CA's intermediate certficate */ public static Certificate createCert( PublicKey pubKey, PrivateKey caPrivKey, PublicKey caPubKey) throws Exception { // signers name table. Hashtable sAttrs = new Hashtable(); Vector sOrder = new Vector(); sAttrs.put(X509Principal.C, "AU"); sAttrs.put(X509Principal.O, "The Legion of the Bouncy Castle"); sAttrs.put(X509Principal.OU, "Bouncy Intermediate Certificate"); sAttrs.put(X509Principal.EmailAddress, "feedback-crypto@bouncycastle.org"); sOrder.addElement(X509Principal.C); sOrder.addElement(X509Principal.O); sOrder.addElement(X509Principal.OU); sOrder.addElement(X509Principal.EmailAddress); // subjects name table. Hashtable attrs = new Hashtable(); Vector order = new Vector(); attrs.put(X509Principal.C, "AU"); attrs.put(X509Principal.O, "The Legion of the Bouncy Castle"); attrs.put(X509Principal.L, "Melbourne"); attrs.put(X509Principal.CN, "Eric H. Echidna"); attrs.put(X509Principal.EmailAddress, "feedback-crypto@bouncycastle.org"); order.addElement(X509Principal.C); order.addElement(X509Principal.O); order.addElement(X509Principal.L); order.addElement(X509Principal.CN); order.addElement(X509Principal.EmailAddress); // create the certificate - version 3 v3CertGen.reset(); v3CertGen.setSerialNumber(BigInteger.valueOf(3)); v3CertGen.setIssuerDN(new X509Principal(sOrder, sAttrs)); v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30)); v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30))); v3CertGen.setSubjectDN(new X509Principal(order, attrs)); v3CertGen.setPublicKey(pubKey); v3CertGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); // add the extensions v3CertGen.addExtension( X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(pubKey)); v3CertGen.addExtension( X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caPubKey)); X509Certificate cert = v3CertGen.generateX509Certificate(caPrivKey); cert.checkValidity(new Date()); cert.verify(caPubKey); PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)cert; // this is also optional - in the sense that if you leave this // out the keystore will add it automatically, note though that // for the browser to recognise the associated private key this // you should at least use the pkcs_9_localKeyId OID and set it // to the same as you do for the private key's localKeyId. bagAttr.setBagAttribute( PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Eric's Key")); bagAttr.setBagAttribute( PKCSObjectIdentifiers.pkcs_9_at_localKeyId, new SubjectKeyIdentifierStructure(pubKey)); return cert; } public static void main( String[] args) throws Exception { Security.addProvider(new BouncyCastleProvider()); // personal keys RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16)); RSAPrivateCrtKeySpec privKeySpec = new RSAPrivateCrtKeySpec( new BigInteger("b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7", 16), new BigInteger("11", 16), new BigInteger("9f66f6b05410cd503b2709e88115d55daced94d1a34d4e32bf824d0dde6028ae79c5f07b580f5dce240d7111f7ddb130a7945cd7d957d1920994da389f490c89", 16), new BigInteger("c0a0758cdf14256f78d4708c86becdead1b50ad4ad6c5c703e2168fbf37884cb", 16), new BigInteger("f01734d7960ea60070f1b06f2bb81bfac48ff192ae18451d5e56c734a5aab8a5", 16), new BigInteger("b54bb9edff22051d9ee60f9351a48591b6500a319429c069a3e335a1d6171391", 16), new BigInteger("d3d83daf2a0cecd3367ae6f8ae1aeb82e9ac2f816c6fc483533d8297dd7884cd", 16), new BigInteger("b8f52fc6f38593dabb661d3f50f8897f8106eee68b1bce78a95b132b4e5b5d19", 16)); // intermediate keys. RSAPublicKeySpec intPubKeySpec = new RSAPublicKeySpec( new BigInteger("8de0d113c5e736969c8d2b047a243f8fe18edad64cde9e842d3669230ca486f7cfdde1f8eec54d1905fff04acc85e61093e180cadc6cea407f193d44bb0e9449b8dbb49784cd9e36260c39e06a947299978c6ed8300724e887198cfede20f3fbde658fa2bd078be946a392bd349f2b49c486e20c405588e306706c9017308e69", 16), new BigInteger("ffff", 16)); RSAPrivateCrtKeySpec intPrivKeySpec = new RSAPrivateCrtKeySpec( new BigInteger("8de0d113c5e736969c8d2b047a243f8fe18edad64cde9e842d3669230ca486f7cfdde1f8eec54d1905fff04acc85e61093e180cadc6cea407f193d44bb0e9449b8dbb49784cd9e36260c39e06a947299978c6ed8300724e887198cfede20f3fbde658fa2bd078be946a392bd349f2b49c486e20c405588e306706c9017308e69", 16), new BigInteger("ffff", 16), new BigInteger("7deb1b194a85bcfd29cf871411468adbc987650903e3bacc8338c449ca7b32efd39ffc33bc84412fcd7df18d23ce9d7c25ea910b1ae9985373e0273b4dca7f2e0db3b7314056ac67fd277f8f89cf2fd73c34c6ca69f9ba477143d2b0e2445548aa0b4a8473095182631da46844c356f5e5c7522eb54b5a33f11d730ead9c0cff", 16), new BigInteger("ef4cede573cea47f83699b814de4302edb60eefe426c52e17bd7870ec7c6b7a24fe55282ebb73775f369157726fcfb988def2b40350bdca9e5b418340288f649", 16), new BigInteger("97c7737d1b9a0088c3c7b528539247fd2a1593e7e01cef18848755be82f4a45aa093276cb0cbf118cb41117540a78f3fc471ba5d69f0042274defc9161265721", 16), new BigInteger("6c641094e24d172728b8da3c2777e69adfd0839085be7e38c7c4a2dd00b1ae969f2ec9d23e7e37090fcd449a40af0ed463fe1c612d6810d6b4f58b7bfa31eb5f", 16), new BigInteger("70b7123e8e69dfa76feb1236d0a686144b00e9232ed52b73847e74ef3af71fb45ccb24261f40d27f98101e230cf27b977a5d5f1f15f6cf48d5cb1da2a3a3b87f", 16), new BigInteger("e38f5750d97e270996a286df2e653fd26c242106436f5bab0f4c7a9e654ce02665d5a281f2c412456f2d1fa26586ef04a9adac9004ca7f913162cb28e13bf40d", 16)); // ca keys RSAPublicKeySpec caPubKeySpec = new RSAPublicKeySpec( new BigInteger("b259d2d6e627a768c94be36164c2d9fc79d97aab9253140e5bf17751197731d6f7540d2509e7b9ffee0a70a6e26d56e92d2edd7f85aba85600b69089f35f6bdbf3c298e05842535d9f064e6b0391cb7d306e0a2d20c4dfb4e7b49a9640bdea26c10ad69c3f05007ce2513cee44cfe01998e62b6c3637d3fc0391079b26ee36d5", 16), new BigInteger("11", 16)); RSAPrivateCrtKeySpec caPrivKeySpec = new RSAPrivateCrtKeySpec( new BigInteger("b259d2d6e627a768c94be36164c2d9fc79d97aab9253140e5bf17751197731d6f7540d2509e7b9ffee0a70a6e26d56e92d2edd7f85aba85600b69089f35f6bdbf3c298e05842535d9f064e6b0391cb7d306e0a2d20c4dfb4e7b49a9640bdea26c10ad69c3f05007ce2513cee44cfe01998e62b6c3637d3fc0391079b26ee36d5", 16), new BigInteger("11", 16), new BigInteger("92e08f83cc9920746989ca5034dcb384a094fb9c5a6288fcc4304424ab8f56388f72652d8fafc65a4b9020896f2cde297080f2a540e7b7ce5af0b3446e1258d1dd7f245cf54124b4c6e17da21b90a0ebd22605e6f45c9f136d7a13eaac1c0f7487de8bd6d924972408ebb58af71e76fd7b012a8d0e165f3ae2e5077a8648e619", 16), new BigInteger("f75e80839b9b9379f1cf1128f321639757dba514642c206bbbd99f9a4846208b3e93fbbe5e0527cc59b1d4b929d9555853004c7c8b30ee6a213c3d1bb7415d03", 16), new BigInteger("b892d9ebdbfc37e397256dd8a5d3123534d1f03726284743ddc6be3a709edb696fc40c7d902ed804c6eee730eee3d5b20bf6bd8d87a296813c87d3b3cc9d7947", 16), new BigInteger("1d1a2d3ca8e52068b3094d501c9a842fec37f54db16e9a67070a8b3f53cc03d4257ad252a1a640eadd603724d7bf3737914b544ae332eedf4f34436cac25ceb5", 16), new BigInteger("6c929e4e81672fef49d9c825163fec97c4b7ba7acb26c0824638ac22605d7201c94625770984f78a56e6e25904fe7db407099cad9b14588841b94f5ab498dded", 16), new BigInteger("dae7651ee69ad1d081ec5e7188ae126f6004ff39556bde90e0b870962fa7b926d070686d8244fe5a9aa709a95686a104614834b0ada4b10f53197a5cb4c97339", 16)); // set up the keys KeyFactory fact = KeyFactory.getInstance("RSA", "BC"); PrivateKey caPrivKey = fact.generatePrivate(caPrivKeySpec); PublicKey caPubKey = fact.generatePublic(caPubKeySpec); PrivateKey intPrivKey = fact.generatePrivate(intPrivKeySpec); PublicKey intPubKey = fact.generatePublic(intPubKeySpec); PrivateKey privKey = fact.generatePrivate(privKeySpec); PublicKey pubKey = fact.generatePublic(pubKeySpec); Certificate[] chain = new Certificate[3]; chain[2] = createMasterCert(caPubKey, caPrivKey); chain[1] = createIntermediateCert(intPubKey, caPrivKey, (X509Certificate)chain[2]); chain[0] = createCert(pubKey, intPrivKey, intPubKey); // add the friendly name for the private key PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier)privKey; // this is also optional - in the sense that if you leave this // out the keystore will add it automatically, note though that // for the browser to recognise which certificate the private key // is associated with you should at least use the pkcs_9_localKeyId // OID and set it to the same as you do for the private key's // corresponding certificate. bagAttr.setBagAttribute( PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString("Eric's Key")); bagAttr.setBagAttribute( PKCSObjectIdentifiers.pkcs_9_at_localKeyId, new SubjectKeyIdentifierStructure(pubKey)); // store the key and the certificate chain KeyStore store = KeyStore.getInstance("PKCS12", "BC"); store.load(null, null); // if you haven't set the friendly name and local key id above // the name below will be the name of the key store.setKeyEntry("Eric's Key", privKey, null, chain); FileOutputStream fOut = new FileOutputStream("id.p12"); store.store(fOut, passwd); fOut.close(); } }
package org.clapper.util.cmdline; import org.clapper.util.io.WordWrapWriter; import org.clapper.util.misc.Logger; import org.clapper.util.misc.ArrayIterator; import java.util.Iterator; import java.util.NoSuchElementException; /** * <p><tt>CommandLineUtility</tt> is an abstract base class for * command-line utilities. It provides:</p> * * <ul> * <li>Parameter-parsing logic, with call-outs for custom parameters * <li>Built-in support a --logging parameter, which enables logging * via the Jakarta Commons Logging API, by calling * {@link org.clapper.util.misc.Logger#enableLogging()} * <li>Automatic generation of a usage message, with a call-out that * permits subclasses to add subclass-specific usage information. * <li>Automatic reporting of exceptions * </ul> * * To use this class, subclass it, and have the subclass's <tt>main()</tt> * method instantiate the subclass, and then call the resulting object's * {@link #execute(String[])} * method. The <tt>execute()</tt> method (which resides in this base class) * will:</p> * * <ul> * <li>parse the parameters * <li>call the {@link #runCommand()} method, which must be provided by * the subclass, to initiate processing. * </ul> * * <p>Here's a sample subclass. It takes the usual -logging parameter, plus * a "-v" (verbose) flag, a numeric count ("-n") and a file name. (Exactly * what it does with those parameters is left as an exercise for the * reader.)</p> * * <blockquote> * <pre> * public class Foo extends CommandLineUtility * { * private boolean verbose = false; * private int count = 1; * private String filename = null; * * public static void main (String args[]) * { * try * { * Foo foo = new Foo(); * foo.execute (args); * } * * catch (CommandLineUsageException ex) * { * // Already reported * * System.exit (1); * } * * catch (CommandLineException ex) * { * System.err.println (ex.getMessage()); * System.exit (1); * } * * System.exit (0); * } * * private Foo() * { * super(); * } * * protected void runCommand() throws CommandLineUtilityException * { * ... * } * * protected void parseCustomOption (String option, Iterator it) * throws CommandLineUtilityException, * NoSuchElementException * { * if (option.equals ("-v") || option.equals ("--verbose")) * verbose = true; * * else if (option.equals ("-n") || option.equals ("--count")) * { * String arg = (String) it.next(); * try * { * count = Integer.parseInt (arg); * } * * catch (NumberFormatException ex) * { * throw new CommandLineException ("Non-numeric parameter \"" + arg "\" to -n option"); * } * } * * else * throw new BadCommandLineException ("Unknown option: " + option); * } * * protected void processPostOptionCommandLine (Iterator it) * throws BadCommandLineException, * NoSuchElementException * { * filename = (String) it.next(); * } * * protected void getCustomUsageInfo (UsageInfo info) * { * info.addOption ("-v, --verbose", "Enable verbose messages"); * info.addOption ("-n count", "Read specified file <count> times. Defaults to 1."); * info.addOption ("--count count", "Synonym for -n option."); * info.addParameter ("filename", "File to process.", false); * } * } * </pre> * </blockquote> * * @version <tt>$Revision$</tt> */ public abstract class CommandLineUtility { /** * Maximum length of option string (see usage()) that can be concatenated * with first line of option's explanation. Strings longer than this are * printed on a line by themselves. */ private static final int MAX_OPTION_STRING_LENGTH = 35; private static Logger log = new Logger (CommandLineUtility.class); private UsageInfo usageInfo = null; /** * Constructor. Initializes this base class. */ protected CommandLineUtility() { } /** * Called to initiate execution of the command line utility. This * method * * <ul> * <li>parse the parameters * <li>call the {@link #runCommand()} method, which must be provided by * the subclass, to initiate processing. * </ul> * * @param args The command-line parameters * * @throws CommandLineUtilityException command failed */ public final void execute (String[] args) throws CommandLineException { boolean ok = true; try { usageInfo = getUsageInfo(); parseParams (args); runCommand(); } catch (CommandLineUsageException ex) { usage (ex.getMessage()); throw ex; } catch (CommandLineException ex) { throw ex; } catch (Exception ex) { throw new CommandLineException (ex); } } /** * Parse the command-line parameters. This method parses the common * options; any other option is passed to the * <tt>parseCustomOption()</tt> method, which should throw an exception * if the option isn't recognized. When the options have all been * satisfied, this method then invokes * <tt>processPostOptionCommandLine()</tt>. * * @param args the command line parameters * * @throws CommandLineUsageException command line error * * @see #processPostOptionCommandLine * @see #parseCustomOption */ protected final void parseParams (String args[]) throws CommandLineUsageException { ArrayIterator it = new ArrayIterator (args); try { while (it.hasNext()) { String arg = (String) it.next(); if (! (arg.charAt (0) == UsageInfo.SHORT_OPTION_PREFIX) ) { // Move iterator back, since we've already advanced // past the last option and retrieved the first // non-option. it.previous(); break; } OptionInfo optionInfo = null; if (arg.length() == 2) optionInfo = usageInfo.getOptionInfo (arg.charAt (1)); else { if (! arg.startsWith (UsageInfo.LONG_OPTION_PREFIX)) { throw new CommandLineUsageException ("Option \"" + arg + "\" is not a single character short option, but " + "doesn't start with \"" + UsageInfo.LONG_OPTION_PREFIX + "\", as long options must."); } optionInfo = usageInfo.getOptionInfo (arg.substring (2)); } if (optionInfo == null) { throw new CommandLineUsageException ("Unknown option: \"" + arg + "\"."); } // Okay, now handle our options. if (optionInfo.longOption.equals ("logging")) Logger.enableLogging(); else { parseCustomOption (optionInfo.shortOption, optionInfo.longOption, it); } } processPostOptionCommandLine (it); // Should be no parameters left now. if (it.hasNext()) throw new CommandLineUsageException ("Too many parameters."); } catch (NoSuchElementException ex) { throw new CommandLineUsageException ("Missing parameter(s)"); } catch (ArrayIndexOutOfBoundsException ex) { throw new CommandLineUsageException ("Missing parameter(s)"); } } /** * Called by <tt>parseParams()</tt> to handle any option it doesn't * recognize. If the option takes any parameters, the overridden * method must extract the parameter by advancing the supplied * <tt>Iterator</tt> (which returns <tt>String</tt> objects). This * default method simply throws an exception. * * @param shortOption the short option character, or * {@link UsageInfo#NO_SHORT_OPTION} if there isn't * one (i.e., if this is a long-only option). * @param longOption the long option string, without any leading * "-" characters, or null if this is a short-only * option * @param it the <tt>Iterator</tt> for the remainder of the * command line, for extracting parameters. * * @throws CommandLineUsageException on error * @throws NoSuchElementException overran the iterator (i.e., missing * parameter) */ protected void parseCustomOption (char shortOption, String longOption, Iterator it) throws CommandLineUsageException, NoSuchElementException { throw new CommandLineUsageException ("(BUG) custom option found, but " + this.getClass().getName() + " class provides no " + "parseCustomOption() method."); } /** * <p>Called by <tt>parseParams()</tt> once option parsing is complete, * this method must handle any additional parameters on the command * line. It's not necessary for the method to ensure that the iterator * has the right number of strings left in it. If you attempt to pull * too many parameters from the iterator, it'll throw a * <tt>NoSuchElementException</tt>, which <tt>parseParams()</tt> traps * and converts into a suitable error message. Similarly, if there are * any parameters left in the iterator when this method returns, * <tt>parseParams()</tt> throws an exception indicating that there are * too many parameters on the command line.</p> * * <p>This method is called unconditionally, even if there are no * parameters left on the command line, so it's a useful place to do * post-option consistency checks, as well.</p> * * @param it the <tt>Iterator</tt> for the remainder of the * command line * * @throws CommandLineUsageException on error * @throws NoSuchElementException attempt to iterate past end of args; * <tt>parseParams()</tt> automatically * handles this exception, so it's * safe for subclass implementations of * this method not to handle it */ protected void processPostOptionCommandLine (Iterator it) throws CommandLineUsageException, NoSuchElementException { throw new CommandLineUsageException ("Extra command line parameter(s)"); } /** * Called by <tt>parseParams()</tt> to get the custom command-line * options and parameters handled by the subclass. This list is used * solely to build a usage message. The overridden method must fill the * supplied <tt>UsageInfo</tt> object: * * <ul> * <li> Each parameter must be added to the object, via the * <tt>UsageInfo.addParameter()</tt> method. The first argument * to <tt>addParameter()</tt> is the parameter string (e.g., * "<dbCfg>" or "input_file"). The second parameter is the * one-line description. The description may be of any length, * but it should be a single line. * * <li> Each option must be added to the object, via the * <tt>UsageInfo.addOption()</tt> method. The first argument to * <tt>addOption()</tt> is the option string (e.g., "-x" or * "-version"). The second parameter is the one-line * description. The description may be of any length, but it * should be a single line. * </ul> * * That information will be combined with the common options supported * by the base class, and used to build a usage message. * * @param info The <tt>UsageInfo</tt> object to fill. */ protected void getCustomUsageInfo (UsageInfo info) { } /** * Actually runs the command. All subclasses are required to provide this * method. * * @throws CommandLineException on error */ protected abstract void runCommand() throws CommandLineException; /** * Print a usage message. * * @param prefixMsg a prefix message to display before dumping the * usage, or null */ protected final void usage (String prefixMsg) { WordWrapWriter out = new WordWrapWriter (System.err); String[] strings; Iterator it; int i; int maxParamLength = 0; int maxOptionLength = 0; String s; StringBuffer usageLine = new StringBuffer(); OptionInfo[] options; OptionInfo opt; if (prefixMsg != null) { out.println(); out.println (prefixMsg); out.println(); } // Now, print the summary line. usageLine.append ("java "); usageLine.append (getClass().getName()); usageLine.append (" [options]"); // Add the parameter placeholders. We'll also calculate the maximum // parameter name length in this loop, to save an iteration later. strings = usageInfo.getParameterNames(); if (strings.length > 0) { for (i = 0; i < strings.length; i++) { usageLine.append (' '); boolean optional = true; if (usageInfo.parameterIsRequired (strings[i])) optional = false; if (optional) usageLine.append ('['); usageLine.append (strings[i]); if (optional) usageLine.append (']'); maxParamLength = Math.max (maxParamLength, strings[i].length() + 1); } } if ( (s = usageInfo.getUsagePrologue()) != null) out.println (s); out.setPrefix ("Usage: "); out.println (usageLine.toString()); out.setPrefix (null); out.println (); // Find the largest option name. out.println ("OPTIONS:"); out.println (); maxOptionLength = 2; options = usageInfo.getOptions(); for (i = 0; i < options.length; i++) { opt = options[i]; if (opt.longOption != null) { // Allow room for short option, long option and argument, // if any. // -x, --long-x <arg> int len = 0; String sep = ""; if (opt.shortOption != UsageInfo.NO_SHORT_OPTION) { len = 2; sep = ", "; } if (opt.longOption != null) { len += (sep.length() + UsageInfo.LONG_OPTION_PREFIX.length() + opt.longOption.length()); } if (opt.argToken != null) len += (opt.argToken.length() + 1); maxOptionLength = Math.max (maxOptionLength, len + 1); } } if (maxOptionLength > MAX_OPTION_STRING_LENGTH) maxOptionLength = MAX_OPTION_STRING_LENGTH; // Now, print the options. StringBuffer optString = new StringBuffer(); for (i = 0; i < options.length; i++) { // If there's a short option, print it first. Then do the // long one. opt = options[i]; optString.setLength (0); String sep = ""; if (opt.shortOption != UsageInfo.NO_SHORT_OPTION) { optString.append (UsageInfo.SHORT_OPTION_PREFIX); optString.append (opt.shortOption); sep = ", "; } if (opt.longOption != null) { optString.append (sep); optString.append (UsageInfo.LONG_OPTION_PREFIX); optString.append (opt.longOption); } if (opt.argToken != null) { optString.append (' '); optString.append (opt.argToken); } s = optString.toString(); if (s.length() > maxOptionLength) { out.println (s); out.setPrefix (padString (" ", maxOptionLength)); } else { out.setPrefix (padString (optString.toString(), maxOptionLength)); } out.println (opt.explanation); out.setPrefix (null); } // Print the parameters. We already have size of the the largest // parameter name. strings = usageInfo.getParameterNames(); if (strings.length > 0) { out.println (); out.println ("PARAMETERS:"); out.println (); // Now, print the parameters. for (i = 0; i < strings.length; i++) { out.setPrefix (padString (strings[i], maxOptionLength)); out.println (usageInfo.getParameterExplanation (strings[i])); out.setPrefix (null); } } if ( (s = usageInfo.getUsageTrailer()) != null) out.println (s); out.flush(); } private String padString (String s, int toLength) { StringBuffer buf = new StringBuffer (s); while (buf.length() < toLength) buf.append (' '); return buf.toString(); } private UsageInfo getUsageInfo() { UsageInfo info = new UsageInfo(); getCustomUsageInfo (info); info.addOption (UsageInfo.NO_SHORT_OPTION, "logging", "Enable logging via Jakarta Commons Logging API."); return info; } }
package org.helioviewer.jhv.view.uri.fits; import java.net.URI; import java.nio.ByteBuffer; import java.nio.ShortBuffer; import javax.annotation.Nullable; import nom.tam.fits.BasicHDU; import nom.tam.fits.Fits; import nom.tam.fits.Header; import nom.tam.fits.HeaderCard; import nom.tam.fits.ImageHDU; import nom.tam.image.compression.hdu.CompressedImageHDU; import nom.tam.util.Cursor; import org.helioviewer.jhv.imagedata.ImageBuffer; import org.helioviewer.jhv.io.NetClient; import org.helioviewer.jhv.math.MathUtils; import org.helioviewer.jhv.log.Log; import org.helioviewer.jhv.view.uri.URIImageReader; // essentially static; local or network cache public class FITSImage implements URIImageReader { @Nullable @Override public String readXML(URI uri) throws Exception { try (NetClient nc = NetClient.of(uri); Fits f = new Fits(nc.getStream())) { BasicHDU<?>[] hdus = f.read(); // this is cumbersome for (BasicHDU<?> hdu : hdus) { if (hdu instanceof CompressedImageHDU) { return readHeader(((CompressedImageHDU) hdu).asImageHDU()); } } for (BasicHDU<?> hdu : hdus) { if (hdu instanceof ImageHDU) { return readHeader((ImageHDU) hdu); } } } throw new Exception("No image found"); } @Nullable @Override public ImageBuffer readImageBuffer(URI uri) throws Exception { try (NetClient nc = NetClient.of(uri); Fits f = new Fits(nc.getStream())) { BasicHDU<?>[] hdus = f.read(); // this is cumbersome for (BasicHDU<?> hdu : hdus) { if (hdu instanceof CompressedImageHDU) { return readHDU(((CompressedImageHDU) hdu).asImageHDU()); } } for (BasicHDU<?> hdu : hdus) { if (hdu instanceof ImageHDU) { return readHDU(hdu); } } } throw new Exception("No image found"); } private static String readHeader(BasicHDU<?> hdu) { return getHeaderAsXML(hdu.getHeader()); } private static final double GAMMA = 1 / 2.2; private static final long BLANK = 0; // in case it doesn't exist, very unlikely value private static float getValue(int bpp, Object lineData, int i, long blank, double bzero, double bscale) { double v = ImageBuffer.BAD_PIXEL; switch (bpp) { case BasicHDU.BITPIX_SHORT: v = ((short[]) lineData)[i]; break; case BasicHDU.BITPIX_INT: v = ((int[]) lineData)[i]; break; case BasicHDU.BITPIX_LONG: v = ((long[]) lineData)[i]; break; case BasicHDU.BITPIX_FLOAT: v = ((float[]) lineData)[i]; break; case BasicHDU.BITPIX_DOUBLE: v = ((double[]) lineData)[i]; break; } return (blank != BLANK && v == blank) || !Double.isFinite(v) ? ImageBuffer.BAD_PIXEL : (float) (bzero + v * bscale); } private static float[] sampleImage(int bpp, int width, int height, Object[] pixelData, long blank, double bzero, double bscale, int[] npix) { int stepW = Math.max(4 * width / 1024, 1); int stepH = Math.max(4 * height / 1024, 1); float[] sampleData = new float[(width / stepW) * (height / stepH)]; int k = 0; for (int j = 0; j < height; j += stepH) { Object lineData = pixelData[j]; for (int i = 0; i < width; i += stepW) { float v = getValue(bpp, lineData, i, blank, bzero, bscale); if (v != ImageBuffer.BAD_PIXEL) sampleData[k++] = v; } } npix[0] = k; return sampleData; } /* private static float[] getMinMax(int bpp, int width, int height, Object[] pixelData, long blank, double bzero, double bscale) { float min = Float.MAX_VALUE; float max = -Float.MAX_VALUE; for (int j = 0; j < height; j++) { Object lineData = pixelData[j]; for (int i = 0; i < width; i++) { float v = getValue(bpp, lineData, i, blank, bzero, bscale); if (v != ImageData.BAD_PIXEL) { if (v > max) max = v; if (v < min) min = v; } } } return new float[]{min, max}; } */ private static ImageBuffer readHDU(BasicHDU<?> hdu) throws Exception { int[] axes = hdu.getAxes(); if (axes == null || axes.length != 2) throw new Exception("Only 2D FITS files supported"); int height = axes[0]; int width = axes[1]; int bpp = hdu.getBitPix(); Object kernel = hdu.getKernel(); if (!(kernel instanceof Object[])) throw new Exception("Cannot retrieve pixel data"); Object[] pixelData = (Object[]) kernel; long blank = BLANK; try { blank = hdu.getBlankValue(); } catch (Exception ignore) { } if (bpp == BasicHDU.BITPIX_BYTE) { byte[][] inData = (byte[][]) pixelData; byte[] outData = new byte[width * height]; for (int j = 0; j < height; j++) { System.arraycopy(inData[j], 0, outData, width * (height - 1 - j), width); } return new ImageBuffer(width, height, ImageBuffer.Format.Gray8, ByteBuffer.wrap(outData)); } double bzero = hdu.getBZero(); double bscale = hdu.getBScale(); int[] npix = {0}; float[] sampleData = sampleImage(bpp, width, height, pixelData, blank, bzero, bscale, npix); float[] zLow = {0}; float[] zHigh = {0}; float[] zMax = {0}; ZScale.zscale(sampleData, npix[0], zLow, zHigh, zMax); // System.out.println(">>> " + npix[0] + " " + zLow[0] + " " + zMax[0]); float[] minmax = {zLow[0], zMax[0]}; // float[] minmax = getMinMax(bpp, width, height, pixelData, blank, bzero, bscale); if (minmax[0] >= minmax[1]) { Log.debug("min >= max :" + minmax[0] + ' ' + minmax[1]); minmax[1] = minmax[0] + 1; } double range = minmax[1] - minmax[0]; // System.out.println(">>> " + minmax[0] + ' ' + minmax[1]); short[] outData = new short[width * height]; float[] lut = new float[65536]; switch (bpp) { case BasicHDU.BITPIX_SHORT: case BasicHDU.BITPIX_INT: case BasicHDU.BITPIX_LONG: case BasicHDU.BITPIX_FLOAT: { double scale = 65535. / Math.pow(range, GAMMA); for (int j = 0; j < height; j++) { Object lineData = pixelData[j]; for (int i = 0; i < width; i++) { float v = getValue(bpp, lineData, i, blank, bzero, bscale); int p = (int) MathUtils.clip(scale * Math.pow(v - minmax[0], GAMMA) + .5, 0, 65535); lut[p] = v; outData[width * (height - 1 - j) + i] = v == ImageBuffer.BAD_PIXEL ? 0 : (short) p; } } break; } case BasicHDU.BITPIX_DOUBLE: { double scale = 65535. / Math.log1p(range); for (int j = 0; j < height; j++) { Object lineData = pixelData[j]; for (int i = 0; i < width; i++) { float v = getValue(bpp, lineData, i, blank, bzero, bscale); int p = (int) MathUtils.clip(scale * Math.log1p(v - minmax[0]) + .5, 0, 65535); lut[p] = v; outData[width * (height - 1 - j) + i] = v == ImageBuffer.BAD_PIXEL ? 0 : (short) p; } } break; } } return new ImageBuffer(width, height, ImageBuffer.Format.Gray16, ShortBuffer.wrap(outData), lut); } private static final String nl = System.getProperty("line.separator"); private static String getHeaderAsXML(Header header) { StringBuilder builder = new StringBuilder("<meta>" + nl + "<fits>" + nl); for (Cursor<String, HeaderCard> iter = header.iterator(); iter.hasNext(); ) { HeaderCard headerCard = iter.next(); String key = headerCard.getKey(); String value = headerCard.getValue(); if (value != null) { builder.append('<').append(key).append('>').append(value).append("</").append(key).append('>').append(nl); } } builder.append("</fits>").append(nl).append("</meta>"); return builder.toString().replace("&", "&amp;"); } }
package org.joval.plugin.adapter.solaris; import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collection; import java.util.Hashtable; import java.util.List; import java.util.StringTokenizer; import java.util.Vector; import java.util.logging.Logger; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import javax.xml.bind.JAXBElement; import oval.schemas.common.MessageType; import oval.schemas.common.MessageLevelEnumeration; import oval.schemas.definitions.solaris.SmfObject; import oval.schemas.systemcharacteristics.core.ItemType; import oval.schemas.systemcharacteristics.core.EntityItemStringType; import oval.schemas.systemcharacteristics.core.StatusEnumeration; import oval.schemas.systemcharacteristics.solaris.EntityItemSmfProtocolType; import oval.schemas.systemcharacteristics.solaris.EntityItemSmfServiceStateType; import oval.schemas.systemcharacteristics.solaris.SmfItem; import oval.schemas.results.core.ResultEnumeration; import org.joval.intf.plugin.IAdapter; import org.joval.intf.plugin.IRequestContext; import org.joval.intf.system.IProcess; import org.joval.intf.system.ISession; import org.joval.oval.OvalException; import org.joval.util.JOVALMsg; import org.joval.util.JOVALSystem; import org.joval.util.StringTools; /** * Evaluates the Solaris SMF OVAL tests. * * @author David A. Solin * @version %I% %G% */ public class SmfAdapter implements IAdapter { private ISession session; private String[] services = null; private Hashtable<String, SmfItem> serviceMap = null; public SmfAdapter(ISession session) { this.session = session; serviceMap = new Hashtable<String, SmfItem>(); } // Implement IAdapter public Class getObjectClass() { return SmfObject.class; } public boolean connect() { if (session != null) { BufferedReader br = null; try { JOVALSystem.getLogger().trace(JOVALMsg.STATUS_SMF); IProcess p = session.createProcess("/usr/bin/svcs -o fmri"); p.start(); br = new BufferedReader(new InputStreamReader(p.getInputStream())); ArrayList<String> list = new ArrayList<String>(); String line = null; while((line = br.readLine()) != null) { if (line.startsWith("FMRI")) { continue; } String fmri = getFullFmri(line.trim()); if (fmri == null) { JOVALSystem.getLogger().warn(JOVALMsg.ERROR_FMRI, line); } else { list.add(fmri); } } services = list.toArray(new String[list.size()]); } catch (Exception e) { JOVALSystem.getLogger().error(JOVALSystem.getMessage(JOVALMsg.ERROR_EXCEPTION), e); } finally { if (br != null) { try { br.close(); } catch (IOException e) { } } } } return services != null; } public void disconnect() { } public Collection<JAXBElement<? extends ItemType>> getItems(IRequestContext rc) throws OvalException { SmfObject sObj = (SmfObject)rc.getObject(); Collection<JAXBElement<? extends ItemType>> items = new Vector<JAXBElement<? extends ItemType>>(); switch(sObj.getFmri().getOperation()) { case EQUALS: try { SmfItem item = getItem((String)sObj.getFmri().getValue()); if (item != null) { items.add(JOVALSystem.factories.sc.solaris.createSmfItem(item)); } } catch (Exception e) { MessageType msg = JOVALSystem.factories.common.createMessageType(); msg.setLevel(MessageLevelEnumeration.ERROR); msg.setValue(e.getMessage()); rc.addMessage(msg); JOVALSystem.getLogger().error(JOVALSystem.getMessage(JOVALMsg.ERROR_EXCEPTION), e); } break; case NOT_EQUAL: { loadFullServiceMap(); for (String fmri : serviceMap.keySet()) { if (!fmri.equals((String)sObj.getFmri().getValue())) { items.add(JOVALSystem.factories.sc.solaris.createSmfItem(serviceMap.get(fmri))); } } break; } case PATTERN_MATCH: { loadFullServiceMap(); try { Pattern p = Pattern.compile((String)sObj.getFmri().getValue()); for (String fmri : serviceMap.keySet()) { if (p.matcher(fmri).find()) { items.add(JOVALSystem.factories.sc.solaris.createSmfItem(serviceMap.get(fmri))); } } } catch (PatternSyntaxException e) { MessageType msg = JOVALSystem.factories.common.createMessageType(); msg.setLevel(MessageLevelEnumeration.ERROR); msg.setValue(JOVALSystem.getMessage(JOVALMsg.ERROR_PATTERN, e.getMessage())); rc.addMessage(msg); JOVALSystem.getLogger().error(JOVALSystem.getMessage(JOVALMsg.ERROR_EXCEPTION), e); } break; } default: { String s = JOVALSystem.getMessage(JOVALMsg.ERROR_UNSUPPORTED_OPERATION, sObj.getFmri().getOperation()); throw new OvalException(s); } } return items; } // Internal private boolean loaded = false; private void loadFullServiceMap() { if (loaded) return; serviceMap = new Hashtable<String, SmfItem>(); for (int i=0; i < services.length; i++) { try { SmfItem item = getItem(services[i]); serviceMap.put((String)item.getFmri().getValue(), item); } catch (Exception e) { JOVALSystem.getLogger().warn(JOVALMsg.ERROR_SMF, services[i]); JOVALSystem.getLogger().error(JOVALSystem.getMessage(JOVALMsg.ERROR_EXCEPTION), e); } } loaded = true; } private static final String FMRI = "fmri"; private static final String NAME = "name"; private static final String ENABLED = "enabled"; private static final String STATE = "state"; private static final String NEXT_STATE = "next_state"; private static final String STATE_TIME = "state_time"; private static final String RESTARTER = "restarter"; private static final String DEPENDENCY = "dependency"; private static final String START_EXEC_PROP = "start/exec"; private static final String INETD_USER_PROP = "inetd_start/user"; private static final String INETD_EXEC_PROP = "inetd_start/exec"; private SmfItem getItem(String fmri) throws Exception { SmfItem item = serviceMap.get(fmri); if (item != null) { return item; } JOVALSystem.getLogger().trace(JOVALMsg.STATUS_SMF_SERVICE, fmri); item = JOVALSystem.factories.sc.solaris.createSmfItem(); IProcess p = session.createProcess("/usr/bin/svcs -l " + fmri); p.start(); BufferedReader br = null; boolean found = false; try { br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; while((line = br.readLine()) != null) { line = line.trim(); if (line.startsWith(FMRI)) { found = true; EntityItemStringType type = JOVALSystem.factories.sc.core.createEntityItemStringType(); type.setValue(getFullFmri(line.substring(FMRI.length()).trim())); item.setFmri(type); } else if (line.startsWith(NAME)) { EntityItemStringType type = JOVALSystem.factories.sc.core.createEntityItemStringType(); type.setValue(line.substring(NAME.length()).trim()); item.setServiceName(type); } else if (line.startsWith(STATE_TIME)) { // NB: this MUST appear before STATE } else if (line.startsWith(STATE)) { EntityItemSmfServiceStateType type = JOVALSystem.factories.sc.solaris.createEntityItemSmfServiceStateType(); type.setValue(line.substring(STATE.length()).trim().toUpperCase()); item.setServiceState(type); } } } finally { if (br != null) { br.close(); } } if (found) { // If the service was found, then we can retrieve some information using svcprop item.setStatus(StatusEnumeration.EXISTS); boolean inetd = false; p = session.createProcess("/usr/bin/svcprop " + fmri); p.start(); try { br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; while ((line = br.readLine()) != null) { if (line.startsWith(START_EXEC_PROP)) { setExecAndArgs(item, line.substring(START_EXEC_PROP.length()).trim()); } else if (line.startsWith(INETD_USER_PROP)) { inetd = true; String suspects = line.substring(INETD_USER_PROP.length()).trim(); List<String> list = StringTools.toList(StringTools.tokenize(suspects, " ")); if (list.size() > 0) { String user = list.get(list.size() - 1); EntityItemStringType type = JOVALSystem.factories.sc.core.createEntityItemStringType(); type.setValue(user); item.setExecAsUser(type); } } else if (line.startsWith(INETD_EXEC_PROP)) { inetd = true; setExecAndArgs(item, line.substring(INETD_EXEC_PROP.length()).trim()); } } } finally { if (br != null) { br.close(); } } // If this is an inetd-initiated service, we can get protocol information using inetadm if (inetd) { p = session.createProcess("/usr/sbin/inetadm -l " + fmri); p.start(); try { br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; while ((line = br.readLine()) != null) { if (line.trim().startsWith("proto=")) { String protocol = line.trim().substring(6); if (protocol.startsWith("\"") && protocol.endsWith("\"")) { protocol = protocol.substring(1, protocol.length() - 1); EntityItemSmfProtocolType type = JOVALSystem.factories.sc.solaris.createEntityItemSmfProtocolType(); type.setValue(protocol); item.setProtocol(type); } } } } finally { if (br != null) { br.close(); } } } } else { EntityItemStringType fmriType = JOVALSystem.factories.sc.core.createEntityItemStringType(); fmriType.setValue(fmri); item.setFmri(fmriType); item.setStatus(StatusEnumeration.DOES_NOT_EXIST); } return item; } /** * Given a property line starting after start/exec or inetd_start/exec, set the server_executable and server_arguments. */ private void setExecAndArgs(SmfItem item, String argv) { String unescaped = argv.replace("\\ ", " "); StringTokenizer tok = new StringTokenizer(unescaped); if (tok.hasMoreTokens()) { String astring = tok.nextToken(); if (astring.equals("astring") && tok.hasMoreTokens()) { String executable = tok.nextToken(); EntityItemStringType type = JOVALSystem.factories.sc.core.createEntityItemStringType(); type.setValue(executable); item.setServerExecutable(type); } StringBuffer arguments = new StringBuffer(); while(tok.hasMoreTokens()) { if (arguments.length() > 0) { arguments.append(" "); } arguments.append(tok.nextToken()); } if (arguments.length() > 0) { EntityItemStringType type = JOVALSystem.factories.sc.core.createEntityItemStringType(); type.setValue(arguments.toString()); item.setServerArguements(type); } } } /** * Generally, prepend "localhost". */ private String getFullFmri(String fmri) { if (fmri.indexOf(" int ptr = fmri.indexOf("/"); if (ptr == -1) { return null; } StringBuffer sb = new StringBuffer(fmri.substring(0, ptr)); sb.append("//localhost"); sb.append(fmri.substring(ptr)); return sb.toString(); } else { return fmri; } } }
package org.lockss.extractor; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Node; import org.jsoup.select.Elements; import org.jsoup.select.NodeVisitor; import org.lockss.config.Configuration; import org.lockss.config.CurrentConfig; import org.lockss.daemon.PluginException; import org.lockss.plugin.ArchivalUnit; import org.lockss.plugin.LinkExtractorStatisticsManager; import org.lockss.util.Logger; import org.lockss.util.ReaderInputStream; import org.lockss.util.StringUtil; import org.lockss.util.UrlUtil; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class JsoupHtmlLinkExtractor implements LinkExtractor { public static final String PREFIX = Configuration.PREFIX + "extractor.jsoup."; public static final String PARAM_ENABLE_STATS = PREFIX + "enable_stats"; public static final boolean DEFAULT_ENABLE_STATS = false; public static final String PARAM_PROCESS_FORMS = PREFIX + "process_forms"; public static final boolean DEFAULT_PROCESS_FORMS = false; /** * the theLog for this class */ private static final Logger theLog = Logger.getLogger(JsoupHtmlLinkExtractor.class); /** * the class map of tags -> link extractors */ private static HashMap<String, LinkExtractor> theTagTable; static { theTagTable = new HashMap<String, LinkExtractor>(); theTagTable.put("a", new SimpleTagLinkExtractor(new String[] { "href", "download" }) ); theTagTable.put("applet", new SimpleTagLinkExtractor(new String[] { "archive", "code", "codebase" }) ); theTagTable.put("area", new SimpleTagLinkExtractor("href")); theTagTable.put("audio", new SimpleTagLinkExtractor("src")); theTagTable.put("blockquote", new SimpleTagLinkExtractor("cite")); theTagTable.put("body", new SimpleTagLinkExtractor("background")); theTagTable.put("command", new SimpleTagLinkExtractor("icon")); theTagTable.put("del", new SimpleTagLinkExtractor("cite")); theTagTable.put("embed", new SimpleTagLinkExtractor("src")); theTagTable.put("frame", new SimpleTagLinkExtractor(new String[] {"src", "longdesc"}) ); theTagTable.put("head", new SimpleTagLinkExtractor("profile")); theTagTable.put("html", new SimpleTagLinkExtractor("manifest")); theTagTable.put("iframe", new SimpleTagLinkExtractor(new String[] {"src", "longdesc"}) ); theTagTable.put("img", new SimpleTagLinkExtractor(new String[] {"src", "longdesc"}) ); theTagTable.put("ins", new SimpleTagLinkExtractor("cite")); theTagTable.put("link", new SimpleTagLinkExtractor("href")); theTagTable.put("meta", new MetaTagLinkExtractor()); theTagTable.put("object", new SimpleTagLinkExtractor(new String[] {"archive", "data", "codebase"})); theTagTable.put("q", new SimpleTagLinkExtractor("cite")); theTagTable.put("table", new SimpleTagLinkExtractor("background")); theTagTable.put("tr", new SimpleTagLinkExtractor("background")); theTagTable.put("th", new SimpleTagLinkExtractor("background")); theTagTable.put("td", new SimpleTagLinkExtractor("background")); theTagTable.put("video", new SimpleTagLinkExtractor(new String[] {"poster", "src"}) ); theTagTable.put("param", new SimpleTagLinkExtractor(new String[] {"url", "src", "filename"}) ); theTagTable.put("script", new ScriptTagLinkExtractor()); theTagTable.put("base", new BaseTagLinkExtractor()); theTagTable.put("style", new StyleTagLinkExtractor()); } /** * true if we should log link extraction statistics */ private boolean m_enableStats; /** * true if we should use a form processor to process forms */ private boolean m_processForms; /** * the statistics manager for logging links extracted */ private LinkExtractorStatisticsManager m_statsMgr; /** * the instance map of tags -> link extractors */ private HashMap<String, LinkExtractor> m_tagTable = new HashMap<String, LinkExtractor>(); /** * The table of FormFieldRestrictions by field name * key = field name, * value = restrictions */ private Map<String, HtmlFormExtractor.FormFieldRestrictions> m_formRestrictors; /** * The table of FormFieldGenerators key = field name, value generator */ private Map<String, HtmlFormExtractor.FieldIterator> m_formGenerators; /** * A link extractor for 'style' attributes rather than tags. */ private StyleAttrLinkExtractor m_styleAttrExtractor; /** * constructor used for the jsoup link extractor. */ public JsoupHtmlLinkExtractor() { // set statistics on/off - def off m_enableStats = CurrentConfig.getBooleanParam(PARAM_ENABLE_STATS, DEFAULT_ENABLE_STATS); if (m_enableStats) { m_statsMgr = new LinkExtractorStatisticsManager(); } m_processForms = CurrentConfig.getBooleanParam(PARAM_PROCESS_FORMS, DEFAULT_PROCESS_FORMS); m_tagTable.putAll(theTagTable); m_styleAttrExtractor = new StyleAttrLinkExtractor(); } /** * constructor used by test code * * @param enableStats true to turn on statistics logging */ public JsoupHtmlLinkExtractor(boolean enableStats, boolean processForms, Map<String, HtmlFormExtractor .FormFieldRestrictions> restrictors, Map<String, HtmlFormExtractor.FieldIterator> generators) { m_enableStats = enableStats; m_processForms = processForms; m_formRestrictors = restrictors; m_formGenerators = generators; m_tagTable.putAll(theTagTable); m_styleAttrExtractor = new StyleAttrLinkExtractor(); } public void setFormRestrictors(final Map<String, HtmlFormExtractor .FormFieldRestrictions> formRestrictors) { m_formRestrictors = formRestrictors; } public void setFormGenerators(final Map<String, HtmlFormExtractor.FieldIterator> formGenerators) { m_formGenerators = formGenerators; } public Map<String, HtmlFormExtractor.FormFieldRestrictions> getFormRestrictors() { return m_formRestrictors; } public Map<String, HtmlFormExtractor.FieldIterator> getFormGenerators() { return m_formGenerators; } /** * Parse content on InputStream, call cb.foundUrl() for each URL found * * @param au the archival unit * @param in the input stream * @param encoding the character encoding for the input stream url * @param srcUrl The URL at which the content lives. Used as the base for * resolving relative URLs (unless/until base set otherwise by content) * @param cb the callback used to forward all found urls */ @Override public void extractUrls(final ArchivalUnit au, final InputStream in, final String encoding, final String srcUrl, final Callback cb) throws IOException, PluginException { // validate input if (in == null) { throw new IllegalArgumentException("Called with null InputStream"); } else if (srcUrl == null) { throw new IllegalArgumentException("Called with null srcUrl"); } else if (cb == null) { throw new IllegalArgumentException("Called with null callback"); } // our base url is the same as source when we start // the wrapper is only needed for the stats manager org.lockss.extractor.LinkExtractor.Callback wrapped_cb = cb; if (m_enableStats) { m_statsMgr.startMeasurement("JsoupHtmlLinkExtractor"); wrapped_cb = m_statsMgr.wrapCallback(cb, "JsoupHtmlLinkExtractor"); } // Parse our file Document doc = Jsoup.parse(in, encoding, srcUrl); HtmlFormExtractor formExtractor = null; if (m_processForms) { Elements els = doc.select("form"); // create a form processor formExtractor = getFormExtractor(au, encoding, cb); // To allow for HTML 5 forms which allow free form getFieldIterator we // grab all // forms. When we encounter an input elements with the 'form' // attribute we'll add it to the correct form. formExtractor.initProcessor(this, els.forms()); } // Now we walk the document as usual and process found urls doc.traverse(new LinkExtractorNodeVisitor(au, srcUrl, wrapped_cb,encoding)); if (formExtractor != null) { // Now we're ready to process any unprocessed forms formExtractor.processForms(); } if (m_enableStats) { m_statsMgr.stopMeasurement(); } } /** * Create a new FormExtractor for use to extract generated form urls. Override * to use a different HtmlFormExtractor. * @param au the archival unit * @param encoding the character encoding for the input stream url * @param cb the callback used to report a found link * @return a new HtmlFormExtractor */ protected HtmlFormExtractor getFormExtractor(final ArchivalUnit au, final String encoding, final Callback cb) { return new HtmlFormExtractor(au, cb, encoding, m_formRestrictors, m_formGenerators); } /** * check the link found in a node with a specific callback and * call foundLink on the callback if it it is valid. This uses the * Jsoup 'abs:' syntax to return the fully normalized link. * * @param node the node withe the given attr * @param cb the callback used to report a found link * @param attr the attr on the node which contains the link */ public static void checkLink(final Node node, final Callback cb, final String attr) { if (node.hasAttr(attr) && !StringUtil.isNullString(node.attr(attr))) { cb.foundLink(node.attr("abs:" + attr)); } } /** * Node Visitor for JSoup parser */ protected class LinkExtractorNodeVisitor implements NodeVisitor, Callback { private Callback m_cb; private ArchivalUnit m_au; private URL m_baseUrl; private String m_encoding; private boolean m_inScript; /** * Constructor * * @param au Current archival unit to which this html document * belongs. * @param srcUrl The url of this html document. * @param cb A callback to record extracted links. * @param encoding Encoding needed to read this html document off input * stream. */ public LinkExtractorNodeVisitor(ArchivalUnit au, String srcUrl, Callback cb, String encoding) { m_cb = cb; m_au = au; try { m_baseUrl = new URL(srcUrl); } catch (MalformedURLException e) { theLog.warning("Malformed Base URL: all doc urls must be absolute."); } m_encoding = encoding; m_inScript = false; VisitorLinkExtractor vle; vle = (VisitorLinkExtractor) m_tagTable.get("script"); vle.setNodeVisitor(this); vle = (VisitorLinkExtractor) m_tagTable.get("base"); vle.setNodeVisitor(this); EncodedLinkExtractor ele; ele = (EncodedLinkExtractor) m_tagTable.get("style"); ele.setEncoding(m_encoding); m_styleAttrExtractor.setEncoding(m_encoding); } /** * Callback used by the jsoup parser for when a node is first visited. * * @param node the node being visited. * @param depth the depth of the node, relative to the root node. E.g., the * root node has depth 0, and a child node of that will have depth 1. */ @Override public void head(final Node node, final int depth) { LinkExtractor tle = m_tagTable.get(node.nodeName()); if (node.hasAttr("style")) { m_styleAttrExtractor.tagBegin(node, m_au, this); } if (tle != null && !m_inScript) { tle.tagBegin(node, m_au, this); } } /** * Callback used by jsoup for when a node is last visited, * after all of its descendants have been visited. * * @param node the node being visited. * @param depth the depth of the node, relative to the root node. E.g., the * root node has depth 0, and a child node of that will have depth 1. */ @Override public void tail(final Node node, final int depth) { String name = node.nodeName(); LinkExtractor tle = m_tagTable.get(name); if (tle != null && ("script".equalsIgnoreCase(name) || !m_inScript)) { tle.tagEnd(node, m_au, this); } if (node.hasAttr("style")) { m_styleAttrExtractor.tagEnd(node, m_au, this); } } /** * Notify the callback when a link has been found by a link extractor. * * @param url the url which has been found. */ @Override public void foundLink(String url) { if (!StringUtil.isNullString(url)) { theLog.debug3("FoundLink (before resolver):" + url); try { url = resolveUri(m_baseUrl, url); if (url == null) { return; } // emit the processed url m_cb.foundLink(url); } catch (MalformedURLException e) { //if the link is malformed, we can safely ignore it } } } /** * Resolves a url relative to given base url and returns an absolute url. * Also does some minor transformation (such as escaping). Derived from * {@link GoslingHtmlLinkExtractor#resolveUri(URL, String)} * * @param base The base url * @param relative Url that needs to be resolved * * @return The absolute url. * * @throws MalformedURLException * @see UrlUtil#resolveUri(URL, String) */ protected String resolveUri(URL base, String relative) throws MalformedURLException { String baseProto = null; if (base != null) { baseProto = base.getProtocol(); } if ("javascript".equalsIgnoreCase(baseProto) || relative != null && StringUtil.startsWithIgnoreCase(relative,"javascript:")) { return null; } if ("mailto".equalsIgnoreCase(baseProto) || relative != null && StringUtil.startsWithIgnoreCase(relative,"mailto:")) { return null; } return UrlUtil.resolveUri(base, relative); } public void setInScript(final boolean inScript) { m_inScript = inScript; } public URL getBaseUrl() { return m_baseUrl; } public void setBaseUrl(final URL baseUrl) { m_baseUrl = baseUrl; } } /** * register a tag link extractor to handle processing a html tag. This * will replace the existing link extractor. * * @param tagName the name of the html tag * @param extractor the LinkExtractor to call when entering and exiting * a tag */ public void registerTagExtractor(String tagName, LinkExtractor extractor) { m_tagTable.put(tagName, extractor); } /** * unregister a tag link extractor to handle processing a html tag. This * will replace the existing link extractor. * * @param tagName the name of the html tag * * @return the LinkExtractor to called when entering and exiting * a tag */ public LinkExtractor unregisterTagExtractor(String tagName) { return m_tagTable.remove(tagName); } /** * The interface which wraps the jsoup callbacks to tagBegin * and tagEnd. */ public interface LinkExtractor { /** * Extract link(s) from this tag. * * @param node the node containing the tag info * @param au Current archival unit to which this html document belongs. * @param cb A callback to record extracted links. */ public void tagBegin(Node node, ArchivalUnit au, Callback cb); /** * Perform any extractions based on end tag processing. * * @param node the node containing the tag info * @param au Current archival unit to which this html document belongs. * @param cb A callback to record extracted links. */ public void tagEnd(Node node, ArchivalUnit au, Callback cb); } public interface EncodedLinkExtractor { public void setEncoding(String encoding); } public interface VisitorLinkExtractor { public void setNodeVisitor(LinkExtractorNodeVisitor nodeVisitor); } /** * Base Class for all Tag Link extractors which implements tagBegin * and tagEnd which simple logs to trace node entry and exit. * Subclasses must override tagBegin &/or tagEnd to obtain correct * tag behaviour. */ public static class BaseLinkExtractor implements LinkExtractor { /** * Extract link(s) from this tag. * * @param node the node containing the link * @param au Current archival unit to which this html document belongs. * @param cb A callback to record extracted links. */ @Override public void tagBegin(final Node node, final ArchivalUnit au, final Callback cb) { theLog.debug3("begin tag: " + node.nodeName()); } /** * Perform any extractions based on end tag processing. * * @param node the node containing the link * @param au Current archival unit to which this html document belongs. * @param cb A callback to record extracted links. */ @Override public void tagEnd(final Node node, final ArchivalUnit au, final Callback cb) { theLog.debug3("end tag: " + node.nodeName()); } } /** * Link Extractor for the html "base" tag */ public static class BaseTagLinkExtractor extends BaseLinkExtractor implements VisitorLinkExtractor{ private boolean m_baseSet = false; protected LinkExtractorNodeVisitor m_nodeVisitor; public void setNodeVisitor(LinkExtractorNodeVisitor nodeVisitor) { m_nodeVisitor = nodeVisitor; } @Override public void tagBegin(final Node node, final ArchivalUnit au, final Callback cb) { super.tagBegin(node, au, cb); if (!m_baseSet && node.hasAttr("href") && !StringUtil.isNullString(node.attr("href"))) { String href = node.attr("abs:href"); try { String newBase = m_nodeVisitor.resolveUri(m_nodeVisitor.getBaseUrl(), href); m_nodeVisitor.setBaseUrl(new URL(newBase)); m_baseSet = true; } catch (MalformedURLException e) { // ignore it, we don't change the base } } } } /** * Link Extractor for meta tag http-equiv url */ public static class MetaTagLinkExtractor extends BaseLinkExtractor { static private String CONTENT_ATTR = "content"; static private String URL_PREFIX = "url="; static private String EQUIV_ATTR = "http-equiv"; static private String EQUIV_REFRESH = "refresh"; /** * Extract link(s) from this tag. * * @param node the node containing the link * @param au Current archival unit to which this html document belongs. * @param cb A callback to record extracted links. */ @Override public void tagBegin(final Node node, final ArchivalUnit au, final Callback cb) { super.tagBegin(node, au, cb); if (node.hasAttr(EQUIV_ATTR) && node.attr(EQUIV_ATTR).equalsIgnoreCase(EQUIV_REFRESH)) { if (node.hasAttr(CONTENT_ATTR)) { String value = node.attr(CONTENT_ATTR); int pos = value.indexOf(URL_PREFIX) + URL_PREFIX.length(); if (pos > 0) { cb.foundLink(value.substring(pos)); } } } } } /** * A link extractor interface that can parse a given html tag and extract * link(s) from one or more attrs within it. */ public static class SimpleTagLinkExtractor extends BaseLinkExtractor { ArrayList<String> m_Attrs = new ArrayList<String>(); public SimpleTagLinkExtractor(String[] attr) { if (attr != null) { java.util.Collections.addAll(m_Attrs, attr); } } public SimpleTagLinkExtractor(String attr) { if (attr != null) { m_Attrs.add(attr); } } /** * Extract link(s) from this tag. * * @param node the node containing the link * @param au Current archival unit to which this html document belongs. * @param cb A callback to record extracted links. */ public void tagBegin(Node node, ArchivalUnit au, Callback cb) { super.tagBegin(node, au, cb); for (String attr : m_Attrs) { checkLink(node, cb, attr); } } } /** * Link Extractor for the script tag */ public static class ScriptTagLinkExtractor extends BaseLinkExtractor implements VisitorLinkExtractor{ protected LinkExtractorNodeVisitor m_nodeVisitor; public void setNodeVisitor(LinkExtractorNodeVisitor nodeVisitor) { m_nodeVisitor = nodeVisitor; } @Override public void tagBegin(final Node node, final ArchivalUnit au, final Callback cb) { super.tagBegin(node, au, cb); m_nodeVisitor.setInScript(true); checkLink(node, cb, "src"); } @Override public void tagEnd(final Node node, final ArchivalUnit au, final Callback cb) { super.tagEnd(node, au, cb); m_nodeVisitor.setInScript(false); } } /** * Base Link Extractor for tags containing style text */ public static class BaseStyleLinkExtractor extends BaseLinkExtractor implements EncodedLinkExtractor{ protected String m_encoding; public void setEncoding(String encoding) { m_encoding = encoding; } // Dispatch to CSS extractor void processStyleText(final String text, final Node node, final ArchivalUnit au, final Callback cb) { InputStream in = new ReaderInputStream(new StringReader(text), m_encoding); try { org.lockss.extractor.LinkExtractor cssExtractor = au.getLinkExtractor("text/css"); if (cssExtractor != null) { cssExtractor.extractUrls(au, in, m_encoding, node.baseUri(), cb); } } catch (IOException e) { theLog.debug3("IOException in CSS extractor", e); } catch (PluginException e) { theLog.debug3("PluginException in CSS extractor", e); } } } /** * Link Extractor for the style tag */ public static class StyleTagLinkExtractor extends BaseStyleLinkExtractor { /** * Extract link(s) from this tag. * * @param node the node containing the link * @param au Current archival unit to which this html document belongs. * @param cb A callback to record extracted links. */ @Override public void tagBegin(final Node node, final ArchivalUnit au, final Callback cb) { super.tagBegin(node, au, cb); processStyleText(node.outerHtml(), node, au, cb); } } /** * Link Extractor for tags with a style attribute */ public static class StyleAttrLinkExtractor extends BaseStyleLinkExtractor { /** * Extract link(s) from this tag. * * @param node the node containing the link * @param au Current archival unit to which this html document belongs. * @param cb A callback to record extracted links. */ @Override public void tagBegin(final Node node, final ArchivalUnit au, final Callback cb) { super.tagBegin(node, au, cb); // style attr is very common, creating css parser is expensive, do // only if evidence of URLs String val = node.attr("style"); if (val != null && StringUtil.indexOfIgnoreCase(val, "url(") >= 0) { processStyleText(val, node, au, cb); } } } public static class Factory implements LinkExtractorFactory { public org.lockss.extractor.LinkExtractor createLinkExtractor(String mimeType) { return new JsoupHtmlLinkExtractor(); } } }
package org.objectweb.proactive.core.mop; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Instances of this class represent method calls performed on reified * objects. They are generated by a <I>stub object</I>, whose role is to act * as a representative for the reified object. * * @author Julien Vayssi&egrave;re */ public final class MethodCall implements java.io.Serializable { /** * The size of the pool we use for recycling MethodCall objects. */ private static int RECYCLE_POOL_SIZE = 30; /** * The pool of recycled methodcall objects */ private static MethodCall[] recyclePool; /** * Position inside the pool */ private static int index; /** * Indicates if the recycling of MethodCall object is on. */ private static boolean recycleMethodCallObject; private static java.util.Hashtable reifiedMethodsTable = new java.util.Hashtable(); /** * Initializes the recycling of MethodCall objects to be enabled by default. */ static { MethodCall.setRecycleMethodCallObject(true); } /** * The array holding the argments of the method call */ private Object[] effectiveArguments; /** * The method corresponding to the call */ private Method reifiedMethod; /** * The hypothetic result */ private Object methodCallResult; /** * The internal ID of the methodcall */ private long methodCallID; /** * Sets recycling of MethodCall objects on/off. Note that turning the recycling * off and on again results in the recycling pool being flushed, thus damaging * performances. * * @param value sets the recycling on if <code>true</code>, otherwise turns it off. */ public static synchronized void setRecycleMethodCallObject(boolean value) { if (MethodCall.recycleMethodCallObject == value) return; else { MethodCall.recycleMethodCallObject = value; if (value) { // Creates the recycle poll for MethodCall objects MethodCall.recyclePool = new MethodCall[RECYCLE_POOL_SIZE]; MethodCall.index = 0; } else { // If we do not want to recycle MethodCall objects anymore, // let's free some memory by permitting the reyclePool to be // garbage-collecting MethodCall.recyclePool = null; } } } /** * Indicates if the recycling of MethodCall objects is currently running or not. * * @return <code>true</code> if recycling is on, <code>false</code> otherwise */ public static synchronized boolean getRecycleMethodCallObject() { return MethodCall.recycleMethodCallObject; } /** * Factory method for getting MethodCall objects * * @param reifiedMethod a <code>Method</code> object that represents * the method whose invocation is reified * @param effectiveArguments the effective arguments of the call. Arguments * that are of primitive type need to be wrapped * within an instance of the corresponding wrapper * class (like <code>java.lang.Integer</code> for * primitive type <code>int</code> for example). * @return a MethodCall object representing an invocation of method * <code>reifiedMethod</code> with arguments <code>effectiveArguments</code> */ public synchronized static MethodCall getMethodCall(Method reifiedMethod, Object[] effectiveArguments) { if (MethodCall.getRecycleMethodCallObject()) { // Finds a recycled MethodCall object in the pool, cleans it and // eventually returns it if (MethodCall.index > 0) { MethodCall result; // gets the object from the pool MethodCall.index result = MethodCall.recyclePool[MethodCall.index]; MethodCall.recyclePool[MethodCall.index] = null; // Refurbishes the object result.reifiedMethod = reifiedMethod; result.effectiveArguments = effectiveArguments; result.methodCallResult = null; return result; } else return new MethodCall(reifiedMethod, effectiveArguments); } else { return new MethodCall(reifiedMethod, effectiveArguments); } } /** * Tells the recyclying process that the MethodCall object passed as parameter * is ready for recycling. It is the responsibility of the caller of this * method to make sure that this object can safely be disposed of. */ public synchronized static void setMethodCall(MethodCall mc) { if (MethodCall.getRecycleMethodCallObject()) { // If there's still one slot left in the pool if (MethodCall.recyclePool[MethodCall.index] == null) { // Cleans up a MethodCall object // It is prefereable to do it here rather than at the moment // the object is picked out of the pool, because it allows // garbage-collecting the objects referenced in here mc.reifiedMethod = null; mc.effectiveArguments = null; mc.methodCallResult = null; // Inserts the object in the pool MethodCall.recyclePool[MethodCall.index] = mc; MethodCall.index++; if (MethodCall.index == RECYCLE_POOL_SIZE) MethodCall.index = RECYCLE_POOL_SIZE - 1; } } } /** * Builds a new MethodCall object. This constructor is private to this class * because we want to enforce the use of factory methods for getting fresh * instances of this class (see <I>Factory</I> pattern in GoF). */ private MethodCall(Method reifiedMethod, Object[] effectiveArguments) { this.reifiedMethod = reifiedMethod; this.effectiveArguments = effectiveArguments; this.methodCallResult = null; } /** * Executes the instance method call represented by this object. * * @param targetObject the Object the method is called on * @throws MethodCallExecutionFailedException thrown if the refleciton of the * call failed. * @throws InvocationTargetException thrown if the execution of the reified * method terminates abruptly by throwing an exception. The exception * thrown by the execution of the reified method is placed inside the * InvocationTargetException object. * @return the result of the invocation of the method. If the method returns * <code>void</code>, then <code>null</code> is returned. If the method * returned a primitive type, then it is wrapped inside the appropriate * wrapper object. */ public Object execute(Object targetObject) throws InvocationTargetException, MethodCallExecutionFailedException { // A test at how non-public methods can be reflected if (reifiedMethod.getParameterTypes().length > 0) reifiedMethod.setAccessible(true); try { return reifiedMethod.invoke(targetObject, effectiveArguments); } catch (IllegalAccessException e) { throw new MethodCallExecutionFailedException("Access rights to the method denied: " + e); } catch (IllegalArgumentException e) { throw new MethodCallExecutionFailedException("Illegal method arguments: " + e); } catch (ExceptionInInitializerError e) { throw new MethodCallExecutionFailedException("Cannot invoke method because it triggered the initialization of a class that failed: " + e); } } protected void finalize() { MethodCall.setMethodCall(this); } public Method getReifiedMethod() { return reifiedMethod; } public String getName() { return this.reifiedMethod.getName(); } public Object getParameter(int index) { return this.effectiveArguments[index]; } /** * Make a deep copy of all arguments of the constructor */ public void makeDeepCopyOfArguments() throws java.io.IOException { effectiveArguments = (Object[]) Utils.makeDeepCopy(effectiveArguments); } private Class[] fixBugRead(FixWrapper[] para) { Class[] tmp = new Class[para.length]; for (int i = 0; i < para.length; i++) { // System.out.println("fixBugRead for " + i + " value is " +para[i]); tmp[i] = para[i].getWrapped(); } return tmp; } private FixWrapper[] fixBugWrite(Class[] para) { FixWrapper[] tmp = new FixWrapper[para.length]; for (int i = 0; i < para.length; i++) { // System.out.println("fixBugWrite for " + i + " out of " + para.length + " value is " +para[i] ); tmp[i] = new FixWrapper(para[i]); } return tmp; } private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException { out.writeObject(this.effectiveArguments); // The Method object needs to be converted Class declaringClass = this.reifiedMethod.getDeclaringClass(); out.writeObject(declaringClass); out.writeObject(reifiedMethod.getName()); out.writeObject(fixBugWrite(this.reifiedMethod.getParameterTypes())); out.writeObject(methodCallResult); out.writeLong(methodCallID); } private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException { Class declaringClass; String simpleName; Class[] parameters; // Reads the effective arguments this.effectiveArguments = (Object[])in.readObject(); // Reads several pieces of data that we need for looking // up the method declaringClass = (Class)in.readObject(); simpleName = (String)in.readObject(); parameters = this.fixBugRead((FixWrapper[])in.readObject()); // Reads the methodCallResult instance variable this.methodCallResult = (Object)in.readObject(); this.methodCallID = in.readLong(); //this.forwarded=in.readBoolean(); // Builds a key StringBuffer sb = new StringBuffer(); sb.append(declaringClass.getName()); sb.append(simpleName); for (int i = 0; i < parameters.length; i++) { sb.append(parameters[i].getName()); } String key = sb.toString(); this.reifiedMethod = (Method)reifiedMethodsTable.get(key); if (this.reifiedMethod == null) { // Looks up the method try { this.reifiedMethod = declaringClass.getMethod(simpleName, parameters); reifiedMethodsTable.put(key, this.reifiedMethod); } catch (NoSuchMethodException e) { throw new InternalException("Lookup for method failed: " + e + ". This may be caused by having different versions of the same class on different VMs. Check your CLASSPATH settings."); } } } public class FixWrapper implements java.io.Serializable { public boolean isPrimitive; public Class encapsulated; public FixWrapper() {} /** * Encapsulate primitives types into Class */ public FixWrapper(Class c) { if (! c.isPrimitive()) { encapsulated = c; return; } isPrimitive = true; if (c.equals(Boolean.TYPE)) { encapsulated = Boolean.class; } else if (c.equals(Byte.TYPE)) { encapsulated = Byte.class; } else if (c.equals(Character.TYPE)) { encapsulated = Character.class; } else if (c.equals(Double.TYPE)) { encapsulated = Double.class; } else if (c.equals(Float.TYPE)) { encapsulated = Float.class; } else if (c.equals(Integer.TYPE)) { encapsulated = Integer.class; } else if (c.equals(Long.TYPE)) { encapsulated = Long.class; } else if (c.equals(Short.TYPE)) { encapsulated = Short.class; } } /** * Give back the original class */ public Class getWrapped() { if (! isPrimitive) return encapsulated; if (encapsulated.equals(Boolean.class)) return Boolean.TYPE; if (encapsulated.equals(Byte.class)) return Byte.TYPE; if (encapsulated.equals(Character.class)) return Character.TYPE; if (encapsulated.equals(Double.class)) return Double.TYPE; if (encapsulated.equals(Float.class)) return Float.TYPE; if (encapsulated.equals(Integer.class)) return Integer.TYPE; if (encapsulated.equals(Long.class)) return Long.TYPE; if (encapsulated.equals(Short.class)) return Short.TYPE; throw new RuntimeException("FixWrapper encapsulated class unkown "+encapsulated); } public String toString() { return "FixWrapper: " + encapsulated.toString(); } } // end inner class FixWrapper }
package hashdb.storage.protocol.external; import org.apache.log4j.Logger; import hashdb.communication.ServerConnectionInstance; import hashdb.exceptions.NoSuchServerException; import hashdb.exceptions.SettingIsNotIntroductionException; import hashdb.main.MasterServer; import hashdb.main.Server; import java.math.BigInteger; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Random; import java.util.concurrent.LinkedBlockingQueue; public class RemoteServerInfo { private static final Logger log = Logger.getLogger(RemoteServerInfo.class); private static int greatestServerId = 0; public int getServerID() { return serverID; } private final int serverID; private BigInteger lowerBound; private BigInteger greaterBound; private static final Queue<RemoteServerInfo> remoteServerInfoQueue = new LinkedBlockingQueue<RemoteServerInfo>(); private static final List<RemoteServerInfo> allRemoteServerInfos = new LinkedList<RemoteServerInfo>(); private ServerConnectionInstance sci; private static final Random r = new Random(); private RemoteServerInfo(int serverID, BigInteger lowerBound, BigInteger greaterBound) { this.lowerBound = lowerBound; this.greaterBound = greaterBound; this.serverID = serverID; if (Server.getInstance() instanceof MasterServer && serverID==0) return; allRemoteServerInfos.add(this); } public static RemoteServerInfo getBase(int byteSize) { byte[] array = new byte[byteSize]; array[0] = (byte) 0x80; BigInteger lbound = new BigInteger(array); for (@SuppressWarnings("unused") byte x : array) x = (byte) 0xFF; array[0] = 0x7F; BigInteger rbound = new BigInteger(array); RemoteServerInfo result = new RemoteServerInfo(1, lbound, rbound); greatestServerId = 1; remoteServerInfoQueue.add(result); return result; } private static final BigInteger TWO = new BigInteger("2"); private static final BigInteger ONE = BigInteger.ONE; public static RemoteServerInfo getNextRandom() { return allRemoteServerInfos.get(r.nextInt(allRemoteServerInfos.size())); } private RemoteServerInfo split(int id) { BigInteger sum = this.lowerBound.add(this.greaterBound); BigInteger half = sum.divide(TWO); RemoteServerInfo result = new RemoteServerInfo(id, half.add(ONE), this.greaterBound); this.greaterBound = half; return result; } public static void newServerDetected(int id) { if (id <= greatestServerId || greatestServerId == 0) return; while (greatestServerId < id) { greatestServerId++; RemoteServerInfo old = remoteServerInfoQueue.poll(); RemoteServerInfo tmp = old.split(greatestServerId); remoteServerInfoQueue.add(old); remoteServerInfoQueue.add(tmp); } greatestServerId = id; report(); } private static void report() { for (RemoteServerInfo rsi : allRemoteServerInfos) log.info("REPORT " + rsi.toString()); } public static RemoteServerInfo findID(byte[] keyBinary) throws NoSuchServerException { BigInteger key = new BigInteger(keyBinary); for (RemoteServerInfo s : allRemoteServerInfos) if (s.contains(key)) return s; throw new NoSuchServerException(); } private boolean contains(BigInteger key) { return key.compareTo(this.lowerBound) != -1 && key.compareTo(this.greaterBound) != 1; } public static void addConnectionInstance(int serverID, ServerConnectionInstance sci) { newServerDetected(serverID); log.info("New server detected with id " + serverID); report(); for (RemoteServerInfo rsi : allRemoteServerInfos) if (rsi.serverID == serverID) rsi.sci = sci; } @Override public String toString() { return serverID + ": " + lowerBound.toString() + " - " + greaterBound.toString(); } public ServerConnectionInstance getServerConnectionInstance() { return sci; } public static int numberOfConnectedServers() { return allRemoteServerInfos.size(); } public static RemoteServerInfo get(int i) { return allRemoteServerInfos.get(i); } private static BigInteger findMaxKeySpace() { return remoteServerInfoQueue.peek().getKeySpace(); } BigInteger getKeySpace() { return greaterBound.subtract(lowerBound).abs(); } public static int getSumRelativeWeight() { BigInteger maximum = findMaxKeySpace(); int i=allRemoteServerInfos.size(); for (RemoteServerInfo rsi:allRemoteServerInfos) if (rsi.getKeySpace().equals(maximum)) i++; return i; } public static RemoteServerInfo getFromWeighted(int i) { BigInteger maximum = findMaxKeySpace(); i++; for (RemoteServerInfo rsi:allRemoteServerInfos) { i if (rsi.getKeySpace().equals(maximum)) i if (i<=0) return rsi; } return null; } private static RemoteServerInfo masterRemoteServerInfo = new RemoteServerInfo(0, new BigInteger("0"), new BigInteger("0")); public static RemoteServerInfo getFromID(int i) { if (i==0) return masterRemoteServerInfo; for (RemoteServerInfo rsi:allRemoteServerInfos) if (rsi.serverID == i) return rsi; return null; } public void introduceServerConnectionInstance(ServerConnectionInstance sci) throws SettingIsNotIntroductionException { if (this.sci != null) throw new SettingIsNotIntroductionException(); this.sci = sci; } public static RemoteServerInfo getMyNext() { int myID = Server.getInstance().getID(); myID++; RemoteServerInfo result = getFromID(myID); if (result == null) result = getFromID(1); return result; } }
package org.peg4d.jvm; import org.objectweb.asm.Label; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.commons.GeneratorAdapter; import org.objectweb.asm.commons.Method; import org.peg4d.Grammar; import org.peg4d.ParsingContext; import org.peg4d.ParsingObject; import org.peg4d.ParsingRule; import org.peg4d.ParsingSource; import org.peg4d.ParsingTag; import org.peg4d.ParsingUtils; import org.peg4d.expression.NonTerminal; import org.peg4d.expression.ParsingAnd; import org.peg4d.expression.ParsingAny; import org.peg4d.expression.ParsingApply; import org.peg4d.expression.ParsingAssert; import org.peg4d.expression.ParsingBlock; import org.peg4d.expression.ParsingByte; import org.peg4d.expression.ParsingByteRange; import org.peg4d.expression.ParsingCatch; import org.peg4d.expression.ParsingChoice; import org.peg4d.expression.ParsingConnector; import org.peg4d.expression.ParsingConstructor; import org.peg4d.expression.ParsingEmpty; import org.peg4d.expression.ParsingExport; import org.peg4d.expression.ParsingExpression; import org.peg4d.expression.ParsingFailure; import org.peg4d.expression.ParsingIf; import org.peg4d.expression.ParsingIndent; import org.peg4d.expression.ParsingIsa; import org.peg4d.expression.ParsingMatch; import org.peg4d.expression.ParsingName; import org.peg4d.expression.ParsingNot; import org.peg4d.expression.ParsingOption; import org.peg4d.expression.ParsingRepetition; import org.peg4d.expression.ParsingSequence; import org.peg4d.expression.ParsingString; import org.peg4d.expression.ParsingTagging; import org.peg4d.expression.ParsingValue; import org.peg4d.expression.ParsingWithFlag; import org.peg4d.expression.ParsingWithoutFlag; import org.peg4d.jvm.ClassBuilder; import org.peg4d.jvm.InvocationTarget; import static org.peg4d.jvm.InvocationTarget.*; import org.peg4d.jvm.Methods; import org.peg4d.jvm.UserDefinedClassLoader; import org.peg4d.jvm.ClassBuilder.MethodBuilder; import org.peg4d.jvm.ClassBuilder.VarEntry; import org.peg4d.pegcode.GrammarFormatter; public class OldStyleJavaByteCodeGenerator extends GrammarFormatter implements Opcodes { private final static String packagePrefix = "org/peg4d/generated/"; private static int nameSuffix = -1; private ClassBuilder cBuilder; /** * current method builder */ private MethodBuilder mBuilder; /** * represents argument (ParsingContext ctx) */ private VarEntry entry_context; // invocation target private InvocationTarget target_byteAt = newVirtualTarget(ParsingSource.class, int.class, "byteAt", long.class); private InvocationTarget target_consume = newVirtualTarget(ParsingContext.class, void.class, "consume", int.class); private InvocationTarget target_getPosition = newVirtualTarget(ParsingContext.class, long.class, "getPosition"); private InvocationTarget target_rollback = newVirtualTarget(ParsingContext.class, void.class, "rollback", long.class); private InvocationTarget target_markLogStack = newVirtualTarget(ParsingContext.class, int.class, "markLogStack"); private InvocationTarget target_abortLog = newVirtualTarget(ParsingContext.class, void.class, "abortLog", int.class); private InvocationTarget target_rememberFailure = newVirtualTarget(ParsingContext.class, long.class, "rememberFailure"); private InvocationTarget target_forgetFailure = newVirtualTarget(ParsingContext.class, void.class, "forgetFailure", long.class); private InvocationTarget target_lazyLink = newVirtualTarget(ParsingContext.class, void.class, "lazyLink", ParsingObject.class, int.class, ParsingObject.class); private InvocationTarget target_setFlag = newVirtualTarget(ParsingContext.class, void.class, "setFlag", String.class, boolean.class); private InvocationTarget target_getFlag = newVirtualTarget(ParsingContext.class, boolean.class, "getFlag", String.class); /** * * @param ruleName * @return * if ruleName is java identifier, return it, * if ruleName is not java identifier, return replaced rule name. */ private String checkAndReplaceRuleName(String ruleName) { StringBuilder sBuilder = new StringBuilder(); final int size = ruleName.length(); for(int i = 0; i < size; i++) { char ch = ruleName.charAt(i); if(i == 0 && !Character.isJavaIdentifierStart(ch)) { sBuilder.append("Rule_"); sBuilder.append((int) ch); continue; } if(!Character.isJavaIdentifierPart(ch)) { sBuilder.append('_'); sBuilder.append((int) ch); } else { sBuilder.append(ch); } } return sBuilder.toString(); } @Override public String getDesc() { return "JVM "; } @Override public void formatGrammar(Grammar peg, StringBuilder sb) { this.formatHeader(); for(ParsingRule r: peg.getRuleList()) { this.formatRule(r.ruleName, r.expr); } this.formatFooter(); } @Override public void formatHeader() { this.cBuilder = new ClassBuilder(packagePrefix + "GeneratedParser" + ++nameSuffix, null, null, null); } @Override public void formatFooter() { this.cBuilder.visitEnd(); // finalize class builder } private void formatRule(String ruleName, ParsingExpression e) { // not use string builder String methodName = this.checkAndReplaceRuleName(ruleName); /** * create new method builder. * ex. FILE -> public static boolean FILE(ParsingContext ctx) */ this.mBuilder = this.cBuilder.newMethodBuilder(ACC_PUBLIC | ACC_STATIC, boolean.class, methodName, ParsingContext.class); // initialize this.mBuilder.enterScope(); // enter block scope this.entry_context = this.mBuilder.defineArgument(ParsingContext.class); // represent first argument of generating method // generate method body e.visit(this); // finalize this.mBuilder.exitScope(); this.mBuilder.returnValue(); // return stack top value (must be boolean type) this.mBuilder.endMethod(); } /** * finalize class builder and generate class form byte code * @return * generated parser class */ public Class<?> generateClass() { UserDefinedClassLoader loader = new UserDefinedClassLoader(); return loader.definedAndLoadClass(this.cBuilder.getInternalName(), cBuilder.toByteArray()); } // helper method. private void generateFailure() { // generate equivalent code to ParsingContext#failure Label thenLabel = this.mBuilder.newLabel(); Label mergeLabel = this.mBuilder.newLabel(); // if cond this.getFieldOfContext("pos", long.class); this.getFieldOfContext("fpos", long.class); this.mBuilder.ifCmp(Type.LONG_TYPE, GeneratorAdapter.GT, thenLabel); // else this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.pushNull(); this.mBuilder.putField(Type.getType(ParsingContext.class), "left", Type.getType(ParsingObject.class)); this.mBuilder.goTo(mergeLabel); // then this.mBuilder.mark(thenLabel); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.dup(); this.mBuilder.getField(Type.getType(ParsingContext.class), "pos", Type.getType(long.class)); this.mBuilder.putField(Type.getType(ParsingContext.class), "fpos", Type.getType(long.class)); //merge this.mBuilder.mark(mergeLabel); } /** * generate code of access ParsingContext field and put field value at stack top * @param fieldName * @param fieldClass */ private void getFieldOfContext(String fieldName, Class<?> fieldClass) { this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.getField(Type.getType(ParsingContext.class), fieldName, Type.getType(fieldClass)); } private void newParsingTag(String tagName) { Type typeDesc = Type.getType(ParsingTag.class); this.mBuilder.newInstance(typeDesc); this.mBuilder.dup(); this.mBuilder.push(tagName); // push tag name this.mBuilder.invokeConstructor(typeDesc, Methods.constructor(String.class)); } // visitor api @Override public void visitNonTerminal(NonTerminal e) { Method methodDesc = Methods.method(boolean.class, this.checkAndReplaceRuleName(e.ruleName), ParsingContext.class); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.invokeStatic(this.cBuilder.getTypeDesc(), methodDesc); } @Override public void visitEmpty(ParsingEmpty e) { this.mBuilder.push(true); } @Override public void visitFailure(ParsingFailure e) { this.generateFailure(); this.mBuilder.push(false); } @Override public void visitByte(ParsingByte e) { // generate if cond Label elseLabel = this.mBuilder.newLabel(); Label mergeLabel = this.mBuilder.newLabel(); // generate byteAt this.getFieldOfContext("source", ParsingSource.class); this.getFieldOfContext("pos", long.class); this.mBuilder.callInvocationTarget(this.target_byteAt); // push byteChar this.mBuilder.push(e.byteChar); this.mBuilder.ifCmp(Type.INT_TYPE, GeneratorAdapter.NE, elseLabel); // generate if block this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.push((int) 1); this.mBuilder.callInvocationTarget(this.target_consume); this.mBuilder.push(true); this.mBuilder.goTo(mergeLabel); // generate else block this.mBuilder.mark(elseLabel); this.generateFailure(); this.mBuilder.push(false); // merge this.mBuilder.mark(mergeLabel); } @Override public void visitByteRange(ParsingByteRange e) { this.mBuilder.enterScope(); // generate byteAt this.getFieldOfContext("source", ParsingSource.class); this.getFieldOfContext("pos", long.class); this.mBuilder.callInvocationTarget(this.target_byteAt); // generate variable VarEntry entry_ch = this.mBuilder.createNewVarAndStore(int.class); Label andRightLabel = this.mBuilder.newLabel(); Label thenLabel = this.mBuilder.newLabel(); Label elseLabel = this.mBuilder.newLabel(); Label mergeLabel = this.mBuilder.newLabel(); // and left this.mBuilder.push(e.startByteChar); this.mBuilder.loadFromVar(entry_ch); this.mBuilder.ifCmp(Type.INT_TYPE, GeneratorAdapter.LE, andRightLabel); this.mBuilder.goTo(elseLabel); // and right this.mBuilder.mark(andRightLabel); this.mBuilder.loadFromVar(entry_ch); this.mBuilder.push(e.endByteChar); this.mBuilder.ifCmp(Type.INT_TYPE, GeneratorAdapter.LE, thenLabel); this.mBuilder.goTo(elseLabel); // then this.mBuilder.mark(thenLabel); this.mBuilder.loadFromVar(entry_context); this.mBuilder.push(1); this.mBuilder.callInvocationTarget(this.target_consume); this.mBuilder.push(true); this.mBuilder.goTo(mergeLabel); // else this.mBuilder.mark(elseLabel); this.generateFailure(); this.mBuilder.push(false); // merge this.mBuilder.mark(mergeLabel); this.mBuilder.exitScope(); } @Override public void visitString(ParsingString e) { //FIXME: this.getFieldOfContext("source", ParsingSource.class); this.getFieldOfContext("pos", long.class); // init utf8 array final int size = e.utf8.length; this.mBuilder.push(size); this.mBuilder.newArray(Type.getType(byte.class)); for(int i = 0; i < size; i++) { this.mBuilder.dup(); this.mBuilder.push(i); this.mBuilder.push(e.utf8[i]); this.mBuilder.arrayStore(Type.getType(byte.class)); } Label thenLabel = this.mBuilder.newLabel(); Label mergeLabel = this.mBuilder.newLabel(); this.mBuilder.callInstanceMethod(ParsingSource.class, boolean.class, "match", long.class, byte[].class); this.mBuilder.push(true); this.mBuilder.ifCmp(Type.BOOLEAN_TYPE, GeneratorAdapter.EQ, thenLabel); // else this.generateFailure(); this.mBuilder.push(false); this.mBuilder.goTo(mergeLabel); // then this.mBuilder.mark(thenLabel); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.push(size); this.mBuilder.callInvocationTarget(this.target_consume); this.mBuilder.push(true); // merge this.mBuilder.mark(mergeLabel); } @Override public void visitAny(ParsingAny e) { this.getFieldOfContext("source", ParsingSource.class); this.getFieldOfContext("pos", long.class); this.mBuilder.callInstanceMethod(ParsingSource.class, int.class, "charAt", long.class); this.mBuilder.push(-1); Label thenLabel = this.mBuilder.newLabel(); Label mergeLabel = this.mBuilder.newLabel(); this.mBuilder.ifCmp(Type.INT_TYPE, GeneratorAdapter.NE, thenLabel); // else this.generateFailure(); this.mBuilder.push(false); this.mBuilder.goTo(mergeLabel); // then { this.mBuilder.mark(thenLabel); this.mBuilder.enterScope(); this.getFieldOfContext("source", ParsingSource.class); this.getFieldOfContext("pos", long.class); this.mBuilder.callInstanceMethod(ParsingSource.class, int.class, "charLength", long.class); VarEntry entry_len = this.mBuilder.createNewVarAndStore(int.class); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.loadFromVar(entry_len); this.mBuilder.callInvocationTarget(this.target_consume); this.mBuilder.push(true); this.mBuilder.exitScope(); } // merge this.mBuilder.mark(mergeLabel); } @Override public void visitTagging(ParsingTagging e) { this.getFieldOfContext("left", ParsingObject.class); this.newParsingTag(e.tag.toString()); this.mBuilder.callInstanceMethod(ParsingObject.class, void.class, "setTag", ParsingTag.class); this.mBuilder.push(true); } @Override public void visitValue(ParsingValue e) { this.getFieldOfContext("left", ParsingObject.class); this.mBuilder.push(e.value); this.mBuilder.callInstanceMethod(ParsingObject.class, void.class, "setValue", Object.class); this.mBuilder.push(true); } @Override public void visitIndent(ParsingIndent e) { throw new RuntimeException("unimplemented visit method: " + e.getClass()); } // @Override // public void visitUnary(ParsingUnary e) { // throw new RuntimeException("unimplemented visit method: " + e.getClass()); @Override public void visitNot(ParsingNot e) { this.mBuilder.enterScope(); // variable this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.callInvocationTarget(this.target_getPosition); VarEntry entry_pos = this.mBuilder.createNewVarAndStore(long.class); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.callInvocationTarget(this.target_rememberFailure); VarEntry entry_f = this.mBuilder.createNewVarAndStore(long.class); this.getFieldOfContext("left", ParsingObject.class); VarEntry entry_left = this.mBuilder.createNewVarAndStore(ParsingObject.class); // if cond Label thenLabel = this.mBuilder.newLabel(); Label mergeLabel = this.mBuilder.newLabel(); e.inner.visit(this); this.mBuilder.push(true); this.mBuilder.ifCmp(Type.BOOLEAN_TYPE, GeneratorAdapter.EQ, thenLabel); // else this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.loadFromVar(entry_pos); this.mBuilder.callInvocationTarget(this.target_rollback); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.loadFromVar(entry_f); this.mBuilder.callInvocationTarget(this.target_forgetFailure); this.mBuilder.loadFromVar(entry_context); this.mBuilder.loadFromVar(entry_left); this.mBuilder.putField(Type.getType(ParsingContext.class), "left", Type.getType(ParsingObject.class)); // this.mBuilder.pushNull(); // this.mBuilder.storeToVar(entry_left); this.mBuilder.push(true); this.mBuilder.goTo(mergeLabel); // then this.mBuilder.mark(thenLabel); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.loadFromVar(entry_pos); this.mBuilder.callInvocationTarget(this.target_rollback); this.generateFailure(); // this.mBuilder.pushNull(); // this.mBuilder.storeToVar(entry_left); this.mBuilder.push(false); // merge this.mBuilder.mark(mergeLabel); this.mBuilder.exitScope(); } @Override public void visitAnd(ParsingAnd e) { this.mBuilder.enterScope(); // generate getPosition this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.callInvocationTarget(this.target_getPosition); // generate variable VarEntry entry_pos = this.mBuilder.createNewVarAndStore(long.class); e.inner.visit(this); // this.mBuilder.pop(); // generate rollback this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.loadFromVar(entry_pos); this.mBuilder.callInvocationTarget(this.target_rollback); // // generate isFailure // this.mBuilder.loadFromVar(this.entry_context); // this.mBuilder.callInvocationTarget(this.target_isFailure); // this.mBuilder.not(); this.mBuilder.exitScope(); } @Override public void visitOptional(ParsingOption e) { this.mBuilder.enterScope(); // variable this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.callInvocationTarget(this.target_rememberFailure); VarEntry entry_f = this.mBuilder.createNewVarAndStore(long.class); this.getFieldOfContext("left", ParsingObject.class); VarEntry entry_left = this.mBuilder.createNewVarAndStore(ParsingObject.class); // if cond Label thenLabel = this.mBuilder.newLabel(); Label mergeLabel = this.mBuilder.newLabel(); e.inner.visit(this); this.mBuilder.push(true); this.mBuilder.ifCmp(Type.BOOLEAN_TYPE, GeneratorAdapter.NE, thenLabel); // else this.mBuilder.goTo(mergeLabel); // then this.mBuilder.mark(thenLabel); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.loadFromVar(entry_left); this.mBuilder.putField(Type.getType(ParsingContext.class), "left", Type.getType(ParsingObject.class)); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.loadFromVar(entry_f); this.mBuilder.callInvocationTarget(this.target_forgetFailure); // merge this.mBuilder.mark(mergeLabel); // this.mBuilder.pushNull(); // this.mBuilder.storeToVar(entry_left); this.mBuilder.push(true); this.mBuilder.exitScope(); } @Override public void visitRepetition(ParsingRepetition e) { this.mBuilder.enterScope(); // variable this.mBuilder.push((long)-1); VarEntry entry_ppos = this.mBuilder.createNewVarAndStore(long.class); this.mBuilder.loadFromVar(entry_context); this.mBuilder.callInvocationTarget(this.target_getPosition); VarEntry entry_pos = this.mBuilder.createNewVarAndStore(long.class); Label continueLabel = this.mBuilder.newLabel(); Label breakLabel = this.mBuilder.newLabel(); Label whileBlockLabel = this.mBuilder.newLabel(); // while continue this.mBuilder.mark(continueLabel); // while cond this.mBuilder.loadFromVar(entry_ppos); this.mBuilder.loadFromVar(entry_pos); this.mBuilder.ifCmp(Type.LONG_TYPE, GeneratorAdapter.LT, whileBlockLabel); this.mBuilder.goTo(breakLabel); // while then { this.mBuilder.mark(whileBlockLabel); this.mBuilder.enterScope(); this.getFieldOfContext("left", ParsingObject.class); VarEntry entry_left = this.mBuilder.createNewVarAndStore(ParsingObject.class); Label thenLabel = this.mBuilder.newLabel(); Label mergeLabel = this.mBuilder.newLabel(); e.inner.visit(this); this.mBuilder.push(true); this.mBuilder.ifCmp(Type.BOOLEAN_TYPE, GeneratorAdapter.NE, thenLabel); this.mBuilder.goTo(mergeLabel); // then this.mBuilder.mark(thenLabel); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.loadFromVar(entry_left); this.mBuilder.putField(Type.getType(ParsingContext.class), "left", Type.getType(ParsingObject.class)); this.mBuilder.pushNull(); this.mBuilder.storeToVar(entry_left); this.mBuilder.goTo(breakLabel); // merge this.mBuilder.mark(mergeLabel); this.mBuilder.loadFromVar(entry_pos); this.mBuilder.storeToVar(entry_ppos); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.callInvocationTarget(this.target_getPosition); this.mBuilder.storeToVar(entry_pos); this.mBuilder.pushNull(); this.mBuilder.storeToVar(entry_left); this.mBuilder.exitScope(); this.mBuilder.goTo(continueLabel); } // break this.mBuilder.mark(breakLabel); this.mBuilder.push(true); this.mBuilder.exitScope(); } @Override public void visitConnector(ParsingConnector e) { this.mBuilder.enterScope(); // variable this.getFieldOfContext("left", ParsingObject.class); VarEntry entry_left = this.mBuilder.createNewVarAndStore(ParsingObject.class); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.callInvocationTarget(this.target_markLogStack); VarEntry entry_mark = this.mBuilder.createNewVarAndStore(int.class); Label thenLabel = this.mBuilder.newLabel(); Label mergeLabel = this.mBuilder.newLabel(); // if cond e.inner.visit(this); this.mBuilder.push(true); this.mBuilder.ifCmp(Type.BOOLEAN_TYPE, GeneratorAdapter.EQ, thenLabel); // else this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.loadFromVar(entry_mark); this.mBuilder.callInvocationTarget(this.target_abortLog); // this.mBuilder.pushNull(); // this.mBuilder.storeToVar(entry_left); this.mBuilder.push(false); this.mBuilder.goTo(mergeLabel); // then { this.mBuilder.mark(thenLabel); Label thenLabel2 = this.mBuilder.newLabel(); Label mergeLabel2 = this.mBuilder.newLabel(); this.getFieldOfContext("left", ParsingObject.class); this.mBuilder.loadFromVar(entry_left); this.mBuilder.ifCmp(Type.getType(Object.class), GeneratorAdapter.NE, thenLabel2); this.mBuilder.goTo(mergeLabel2); // then2 this.mBuilder.mark(thenLabel2); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.loadFromVar(entry_mark); this.getFieldOfContext("left", ParsingObject.class); this.mBuilder.callInstanceMethod(ParsingContext.class, void.class, "commitLog", int.class, ParsingObject.class); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.loadFromVar(entry_left); this.mBuilder.push(e.index); this.getFieldOfContext("left", ParsingObject.class); this.mBuilder.callInvocationTarget(this.target_lazyLink); // merge2 this.mBuilder.mark(mergeLabel2); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.loadFromVar(entry_left); this.mBuilder.putField(Type.getType(ParsingContext.class), "left", Type.getType(ParsingObject.class)); // this.mBuilder.pushNull(); // this.mBuilder.storeToVar(entry_left); this.mBuilder.push(true); } // merge this.mBuilder.mark(mergeLabel); this.mBuilder.exitScope(); } @Override public void visitExport(ParsingExport e) { //TODO: this.mBuilder.push(true); } @Override public void visitSequence(ParsingSequence e) { this.mBuilder.enterScope(); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.callInvocationTarget(this.target_getPosition); VarEntry entry_pos = this.mBuilder.createNewVarAndStore(long.class); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.callInvocationTarget(this.target_markLogStack); VarEntry entry_mark = this.mBuilder.createNewVarAndStore(int.class); Label thenLabel = this.mBuilder.newLabel(); Label mergeLabel = this.mBuilder.newLabel(); for(int i = 0; i < e.size(); i++) { e.get(i).visit(this); this.mBuilder.push(true); this.mBuilder.ifCmp(Type.BOOLEAN_TYPE, GeneratorAdapter.NE, thenLabel); } this.mBuilder.push(true); this.mBuilder.goTo(mergeLabel); // then this.mBuilder.mark(thenLabel); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.loadFromVar(entry_mark); this.mBuilder.callInvocationTarget(this.target_abortLog); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.loadFromVar(entry_pos); this.mBuilder.callInvocationTarget(this.target_rollback); this.mBuilder.push(false); // merge this.mBuilder.mark(mergeLabel); this.mBuilder.exitScope(); } @Override public void visitChoice(ParsingChoice e) { this.mBuilder.enterScope(); // generate context.rememberFailure and store to f this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.callInvocationTarget(this.target_rememberFailure); VarEntry entry_f = this.mBuilder.createNewVarAndStore(long.class); // generate context.left and store to left this.getFieldOfContext("left", ParsingObject.class); VarEntry entry_left = this.mBuilder.createNewVarAndStore(ParsingObject.class); Label thenLabel = this.mBuilder.newLabel(); Label mergeLabel = this.mBuilder.newLabel(); for(int i = 0; i < e.size(); i++) { // store to context.left this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.loadFromVar(entry_left); this.mBuilder.putField(Type.getType(ParsingContext.class), "left", Type.getType(ParsingObject.class)); e.get(i).visit(this); this.mBuilder.push(true); this.mBuilder.ifCmp(Type.BOOLEAN_TYPE, GeneratorAdapter.EQ, thenLabel); } // this.mBuilder.pushNull(); // this.mBuilder.storeToVar(entry_left); this.mBuilder.push(false); this.mBuilder.goTo(mergeLabel); // then this.mBuilder.mark(thenLabel); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.loadFromVar(entry_f); this.mBuilder.callInvocationTarget(this.target_forgetFailure); // this.mBuilder.pushNull(); // this.mBuilder.storeToVar(entry_left); this.mBuilder.push(true); // merge this.mBuilder.mark(mergeLabel); this.mBuilder.exitScope(); } @Override public void visitConstructor(ParsingConstructor e) { this.mBuilder.enterScope(); // variable this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.callInvocationTarget(this.target_getPosition); VarEntry entry_startIndex = this.mBuilder.createNewVarAndStore(long.class); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.callInvocationTarget(this.target_markLogStack); VarEntry entry_mark = this.mBuilder.createNewVarAndStore(int.class); // new parsingObject Type parsingObjectTypeDesc = Type.getType(ParsingObject.class); this.mBuilder.newInstance(parsingObjectTypeDesc); this.mBuilder.dup(); this.newParsingTag("Text"); this.getFieldOfContext("source", ParsingSource.class); // call objectId this.mBuilder.loadFromVar(entry_startIndex); this.mBuilder.push(e.uniqueId); this.mBuilder.callStaticMethod(ParsingUtils.class, long.class, "objectId", long.class, short.class); this.mBuilder.invokeConstructor(parsingObjectTypeDesc, Methods.constructor(ParsingTag.class, ParsingSource.class, long.class)); VarEntry entry_newnode = this.mBuilder.createNewVarAndStore(ParsingObject.class); if(e.leftJoin) { this.mBuilder.loadFromVar(this.entry_context); this.getFieldOfContext("left", ParsingObject.class); this.mBuilder.callInstanceMethod(ParsingContext.class, void.class, "lazyJoin", ParsingObject.class); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.loadFromVar(entry_newnode); this.mBuilder.push(0); this.getFieldOfContext("left", ParsingObject.class); this.mBuilder.callInvocationTarget(this.target_lazyLink); } // put to context.left this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.loadFromVar(entry_newnode); this.mBuilder.putField(Type.getType(ParsingContext.class), "left", Type.getType(ParsingObject.class)); Label thenLabel = this.mBuilder.newLabel(); Label mergeLabel = this.mBuilder.newLabel(); for(int i = 0; i < e.size(); i++) { // only support prefetchIndex = 0 e.get(i).visit(this); this.mBuilder.push(true); this.mBuilder.ifCmp(Type.BOOLEAN_TYPE, GeneratorAdapter.NE, thenLabel); } // else this.mBuilder.loadFromVar(entry_newnode); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.callInvocationTarget(this.target_getPosition); this.mBuilder.loadFromVar(entry_startIndex); this.mBuilder.math(GeneratorAdapter.SUB, Type.LONG_TYPE); this.mBuilder.cast(Type.LONG_TYPE, Type.INT_TYPE); this.mBuilder.callInstanceMethod(ParsingObject.class, void.class, "setLength", int.class); // put to context.left this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.loadFromVar(entry_newnode); this.mBuilder.putField(Type.getType(ParsingContext.class), "left", Type.getType(ParsingObject.class)); // this.mBuilder.pushNull(); // this.mBuilder.storeToVar(entry_newnode); this.mBuilder.push(true); this.mBuilder.goTo(mergeLabel); // then this.mBuilder.mark(thenLabel); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.loadFromVar(entry_mark); this.mBuilder.callInvocationTarget(this.target_abortLog); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.loadFromVar(entry_startIndex); this.mBuilder.callInvocationTarget(this.target_rollback); // this.mBuilder.pushNull(); // this.mBuilder.storeToVar(entry_newnode); this.mBuilder.push(false); // merge this.mBuilder.mark(mergeLabel); this.mBuilder.exitScope(); } @Override public void visitWithFlag(ParsingWithFlag e) { final String flagName = e.getParameters().substring(1); if(ParsingIf.OldFlag) { this.mBuilder.enterScope(); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.push(flagName); this.mBuilder.callInvocationTarget(this.target_getFlag); VarEntry entry_currentFlag = this.mBuilder.createNewVarAndStore(boolean.class); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.push(flagName); this.mBuilder.push(true); this.mBuilder.callInvocationTarget(this.target_setFlag); e.inner.visit(this); VarEntry entry_res = this.mBuilder.createNewVarAndStore(boolean.class); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.push(flagName); this.mBuilder.loadFromVar(entry_currentFlag); this.mBuilder.callInvocationTarget(this.target_setFlag); this.mBuilder.loadFromVar(entry_res); this.mBuilder.exitScope(); return; } e.inner.visit(this); } @Override public void visitWithoutFlag(ParsingWithoutFlag e) { final String flagName = e.getParameters().substring(1); if(ParsingIf.OldFlag) { this.mBuilder.enterScope(); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.push(flagName); this.mBuilder.callInvocationTarget(this.target_getFlag); VarEntry entry_currentFlag = this.mBuilder.createNewVarAndStore(boolean.class); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.push(flagName); this.mBuilder.push(false); this.mBuilder.callInvocationTarget(this.target_setFlag); e.inner.visit(this); VarEntry entry_res = this.mBuilder.createNewVarAndStore(boolean.class); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.push(flagName); this.mBuilder.loadFromVar(entry_currentFlag); this.mBuilder.callInvocationTarget(this.target_setFlag); this.mBuilder.loadFromVar(entry_res); this.mBuilder.exitScope(); return; } e.inner.visit(this); } @Override public void visitRule(ParsingRule e) { // TODO Auto-generated method stub throw new RuntimeException("unimplemented visit method: " + e.getClass()); } @Override public void visitMatch(ParsingMatch e) { // TODO Auto-generated method stub throw new RuntimeException("unimplemented visit method: " + e.getClass()); } @Override public void visitCatch(ParsingCatch e) { // TODO Auto-generated method stub throw new RuntimeException("unimplemented visit method: " + e.getClass()); } @Override public void visitAssert(ParsingAssert e) { // TODO Auto-generated method stub throw new RuntimeException("unimplemented visit method: " + e.getClass()); } @Override public void visitIfFlag(ParsingIf e) { if(ParsingIf.OldFlag) { this.mBuilder.enterScope(); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.push(e.getParameters().substring(1)); this.mBuilder.callInstanceMethod(ParsingContext.class, boolean.class, "getFlag", String.class); VarEntry entry_f = this.mBuilder.createNewVarAndStore(boolean.class); Label thenLabel = this.mBuilder.newLabel(); Label mergeLabel = this.mBuilder.newLabel(); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.loadFromVar(entry_f); this.mBuilder.callInstanceMethod(ParsingContext.class, boolean.class, "isFlag", boolean.class); this.mBuilder.push(true); this.mBuilder.ifCmp(Type.BOOLEAN_TYPE, GeneratorAdapter.NE, thenLabel); this.mBuilder.goTo(mergeLabel); // then this.mBuilder.mark(thenLabel); this.generateFailure(); // merge this.mBuilder.mark(mergeLabel); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.callInstanceMethod(ParsingContext.class, boolean.class, "isFailure"); this.mBuilder.not(); this.mBuilder.exitScope(); return; } this.mBuilder.push(true); } @Override public void visitBlock(ParsingBlock e) { // TODO Auto-generated method stub throw new RuntimeException("unimplemented visit method: " + e.getClass()); } @Override public void visitName(ParsingName e) { this.mBuilder.enterScope(); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.callInvocationTarget(this.target_getPosition); VarEntry entry_startIndex = this.mBuilder.createNewVarAndStore(long.class); Label thenLabel = this.mBuilder.newLabel(); Label mergeLabel = this.mBuilder.newLabel(); this.mBuilder.push(true); e.inner.visit(this); this.mBuilder.ifCmp(Type.BOOLEAN_TYPE, GeneratorAdapter.EQ, thenLabel); this.mBuilder.push(false); this.mBuilder.goTo(mergeLabel); // then this.mBuilder.mark(thenLabel); { this.mBuilder.enterScope(); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.callInvocationTarget(this.target_getPosition); VarEntry entry_endIndex = this.mBuilder.createNewVarAndStore(long.class); this.getFieldOfContext("source", ParsingSource.class); this.mBuilder.loadFromVar(entry_startIndex); this.mBuilder.loadFromVar(entry_endIndex); this.mBuilder.callInstanceMethod(ParsingSource.class, String.class, "substring", long.class, long.class); VarEntry entry_s = this.mBuilder.createNewVarAndStore(String.class); this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.push(ParsingTag.tagId(e.getParameters().substring(1))); this.mBuilder.loadFromVar(entry_s); this.mBuilder.callInstanceMethod(ParsingContext.class, int.class, "pushTokenStack", int.class, String.class); this.mBuilder.pop(); this.mBuilder.push(true); this.mBuilder.exitScope(); } // merge this.mBuilder.mark(mergeLabel); this.mBuilder.exitScope(); } @Override public void visitIsa(ParsingIsa e) { this.mBuilder.loadFromVar(this.entry_context); this.mBuilder.push(ParsingTag.tagId(e.getParameters().substring(1))); this.mBuilder.callInstanceMethod(ParsingContext.class, boolean.class, "matchTokenStack", int.class); } @Override public void visitApply(ParsingApply e) { // TODO Auto-generated method stub throw new RuntimeException("unimplemented visit method: " + e.getClass()); } }
package kbasesearchengine.test.search; import static kbasesearchengine.test.common.TestCommon.set; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import com.google.common.collect.ImmutableList; import org.apache.commons.io.FileUtils; import org.apache.http.HttpHost; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import com.fasterxml.jackson.core.JsonParser; import com.google.common.collect.ImmutableMap; import junit.framework.Assert; import kbasesearchengine.common.GUID; import kbasesearchengine.common.ObjectJsonPath; import kbasesearchengine.events.exceptions.FatalIndexingException; import kbasesearchengine.events.exceptions.IndexingException; import kbasesearchengine.events.handler.SourceData; import kbasesearchengine.parse.IdMapper; import kbasesearchengine.parse.KeywordParser; import kbasesearchengine.parse.ObjectParseException; import kbasesearchengine.parse.ObjectParser; import kbasesearchengine.parse.ParsedObject; import kbasesearchengine.parse.SimpleIdConsumer; import kbasesearchengine.parse.SimpleSubObjectConsumer; import kbasesearchengine.parse.SubObjectConsumer; import kbasesearchengine.parse.KeywordParser.ObjectLookupProvider; import kbasesearchengine.search.AccessFilter; import kbasesearchengine.search.ElasticIndexingStorage; import kbasesearchengine.search.MatchFilter; import kbasesearchengine.search.MatchValue; import kbasesearchengine.search.ObjectData; import kbasesearchengine.search.PostProcessing; import kbasesearchengine.search.FoundHits; import kbasesearchengine.system.IndexingRules; import kbasesearchengine.system.ObjectTypeParsingRules; import kbasesearchengine.system.ObjectTypeParsingRulesFileParser; import kbasesearchengine.system.SearchObjectType; import kbasesearchengine.test.common.TestCommon; import kbasesearchengine.test.controllers.elasticsearch.ElasticSearchController; import kbasesearchengine.test.parse.SubObjectExtractorTest; import org.junit.rules.ExpectedException; import us.kbase.common.service.UObject; public class ElasticIndexingStorageTest { private static ElasticIndexingStorage indexStorage; private static File tempDir = null; private static ObjectLookupProvider objLookup; private static ElasticSearchController es; public ElasticIndexingStorageTest() { } @BeforeClass public static void prepare() throws Exception { TestCommon.stfuLoggers(); final Path tdir = Paths.get(TestCommon.getTempDir()); tempDir = tdir.resolve("ElasticIndexingStorageTest").toFile(); FileUtils.deleteQuietly(tempDir); es = new ElasticSearchController(TestCommon.getElasticSearchExe(), tdir); String indexNamePrefix = "test_" + System.currentTimeMillis() + "."; indexStorage = new ElasticIndexingStorage( new HttpHost("localhost", es.getServerPort()), tempDir); indexStorage.setIndexNamePrefix(indexNamePrefix); tempDir.mkdirs(); objLookup = new ObjectLookupProvider() { @Override public Set<GUID> resolveRefs(List<GUID> callerRefPath, Set<GUID> refs) { for (GUID pguid : refs) { try { boolean indexed = indexStorage.checkParentGuidsExist(new LinkedHashSet<>( Arrays.asList(pguid))).get(pguid); if (!indexed) { indexObject("Assembly", "assembly01", pguid, "MyAssembly.1"); indexObject("AssemblyContig", "assembly01", pguid, "MyAssembly.1"); Assert.assertTrue(indexStorage.checkParentGuidsExist(new LinkedHashSet<>( Arrays.asList(pguid))).get(pguid)); } } catch (Exception ex) { throw new IllegalStateException(ex); } } return refs; } @Override public Map<GUID, ObjectData> lookupObjectsByGuid(Set<GUID> guids) throws FatalIndexingException { List<ObjectData> objList; try { objList = indexStorage.getObjectsByIds(guids); } catch (IOException e) { throw new FatalIndexingException(e.getMessage(), e); } return objList.stream().collect( Collectors.toMap(od -> od.getGUID(), Function.identity())); } @Override public ObjectTypeParsingRules getTypeDescriptor(SearchObjectType type) { try { final File rulesFile = new File("resources/types/" + type.getType() + ".json"); return ObjectTypeParsingRulesFileParser.fromFile(rulesFile) .get(type.getVersion() - 1); } catch (Exception ex) { throw new IllegalStateException(ex); } } @Override public Map<GUID, SearchObjectType> getTypesForGuids(Set<GUID> guids) throws FatalIndexingException { PostProcessing pp = new PostProcessing(); pp.objectData = false; pp.objectKeys = false; pp.objectInfo = true; try { return indexStorage.getObjectsByIds(guids, pp).stream().collect( Collectors.toMap(od -> od.getGUID(), od -> od.getType().get())); } catch (IOException e) { throw new FatalIndexingException(e.getMessage(), e); } } }; } @After public void cleanup() throws Exception { indexStorage.dropData(); } @AfterClass public static void teardown() throws Exception { if (es != null) { es.destroy(TestCommon.getDeleteTempFiles()); } if (tempDir != null && tempDir.exists() && TestCommon.getDeleteTempFiles()) { FileUtils.deleteQuietly(tempDir); } } private static MatchFilter ft(String fullText) { return MatchFilter.create().withFullTextInAll(fullText); } private static void indexObject( final GUID id, final SearchObjectType objectType, final String json, final String objectName, final Instant timestamp, final String parentJsonValue, final boolean isPublic, final List<IndexingRules> indexingRules) throws IOException, ObjectParseException, IndexingException, InterruptedException { ParsedObject obj = KeywordParser.extractKeywords(objectType, json, parentJsonValue, indexingRules, objLookup, null); final SourceData data = SourceData.getBuilder(new UObject(json), objectName, "creator") .build(); indexStorage.indexObject(id, objectType, obj, data, timestamp, parentJsonValue, isPublic, indexingRules); } private static void indexObject(String type, String jsonResource, GUID ref, String objName) throws Exception { // yuck final String extension = type.equals("Genome") ? ".yaml" : ".json"; final File file = new File("resources/types/" + type + extension); ObjectTypeParsingRules parsingRules = ObjectTypeParsingRulesFileParser.fromFile(file).get(0); Map<ObjectJsonPath, String> pathToJson = new LinkedHashMap<>(); SubObjectConsumer subObjConsumer = new SimpleSubObjectConsumer(pathToJson); String parentJson = null; try (JsonParser jts = SubObjectExtractorTest.getParsedJsonResource(jsonResource)) { parentJson = ObjectParser.extractParentFragment(parsingRules, jts); } try (JsonParser jts = SubObjectExtractorTest.getParsedJsonResource(jsonResource)) { ObjectParser.extractSubObjects(parsingRules, subObjConsumer, jts); } for (ObjectJsonPath path : pathToJson.keySet()) { String subJson = pathToJson.get(path); SimpleIdConsumer idConsumer = new SimpleIdConsumer(); if (parsingRules.getSubObjectIDPath().isPresent()) { try (JsonParser subJts = UObject.getMapper().getFactory().createParser(subJson)) { IdMapper.mapKeys(parsingRules.getSubObjectIDPath().get(), subJts, idConsumer); } } GUID id = ObjectParser.prepareGUID(parsingRules, ref, path, idConsumer); indexObject(id, parsingRules.getGlobalObjectType(), subJson, objName, Instant.now(), parentJson, false, parsingRules.getIndexingRules()); } } private static ObjectData getIndexedObject(GUID guid) throws Exception { return indexStorage.getObjectsByIds(new LinkedHashSet<>(Arrays.asList(guid))).get(0); } @SuppressWarnings("unchecked") @Test public void testFeatures() throws Exception { indexObject("GenomeFeature", "genome01", new GUID("WS:1/1/1"), "MyGenome.1"); Map<String, Integer> typeToCount = indexStorage.searchTypes(ft("Rfah"), AccessFilter.create().withAdmin(true)); Assert.assertEquals(1, typeToCount.size()); List<String> type = ImmutableList.of(typeToCount.keySet().iterator().next()); Assert.assertEquals(1, (int)typeToCount.get(type.get(0))); GUID expectedGUID = new GUID("WS:1/1/1:feature/NewGenome.CDS.6210"); // Admin mode Set<GUID> ids = indexStorage.searchIds(type, ft("RfaH"), null, AccessFilter.create().withAdmin(true)); Assert.assertEquals(1, ids.size()); GUID id = ids.iterator().next(); Assert.assertEquals(expectedGUID, id); // Wrong groups ids = indexStorage.searchIds(type, ft("RfaH"), null, AccessFilter.create().withAccessGroups(2,3)); Assert.assertEquals(0, ids.size()); // Right groups Set<Integer> accessGroupIds = new LinkedHashSet<>(Arrays.asList(1, 2, 3)); ids = indexStorage.searchIds(type, ft("RfaH"), null, AccessFilter.create().withAccessGroups(accessGroupIds)); Assert.assertEquals(1, ids.size()); id = ids.iterator().next(); Assert.assertEquals(expectedGUID, id); // Check object loading by IDs List<ObjectData> objList = indexStorage.getObjectsByIds( new HashSet<>(Arrays.asList(id))); Assert.assertEquals(1, objList.size()); ObjectData featureIndex = objList.get(0); //System.out.println("GenomeFeature index: " + featureIndex); Map<String, Object> obj = (Map<String, Object>)featureIndex.getData().get(); Assert.assertTrue(obj.containsKey("id")); Assert.assertTrue(obj.containsKey("location")); Assert.assertTrue(obj.containsKey("function")); Assert.assertTrue(obj.containsKey("type")); Assert.assertEquals("NC_000913", featureIndex.getKeyProperties().get("contig_id")); String contigGuidText = featureIndex.getKeyProperties().get("contig_guid"); Assert.assertNotNull("missing contig_guid", contigGuidText); ObjectData contigIndex = getIndexedObject(new GUID(contigGuidText)); //System.out.println("AssemblyContig index: " + contigIndex); Assert.assertEquals("NC_000913", "" + contigIndex.getKeyProperties().get("contig_id")); // Search by keyword ids = indexStorage.searchIds(type, MatchFilter.create().withLookupInKey( "ontology_terms", "SSO:000008186"), null, AccessFilter.create().withAccessGroups(accessGroupIds)); Assert.assertEquals(1, ids.size()); id = ids.iterator().next(); Assert.assertEquals(expectedGUID, id); } @Test public void testGenome() throws Exception { System.out.println("*** start testGenome***"); indexObject("Genome", "genome01", new GUID("WS:1/1/1"), "MyGenome.1"); Set<GUID> guids = indexStorage.searchIds(ImmutableList.of("Genome"), MatchFilter.create().withLookupInKey( "features", new MatchValue(1, null)), null, AccessFilter.create().withAdmin(true)); Assert.assertEquals(1, guids.size()); ObjectData genomeIndex = indexStorage.getObjectsByIds(guids).get(0); //System.out.println("Genome index: " + genomeIndex); Assert.assertTrue(genomeIndex.getKeyProperties().containsKey("features")); Assert.assertEquals("3", "" + genomeIndex.getKeyProperties().get("features")); Assert.assertEquals("1", "" + genomeIndex.getKeyProperties().get("contigs")); String assemblyGuidText = genomeIndex.getKeyProperties().get("assembly_guid"); Assert.assertNotNull(assemblyGuidText); ObjectData assemblyIndex = getIndexedObject(new GUID(assemblyGuidText)); //System.out.println("Assembly index: " + genomeIndex); Assert.assertEquals("1", "" + assemblyIndex.getKeyProperties().get("contigs")); System.out.println("*** end testGenome***"); } @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void testMultiTypeSearchValidation1() throws Exception { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Invalid list of object types. List is null."); // null list of types Set<GUID> guids = indexStorage.searchIds(null, MatchFilter.create().withAccessGroupId(1), null, AccessFilter.create().withAdmin(true)); } @Test public void testMultiTypeSearchValidation2() throws Exception { indexObject("Genome", "genome01", new GUID("WS:1/1/1"), "MyGenome.1"); // empty list Set<GUID> guids = indexStorage.searchIds(new ArrayList<String>(), MatchFilter.create().withAccessGroupId(1), null, AccessFilter.create().withAdmin(true)); // genome object + 2 parent guids (see prepare) assertThat("incorrect number of results", guids.size(), is(3)); } @Test public void testMultiTypeSearchValidation3() throws Exception { expectedException.expect(IOException.class); expectedException.expectMessage("Invalid list of object types. Contains one or more null elements."); // list containing a mix of null and non-null types List<String> objectTypes = new ArrayList<>(); objectTypes.add(null); objectTypes.add("Narrative"); Set<GUID> guids = indexStorage.searchIds(objectTypes, MatchFilter.create().withAccessGroupId(1), null, AccessFilter.create().withAdmin(true)); } @Test public void testMultiTypeSearchValidation4() throws Exception { indexObject("Genome", "genome01", new GUID("WS:1/1/1"), "MyGenome.1"); List<String> objectTypes; Set<GUID> guids; // list with single non-null element objectTypes = new ArrayList<>(); objectTypes.add("Genome"); guids = indexStorage.searchIds(objectTypes, MatchFilter.create().withAccessGroupId(1), null, AccessFilter.create().withAdmin(true)); assertThat("incorrect number of results", guids.size(), is(1)); } @Test public void testMultiTypeSearchValidation5() throws Exception { expectedException.expect(IOException.class); expectedException.expectMessage("Invalid list of object types. List size exceeds maximum limit of 50"); // list exceeding max size List<String> objectTypes = new ArrayList<>(); for(int ii=0; ii< ElasticIndexingStorage.MAX_OBJECT_TYPES_SIZE+1; ii++) { objectTypes.add("Narrative"); } Set<GUID> guids = indexStorage.searchIds(objectTypes, MatchFilter.create().withAccessGroupId(1), null, AccessFilter.create().withAdmin(true)); } @Test public void testMultiTypeSearch() throws Exception { // search for Genome objects indexObject("Genome", "genome01", new GUID("WS:1/3/1"), "MyGenome.1"); Set<GUID> guids; guids = indexStorage.searchIds(ImmutableList.of("Genome"), MatchFilter.create().withAccessGroupId(1), null, AccessFilter.create().withAdmin(true)); assertThat("result missing expected object", guids.contains(GUID.fromRef("WS", "1/3/1")), is(true)); assertThat("incorrect number of objects in results", guids.size(), is(1)); // search for Genome and Assembly objects (assembly object from prepare method) guids = indexStorage.searchIds(ImmutableList.of("Genome", "Assembly"), MatchFilter.create().withAccessGroupId(1), null, AccessFilter.create().withAdmin(true)); assertThat("result missing expected object", guids.contains(GUID.fromRef("WS", "1/3/1")), is(true)); assertThat("result missing expected object", guids.contains(GUID.fromRef("WS", "1/2/1")), is(true)); assertThat("incorrect number of objects in results", guids.size(), is(2)); // search for Genome, Assembly and AssemblyContig objects (assembly and contig objects from prepare method) guids = indexStorage.searchIds(ImmutableList.of("Genome", "Assembly", "AssemblyContig"), MatchFilter.create().withAccessGroupId(1), null, AccessFilter.create().withAdmin(true)); assertThat("result missing expected object", guids.contains(GUID.fromRef("WS", "1/3/1")), is(true)); assertThat("result missing expected object", guids.contains(GUID.fromRef("WS", "1/2/1")), is(true)); assertThat("result missing expected object", guids.contains(GUID.fromRef("WS", "WS:1/2/1:contig/NC_000913")), is(true)); assertThat("incorrect number of objects in results", guids.size(), is(3)); } @Test public void testVersions() throws Exception { SearchObjectType objType = new SearchObjectType("Simple", 1); List<String> type = ImmutableList.of(objType.getType()); IndexingRules ir = IndexingRules.fromPath(new ObjectJsonPath("prop1")) .withFullText().build(); List<IndexingRules> indexingRules= Arrays.asList(ir); GUID id11 = new GUID("WS:2/1/1"); indexObject(id11, objType, "{\"prop1\":\"abc 123\"}", "obj.1", Instant.now(), null, false, indexingRules); checkIdInSet(indexStorage.searchIds(type, ft("abc"), null, AccessFilter.create().withAccessGroups(2)), 1, id11); GUID id2 = new GUID("WS:2/2/1"); indexObject(id2, objType, "{\"prop1\":\"abd\"}", "obj.2", Instant.now(), null, false, indexingRules); GUID id3 = new GUID("WS:3/1/1"); indexObject(id3, objType, "{\"prop1\":\"abc\"}", "obj.3", Instant.now(), null, false, indexingRules); checkIdInSet(indexStorage.searchIds(type, ft("abc"), null, AccessFilter.create().withAccessGroups(2)), 1, id11); GUID id12 = new GUID("WS:2/1/2"); indexObject(id12, objType, "{\"prop1\":\"abc 124\"}", "obj.1", Instant.now(), null, false, indexingRules); checkIdInSet(indexStorage.searchIds(type, ft("abc"), null, AccessFilter.create().withAccessGroups(2)), 1, id12); GUID id13 = new GUID("WS:2/1/3"); indexObject(id13, objType, "{\"prop1\":\"abc 125\"}", "obj.1", Instant.now(), null, false, indexingRules); //indexStorage.refreshIndex(indexStorage.getIndex(objType)); checkIdInSet(indexStorage.searchIds(type, ft("abc"), null, AccessFilter.create().withAccessGroups(2)), 1, id13); checkIdInSet(indexStorage.searchIds(type, ft("125"), null, AccessFilter.create().withAccessGroups(2)), 1, id13); Assert.assertEquals(0, indexStorage.searchIds(type, ft("123"), null, AccessFilter.create().withAccessGroups(2)).size()); checkIdInSet(indexStorage.searchIds(type, ft("abd"), null, AccessFilter.create().withAccessGroups(2)), 1, id2); checkIdInSet(indexStorage.searchIds(type, ft("abc"), null, AccessFilter.create().withAccessGroups(3)), 1, id3); // With all history Assert.assertEquals(1, indexStorage.searchIds(type, ft("123"), null, AccessFilter.create().withAccessGroups(2).withAllHistory(true)).size()); Assert.assertEquals(3, indexStorage.searchIds(type, ft("abc"), null, AccessFilter.create().withAccessGroups(2).withAllHistory(true)).size()); } private Set<GUID> lookupIdsByKey(List<String> objTypes, String keyName, Object value, AccessFilter af) throws IOException { Set<GUID> ret = indexStorage.searchIds(objTypes, MatchFilter.create().withLookupInKey( keyName, new MatchValue(value)), null, af); PostProcessing pp = new PostProcessing(); pp.objectInfo = true; pp.objectData = true; pp.objectKeys = true; indexStorage.getObjectsByIds(ret, pp); return ret; } @Test public void testSharing() throws Exception { SearchObjectType objType = new SearchObjectType("Sharable",1 ); List<String> type = ImmutableList.of(objType.getType()); IndexingRules ir = IndexingRules.fromPath(new ObjectJsonPath("prop2")) .withKeywordType("integer").build(); List<IndexingRules> indexingRules= Arrays.asList(ir); GUID id1 = new GUID("WS:10/1/1"); indexObject(id1, objType, "{\"prop2\": 123}", "obj.1", Instant.now(), null, false, indexingRules); GUID id2 = new GUID("WS:10/1/2"); indexObject(id2, objType, "{\"prop2\": 124}", "obj.1", Instant.now(), null, false, indexingRules); GUID id3 = new GUID("WS:10/1/3"); indexObject(id3, objType, "{\"prop2\": 125}", "obj.1", Instant.now(), null, false, indexingRules); AccessFilter af10 = AccessFilter.create().withAccessGroups(10); Assert.assertEquals(0, lookupIdsByKey(type, "prop2", 123, af10).size()); checkIdInSet(lookupIdsByKey(type, "prop2", 125, af10), 1, id3); indexStorage.shareObjects(new LinkedHashSet<>(Arrays.asList(id1)), 11, false); AccessFilter af11 = AccessFilter.create().withAccessGroups(11); checkIdInSet(lookupIdsByKey(type, "prop2", 123, af11), 1, id1); checkIdInSet(lookupIdsByKey(type, "prop2", 125, af10), 1, id3); Assert.assertEquals(0, lookupIdsByKey(type, "prop2", 124, af11).size()); checkIdInSet(lookupIdsByKey(type, "prop2", 124, AccessFilter.create().withAccessGroups(10).withAllHistory(true)), 1, id2); Assert.assertEquals(0, lookupIdsByKey(type, "prop2", 125, af11).size()); indexStorage.shareObjects(new LinkedHashSet<>(Arrays.asList(id2)), 11, false); Assert.assertEquals(0, lookupIdsByKey(type, "prop2", 123, af11).size()); checkIdInSet(lookupIdsByKey(type, "prop2", 124, af11), 1, id2); Assert.assertEquals(0, lookupIdsByKey(type, "prop2", 125, af11).size()); indexStorage.unshareObjects(new LinkedHashSet<>(Arrays.asList(id2)), 11); Assert.assertEquals(0, lookupIdsByKey(type, "prop2", 123, af11).size()); Assert.assertEquals(0, lookupIdsByKey(type, "prop2", 124, af11).size()); Assert.assertEquals(0, lookupIdsByKey(type, "prop2", 125, af11).size()); indexStorage.shareObjects(new LinkedHashSet<>(Arrays.asList(id1)), 11, false); indexStorage.shareObjects(new LinkedHashSet<>(Arrays.asList(id2)), 12, false); AccessFilter af1x = AccessFilter.create().withAccessGroups(11, 12); checkIdInSet(lookupIdsByKey(type, "prop2", 123, af1x), 1, id1); checkIdInSet(lookupIdsByKey(type, "prop2", 124, af1x), 1, id2); Assert.assertEquals(0, lookupIdsByKey(type, "prop2", 125, af1x).size()); indexStorage.unshareObjects(new LinkedHashSet<>(Arrays.asList(id1)), 11); Assert.assertEquals(0, lookupIdsByKey(type, "prop2", 123, af1x).size()); checkIdInSet(lookupIdsByKey(type, "prop2", 124, af1x), 1, id2); Assert.assertEquals(0, lookupIdsByKey(type, "prop2", 125, af1x).size()); indexStorage.unshareObjects(new LinkedHashSet<>(Arrays.asList(id2)), 12); Assert.assertEquals(0, lookupIdsByKey(type, "prop2", 123, af1x).size()); Assert.assertEquals(0, lookupIdsByKey(type, "prop2", 124, af1x).size()); Assert.assertEquals(0, lookupIdsByKey(type, "prop2", 125, af1x).size()); } @Test public void testPublic() throws Exception { SearchObjectType objType = new SearchObjectType("Publishable", 1); List<String> type = ImmutableList.of(objType.getType()); IndexingRules ir = IndexingRules.fromPath(new ObjectJsonPath("prop3")) .withFullText().build(); List<IndexingRules> indexingRules= Arrays.asList(ir); GUID id1 = new GUID("WS:20/1/1"); GUID id2 = new GUID("WS:20/2/1"); indexObject(id1, objType, "{\"prop3\": \"private gggg\"}", "obj.1", Instant.now(), null, false, indexingRules); indexObject(id2, objType, "{\"prop3\": \"public gggg\"}", "obj.2", Instant.now(), null, true, indexingRules); Assert.assertEquals(0, lookupIdsByKey(type, "prop3", "private", AccessFilter.create().withPublic(true)).size()); checkIdInSet(lookupIdsByKey(type, "prop3", "private", AccessFilter.create().withAccessGroups(20).withPublic(true)), 1, id1); Assert.assertEquals(0, lookupIdsByKey(type, "prop3", "private", AccessFilter.create().withAccessGroups(21).withPublic(true)).size()); checkIdInSet(lookupIdsByKey(type, "prop3", "public", AccessFilter.create().withAccessGroups(21).withPublic(true)), 1, id2); indexStorage.publishObjects(new LinkedHashSet<>(Arrays.asList(id1))); checkIdInSet(lookupIdsByKey(type, "prop3", "private", AccessFilter.create().withAccessGroups(20).withPublic(true)), 1, id1); checkIdInSet(lookupIdsByKey(type, "prop3", "private", AccessFilter.create().withAccessGroups(21).withPublic(true)), 1, id1); indexStorage.unpublishObjects(new LinkedHashSet<>(Arrays.asList(id1))); checkIdInSet(lookupIdsByKey(type, "prop3", "private", AccessFilter.create().withAccessGroups(20).withPublic(true)), 1, id1); Assert.assertEquals(0, lookupIdsByKey(type, "prop3", "private", AccessFilter.create().withAccessGroups(21).withPublic(true)).size()); checkIdInSet(lookupIdsByKey(type, "prop3", "public", AccessFilter.create().withAccessGroups(21).withPublic(true)), 1, id2); indexStorage.unpublishObjects(new LinkedHashSet<>(Arrays.asList(id2))); checkIdInSet(lookupIdsByKey(type, "prop3", "private", AccessFilter.create().withAccessGroups(20).withPublic(true)), 1, id1); checkIdInSet(lookupIdsByKey(type, "prop3", "public", AccessFilter.create().withAccessGroups(20).withPublic(true)), 1, id2); Assert.assertEquals(0, lookupIdsByKey(type, "prop3", "private", AccessFilter.create().withAccessGroups(21).withPublic(true)).size()); Assert.assertEquals(0, lookupIdsByKey(type, "prop3", "public", AccessFilter.create().withAccessGroups(21).withPublic(true)).size()); } private static Set<GUID> asSet(GUID... guids) { return new LinkedHashSet<>(Arrays.asList(guids)); } private static void checkIdInSet(Set<GUID> ids, int size, GUID id) { Assert.assertEquals("Set contains: " + ids, size, ids.size()); Assert.assertTrue("Set contains: " + ids, ids.contains(id)); } @Test public void testPublicDataPalettes() throws Exception { SearchObjectType objType = new SearchObjectType("ShareAndPublic", 1); List<String> type = ImmutableList.of(objType.getType()); IndexingRules ir = IndexingRules.fromPath(new ObjectJsonPath("prop4")) .withKeywordType("integer").build(); List<IndexingRules> indexingRules = Arrays.asList(ir); GUID id1 = new GUID("WS:30/1/1"); indexObject(id1, objType, "{\"prop4\": 123}", "obj.1", Instant.now(), null, false, indexingRules); AccessFilter af30 = AccessFilter.create().withAccessGroups(30); checkIdInSet(lookupIdsByKey(type, "prop4", 123, af30), 1, id1); AccessFilter afPub = AccessFilter.create().withPublic(true); Assert.assertEquals(0, lookupIdsByKey(type, "prop4", 123, afPub).size()); // Let's share object id1 with PUBLIC workspace 31 indexStorage.shareObjects(new LinkedHashSet<>(Arrays.asList(id1)), 31, true); // Should be publicly visible checkIdInSet(lookupIdsByKey(type, "prop4", 123, afPub), 1, id1); // Let's check that unshare (with no call to unpublishObjectsExternally is enough indexStorage.unshareObjects(new LinkedHashSet<>(Arrays.asList(id1)), 31); // Should NOT be publicly visible Assert.assertEquals(0, lookupIdsByKey(type, "prop4", 123, afPub).size()); // Let's share object id1 with NOT public workspace 31 indexStorage.shareObjects(new LinkedHashSet<>(Arrays.asList(id1)), 31, false); // Should NOT be publicly visible Assert.assertEquals(0, lookupIdsByKey(type, "prop4", 123, afPub).size()); // Now let's declare workspace 31 PUBLIC indexStorage.publishObjectsExternally(asSet(id1), 31); // Should be publicly visible checkIdInSet(lookupIdsByKey(type, "prop4", 123, afPub), 1, id1); // Now let's declare workspace 31 NOT public indexStorage.unpublishObjectsExternally(asSet(id1), 31); // Should NOT be publicly visible Assert.assertEquals(0, lookupIdsByKey(type, "prop4", 123, afPub).size()); } @Test public void testDeleteUndelete() throws Exception { SearchObjectType objType = new SearchObjectType("DelUndel", 1); List<String> type = ImmutableList.of(objType.getType()); IndexingRules ir = IndexingRules.fromPath(new ObjectJsonPath("myprop")) .withFullText().build(); List<IndexingRules> indexingRules= Arrays.asList(ir); GUID id1 = new GUID("WS:100/2/1"); GUID id2 = new GUID("WS:100/2/2"); indexObject(id1, objType, "{\"myprop\": \"some stuff\"}", "myobj", Instant.now(), null, false, indexingRules); indexObject(id2, objType, "{\"myprop\": \"some other stuff\"}", "myobj", Instant.now(), null, false, indexingRules); final AccessFilter filter = AccessFilter.create().withAccessGroups(100); final AccessFilter filterAllVers = AccessFilter.create().withAccessGroups(100) .withAllHistory(true); // check ids show up before delete assertThat("incorrect ids returned", lookupIdsByKey(type, "myprop", "some", filter), is(set(id2))); assertThat("incorrect ids returned", lookupIdsByKey(type, "myprop", "some", filterAllVers), is(set(id1, id2))); // check ids show up correctly after delete indexStorage.deleteAllVersions(id1); indexStorage.refreshIndexByType(objType); assertThat("incorrect ids returned", lookupIdsByKey(type, "myprop", "some", filter), is(set())); //TODO NOW these should probaby not show up assertThat("incorrect ids returned", lookupIdsByKey(type, "myprop", "some", filterAllVers), is(set(id1, id2))); // check ids restored after undelete indexStorage.undeleteAllVersions(id1); indexStorage.refreshIndexByType(objType); assertThat("incorrect ids returned", lookupIdsByKey(type, "myprop", "some", filter), is(set(id2))); assertThat("incorrect ids returned", lookupIdsByKey(type, "myprop", "some", filterAllVers), is(set(id1, id2))); /* This doesn't actually test that the access group id is removed from the access * doc AFAIK, but I don't think that matters. */ } @Test public void testPublishAllVersions() throws Exception { // tests the all versions method for setting objects public / non-public. SearchObjectType objType = new SearchObjectType("PublishAllVersions", 1); List<String> type = ImmutableList.of(objType.getType()); IndexingRules ir = IndexingRules.fromPath(new ObjectJsonPath("myprop")) .withFullText().build(); List<IndexingRules> indexingRules = Arrays.asList(ir); GUID id1 = new GUID("WS:200/2/1"); GUID id2 = new GUID("WS:200/2/2"); indexObject(id1, objType, "{\"myprop\": \"some stuff\"}", "myobj", Instant.now(), null, false, indexingRules); indexObject(id2, objType, "{\"myprop\": \"some other stuff\"}", "myobj", Instant.now(), null, false, indexingRules); final AccessFilter filter = AccessFilter.create() .withAllHistory(true).withPublic(false); final AccessFilter filterPublic = AccessFilter.create() .withAllHistory(true).withPublic(true); // check ids show up before publish assertThat("incorrect ids returned", lookupIdsByKey(type, "myprop", "some", filter), is(set())); assertThat("incorrect ids returned", lookupIdsByKey(type, "myprop", "some", filterPublic), is(set())); // check ids show up correctly after publish indexStorage.publishAllVersions(id1); indexStorage.refreshIndexByType(objType); assertThat("incorrect ids returned", lookupIdsByKey(type, "myprop", "some", filter), is(set())); //TODO NOW these should probaby not show up assertThat("incorrect ids returned", lookupIdsByKey(type, "myprop", "some", filterPublic), is(set(id1, id2))); // check ids hidden after unpublish indexStorage.unpublishAllVersions(id1); indexStorage.refreshIndexByType(objType); assertThat("incorrect ids returned", lookupIdsByKey(type, "myprop", "some", filter), is(set())); assertThat("incorrect ids returned", lookupIdsByKey(type, "myprop", "some", filterPublic), is(set())); } @Test public void testTypeVersions() throws Exception { /* test that types with incompatible fields but different versions index successfully. */ final SearchObjectType type1 = new SearchObjectType("TypeVers", 5); // changing 10 -> 5 makes the test fail due to elasticsearch exception final SearchObjectType type2 = new SearchObjectType("TypeVers", 10); final List<IndexingRules> idxRules1 = Arrays.asList( IndexingRules.fromPath(new ObjectJsonPath("bar")) .withKeywordType("integer").build()); final List<IndexingRules> idxRules2 = Arrays.asList( IndexingRules.fromPath(new ObjectJsonPath("bar")) .withKeywordType("keyword").build()); final Instant now = Instant.now(); indexObject(new GUID("WS:1/2/3"), type1, "{\"bar\": 1}", "o1", now, null, false, idxRules1); indexObject(new GUID("WS:4/5/6"), type2, "{\"bar\": \"whee\"}", "o2", now, null, false, idxRules2); final ObjectData indexedObj1 = indexStorage.getObjectsByIds(TestCommon.set(new GUID("WS:1/2/3"))).get(0); final ObjectData expected1 = ObjectData.getBuilder(new GUID("WS:1/2/3")) .withNullableObjectName("o1") .withNullableType(type1) .withNullableCreator("creator") .withNullableTimestamp(indexedObj1.getTimestamp().get()) .withNullableData(ImmutableMap.of("bar", 1)) .withKeyProperty("bar", "1") .build(); //due to potential truncation of timestamp on mac TestCommon.assertCloseMS(indexedObj1.getTimestamp().get(), now, 0, 10); assertThat("incorrect indexed object", indexedObj1, is(expected1)); final ObjectData indexedObj2 = indexStorage.getObjectsByIds(TestCommon.set(new GUID("WS:4/5/6"))).get(0); final ObjectData expected2 = ObjectData.getBuilder(new GUID("WS:4/5/6")) .withNullableObjectName("o2") .withNullableType(type2) .withNullableCreator("creator") .withNullableTimestamp(indexedObj2.getTimestamp().get()) .withNullableData(ImmutableMap.of("bar", "whee")) .withKeyProperty("bar", "whee") .build(); TestCommon.assertCloseMS(indexedObj2.getTimestamp().get(), now, 0, 10); assertThat("incorrect indexed object", indexedObj2, is(expected2)); } @Test public void noIndexingRules() throws Exception { indexStorage.indexObjects( new SearchObjectType("NoIndexingRules", 1), SourceData.getBuilder(new UObject(new HashMap<>()), "objname", "creator") .withNullableCommitHash("commit") .withNullableCopier("cop") .withNullableMD5("emmdeefive") .withNullableMethod("meth") .withNullableModule("mod") .withNullableVersion("ver") .build(), Instant.ofEpochMilli(10000), null, new GUID("WS:1000/1/1"), Collections.emptyMap(), false, Collections.emptyList()); final ObjectData indexedObj = indexStorage.getObjectsByIds(TestCommon.set(new GUID("WS:1000/1/1"))).get(0); final ObjectData expected = ObjectData.getBuilder(new GUID("WS:1000/1/1")) .withNullableObjectName("objname") .withNullableType(new SearchObjectType("NoIndexingRules", 1)) .withNullableCreator("creator") .withNullableCommitHash("commit") .withNullableCopier("cop") .withNullableMD5("emmdeefive") .withNullableMethod("meth") .withNullableModule("mod") .withNullableModuleVersion("ver") .withNullableTimestamp(Instant.ofEpochMilli(10000)) .build(); assertThat("incorrect indexed object", indexedObj, is(expected)); } private void prepareTestMultiwordSearch(GUID guid1, GUID guid2, GUID guid3) throws Exception { SearchObjectType objectType = new SearchObjectType("Simple", 1); IndexingRules ir = IndexingRules.fromPath(new ObjectJsonPath("prop1")) .withFullText().build(); List<IndexingRules> indexingRules = Arrays.asList(ir); indexObject(guid1, objectType, "{\"prop1\":\"multiWordInSearchMethod1 multiWordInSearchMethod2\"}", "multiword.1", Instant.now(), null, true, indexingRules); indexObject(guid2, objectType, "{\"prop1\":\"multiWordInSearchMethod2\"}", "multiword.2", Instant.now(), null, true, indexingRules); indexObject(guid3, objectType, "{\"prop1\":\"multiWordInSearchMethod1\"}", "multiword.3", Instant.now(), null, true, indexingRules); } @Test public void testMultiwordSearch() throws Exception{ GUID guid1 = new GUID("WS:11/1/2"); GUID guid2 = new GUID("WS:11/2/2"); GUID guid3 = new GUID("WS:11/3/2"); prepareTestMultiwordSearch(guid1, guid2, guid3); List<String> emtpy = new ArrayList<>(); final kbasesearchengine.search.MatchFilter filter = new kbasesearchengine.search.MatchFilter(); List<kbasesearchengine.search.SortingRule> sorting = null; AccessFilter accessFilter = AccessFilter.create().withAdmin(true); filter.withFullTextInAll("multiWordInSearchMethod1 multiWordInSearchMethod2"); FoundHits hits1 = indexStorage.searchObjects(emtpy, filter,sorting, accessFilter, null, null); filter.withFullTextInAll("multiWordInSearchMethod1"); FoundHits hits2 = indexStorage.searchObjects(emtpy, filter,sorting, accessFilter, null, null); filter.withFullTextInAll("multiWordInSearchMethod2"); FoundHits hits3 = indexStorage.searchObjects(emtpy, filter,sorting, accessFilter, null, null); assertThat("did not find object1", hits1.guids, is(set(guid1))); assertThat("did not find object1 and object3", hits2.guids, is(set(guid1,guid3))); assertThat("did not find object1 and object2", hits3.guids, is(set(guid1, guid2))); } private void prepareTestLookupInKey(GUID guid1, GUID guid2, GUID guid3) throws Exception { SearchObjectType objType = new SearchObjectType("SimpleNumber", 1 ); IndexingRules ir1 = IndexingRules.fromPath(new ObjectJsonPath("num1")) .withKeywordType("integer").build(); IndexingRules ir2 = IndexingRules.fromPath(new ObjectJsonPath("num2")) .withKeywordType("integer").build(); List<IndexingRules> indexingRules= Arrays.asList(ir1, ir2); indexObject(guid1, objType, "{\"num1\": 123, \"num2\": 123}", "number.1", Instant.now(), null, false, indexingRules); indexObject(guid2, objType, "{\"num1\": 1234, \"num2\": 1234}", "number.2", Instant.now(), null, false, indexingRules); indexObject(guid3, objType, "{\"num1\": 1236, \"num2\": 1236}", "number.3", Instant.now(), null, false, indexingRules); } @Test public void testLookupInKey() throws Exception{ GUID guid1 = new GUID("WS:12/1/2"); GUID guid2 = new GUID("WS:12/2/2"); GUID guid3 = new GUID("WS:12/3/2"); prepareTestLookupInKey(guid1, guid2, guid3); List<String> emtpy = new ArrayList<>(); List<kbasesearchengine.search.SortingRule> sorting = null; AccessFilter accessFilter = AccessFilter.create().withAdmin(true); //key, value pair lookup MatchFilter filter0 = MatchFilter.create().withLookupInKey( "num1", "123"); FoundHits hits0 = indexStorage.searchObjects(emtpy, filter0,sorting, accessFilter , null, null); assertThat("did not find object1 using LookupInKey with value", hits0.guids, is(set(guid1))); //key, range lookup MatchValue range1 = new MatchValue(100, 200); MatchValue range2 = new MatchValue(1000, 2000); MatchValue range3 = new MatchValue(100, 1234); MatchFilter filter1 = MatchFilter.create().withLookupInKey("num1", range1); MatchFilter filter2 = MatchFilter.create().withLookupInKey("num2", range2); MatchFilter filter3 = MatchFilter.create().withLookupInKey("num1", range3); FoundHits hits1 = indexStorage.searchObjects(emtpy, filter1,sorting, accessFilter, null, null); FoundHits hits2 = indexStorage.searchObjects(emtpy, filter2,sorting, accessFilter, null, null); FoundHits hits3 = indexStorage.searchObjects(emtpy, filter3,sorting, accessFilter, null, null); assertThat("did not find object1 using LookupInKey with range", hits1.guids, is(set(guid1))); assertThat("did not find object2 and object3 using LookupInKey with range", hits2.guids, is(set(guid2, guid3))); assertThat("did not find object1 and object3 using LookupInKey with range", hits3.guids, is(set(guid1, guid2))); //conflicting filters should return nothing MatchFilter filter4 = MatchFilter.create().withLookupInKey("num1", range1); filter4.withLookupInKey("num2", range2); FoundHits hits4 = indexStorage.searchObjects(emtpy, filter4,sorting, accessFilter, null, null); assertThat("conflicting ranges should produce 0 results", hits4.guids.isEmpty(), is(true)); // overlapping filters should return intersection MatchFilter filter5 = MatchFilter.create().withLookupInKey("num1", range3); filter5.withLookupInKey("num2", range2); FoundHits hits5 = indexStorage.searchObjects(emtpy, filter5,sorting, accessFilter , null, null); assertThat("overlapping ranges did not return intersection", hits5.guids, is(set(guid2))); } }
package org.xins.common.manageable; import org.xins.common.MandatoryArgumentChecker; import org.xins.common.collections.InvalidPropertyValueException; import org.xins.common.collections.MissingRequiredPropertyException; import org.xins.common.collections.PropertyReader; import org.xins.common.collections.PropertyReaderUtils; /** * Abstraction of a manageable object. Abstract base class for classes that * support bootstrap, initialization and destruction functions. * * <p>In environments where <code>Manageable</code> instances are constructed * dynamically, they are typically expected to have a public no-argument * constructor. * * <p>The {@link #bootstrap(PropertyReader)} method should be called exactly * once before initializing and using this object. * * <p>After that the {@link #init(PropertyReader)} method should be called to * initialize or re-initialize this object. This should be done at least once * before this object can be used. This method should only be called after * {@link #bootstrap(PropertyReader)}. * * <p>The {@link #deinit()} method will be called when this object is no * longer needed. After that, {@link #bootstrap(PropertyReader)} could be * called again, though. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>) * * @since XINS 1.0.0 */ public abstract class Manageable extends Object { // Class fields /** * The <em>UNUSABLE</em> state. */ public static final State UNUSABLE = new State("UNUSABLE"); /** * The <em>BOOTSTRAPPING</em> state. */ public static final State BOOTSTRAPPING = new State("BOOTSTRAPPING"); /** * The <em>BOOTSTRAPPED</em> state. */ public static final State BOOTSTRAPPED = new State("BOOTSTRAPPED"); /** * The <em>INITIALIZING</em> state. */ public static final State INITIALIZING = new State("INITIALIZING"); /** * The <em>USABLE</em> state. */ public static final State USABLE = new State("USABLE"); /** * The <em>DEINITIALIZING</em> state. */ public static final State DEINITIALIZING = new State("DEINITIALIZING"); // Class functions // Constructors /** * Constructs a new <code>Manageable</code>. */ protected Manageable() { _state = UNUSABLE; _stateLock = new Object(); } // Fields /** * The state of this manageable object. */ private State _state; /** * The lock for the state object. */ private Object _stateLock; // Methods /** * Gets the current state of this object * * @return * the current state, never <code>null</code>. */ public final State getState() { return _state; } public final void bootstrap(PropertyReader properties) throws IllegalStateException, MissingRequiredPropertyException, InvalidPropertyValueException, BootstrapException { // TODO: Log State erroneousState = null; // Get the current state and change to BOOTSTRAPPING if it is valid synchronized (_stateLock) { if (_state != UNUSABLE) { erroneousState = _state; } else { _state = BOOTSTRAPPING; } } // If the state was invalid, then fail if (erroneousState != null) { final String MESSAGE = "The current state is " + erroneousState + " instead of UNUSABLE."; throw new IllegalStateException(MESSAGE); } // If no properties are passed, then use an empty set if (properties == null) { properties = PropertyReaderUtils.EMPTY_PROPERTY_READER; } // Delegate to subclass boolean done = false; try { bootstrapImpl(properties); done = true; // Catch expected exceptions } catch (MissingRequiredPropertyException exception) { throw exception; } catch (InvalidPropertyValueException exception) { throw exception; } catch (BootstrapException exception) { throw exception; // Wrap other exceptions in an InitializationException } catch (Throwable exception) { throw new BootstrapException(exception); // Always set the state before returning } finally { synchronized (_stateLock) { if (done) { _state = BOOTSTRAPPED; } else { _state = UNUSABLE; } } } } /** * Performs the bootstrap procedure (actual implementation). When this * method is called from {@link #bootstrap(PropertyReader)}, the state and * the argument will have been checked and the state will have been set to * {@link #BOOTSTRAPPING}. * * <p>The implementation of this method in class {@link Manageable} is * empty. * * @param properties * the bootstrap properties, not <code>null</code>. * * @throws MissingRequiredPropertyException * if a required property is not given. * * @throws InvalidPropertyValueException * if the value of a certain property is invalid. * * @throws BootstrapException * if the bootstrapping failed for any other reason. */ protected void bootstrapImpl(PropertyReader properties) throws MissingRequiredPropertyException, InvalidPropertyValueException, BootstrapException { // empty } public final void init(PropertyReader properties) throws IllegalStateException, MissingRequiredPropertyException, InvalidPropertyValueException, InitializationException { State erroneousState = null; // Get the current state and change to INITIALIZING if it is valid synchronized (_stateLock) { if (_state != BOOTSTRAPPED && _state != USABLE) { erroneousState = _state; } else { _state = INITIALIZING; } } // If the state was invalid, then fail if (erroneousState != null) { throw new IllegalStateException("The current state is " + erroneousState + " instead of either " + BOOTSTRAPPED + " or " + USABLE + '.'); } // If no properties are passed, then use an empty set if (properties == null) { properties = PropertyReaderUtils.EMPTY_PROPERTY_READER; } // Delegate to subclass boolean done = false; try { initImpl(properties); done = true; // Catch expected exceptions } catch (MissingRequiredPropertyException exception) { throw exception; } catch (InvalidPropertyValueException exception) { throw exception; } catch (InitializationException exception) { throw exception; // Wrap other exceptions in an InitializationException } catch (Throwable exception) { throw new InitializationException(exception); // Always set the state before returning } finally { synchronized (_stateLock) { if (done) { _state = USABLE; } else { _state = BOOTSTRAPPED; } } } } /** * Performs the initialization procedure (actual implementation). When this * method is called from {@link #init(PropertyReader)}, the state and the * argument will have been checked and the state will have been set to * {@link #INITIALIZING}. * * <p>The implementation of this method in class {@link Manageable} is * empty. * * @param properties * the initialization properties, not <code>null</code>. * * @throws MissingRequiredPropertyException * if a required property is not given. * * @throws InvalidPropertyValueException * if the value of a certain property is invalid. * * @throws InitializationException * if the initialization failed, for any other reason. */ protected void initImpl(PropertyReader properties) throws MissingRequiredPropertyException, InvalidPropertyValueException, InitializationException { // empty } public final void deinit() throws IllegalStateException, DeinitializationException { State erroneousState = null; // Get the current state and change to DEINITIALIZING if it is valid synchronized (_stateLock) { if (_state != BOOTSTRAPPED && _state != USABLE) { erroneousState = _state; } else { _state = DEINITIALIZING; } } // If the state was invalid, then fail if (erroneousState != null) { throw new IllegalStateException("The current state is " + erroneousState + " instead of either " + BOOTSTRAPPED + " or " + USABLE + '.'); } // Delegate to subclass boolean done = false; try { deinitImpl(); done = true; // Catch and wrap all caught exceptions } catch (Throwable exception) { throw new DeinitializationException(exception); // Always set the state before returning } finally { synchronized (_stateLock) { if (done) { _state = UNUSABLE; } else { _state = BOOTSTRAPPED; } } } } /** * Deinitializes this instance (actual implementation). This method will be * called from {@link #deinit()} each time the latter is called and it * finds that the state is correct. The state will have been set to * {@link #DEINITIALIZING}. * * @throws Throwable * if the deinitialization caused an exception. */ protected void deinitImpl() throws Throwable { // empty } protected final void assertUsable() throws IllegalStateException { boolean usable; // Minimize the time the lock is held synchronized (_stateLock) { usable = (_state == USABLE); } // Construct and throw an exception, if appropriate if (!usable) { throw new IllegalStateException("The current state is " + _state + " instead of " + USABLE + '.'); } } // Inner classes /** * State of a <code>Manageable</code> object. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:ernst.dehaan@nl.wanadoo.com">ernst.dehaan@nl.wanadoo.com</a>) * * @since XINS 1.0.0 */ public static final class State extends Object { // Constructors private State(String name) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("name", name); _name = name; } // Fields /** * The name of this state. Cannot be <code>null</code>. */ private final String _name; // Methods /** * Returns the name of this state. * * @return * the name of this state, cannot be <code>null</code>. */ public String getName() { return _name; } /** * Returns a textual representation of this object. * * @return * the name of this state, never <code>null</code>. */ public String toString() { return _name; } } }
package org.jaxen.function.ext; import java.util.Collections; import java.util.Iterator; import java.util.List; import org.jaxen.BaseXPath; import org.jaxen.Context; import org.jaxen.ContextSupport; import org.jaxen.Function; import org.jaxen.Navigator; import org.jaxen.FunctionCallException; import org.jaxen.function.StringFunction; import org.saxpath.SAXPathException; /** * <code><i>node-set</i> evaluate(<i>string</i>)</code> * * @author Erwin Bolwidt (ejb @ klomp.org) */ public class EvaluateFunction implements Function { public Object call( Context context, List args ) throws FunctionCallException { if ( args.size() == 1 ) { return evaluate( context, args.get(0)); } throw new FunctionCallException( "id() requires one argument" ); } public static List evaluate (Context context, Object arg) throws FunctionCallException { List contextNodes = context.getNodeSet(); if (contextNodes.size() == 0) return Collections.EMPTY_LIST; Object contextNode = contextNodes.get(0); Navigator nav = context.getNavigator(); String xpathString; if ( arg instanceof String ) xpathString = (String)arg; else xpathString = StringFunction.evaluate(arg, nav); try { BaseXPath xpath = nav.parseXPath(xpathString); ContextSupport support = context.getContextSupport(); xpath.setVariableContext( support.getVariableContext() ); xpath.setFunctionContext( support.getFunctionContext() ); xpath.setNamespaceContext( support.getNamespaceContext() ); return xpath.selectNodes( context.duplicate() ); } catch ( SAXPathException e ) { throw new FunctionCallException(e.toString()); } } }
package org.jsmpp.session; import org.jsmpp.bean.DeliverSm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ClientResponseHandler { private static final Logger logger = LoggerFactory.getLogger(ClientResponseHandler.class); public void processDeliverSm(ClientSession session, DeliverSm deliverSm) { if (session.getMessageReceiverListener() != null) { session.getMessageReceiverListener().onAcceptDeliverSm(deliverSm); session.getPDUSender().sendDeliverSmResp(deliverSm); } else { logger.info("Message received to ClientResponseHandler, but MessageReceiverListener is not set"); } } }
package org.jivesoftware.sparkimpl.settings; public class JiveInfo { private JiveInfo() { } public static String getVersion() { return "2.0.1"; } public static String getOS() { return System.getProperty("os.name"); } }
package org.jdesktop.swingx; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Container; import java.awt.LayoutManager; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.Action; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.UIManager; import org.jdesktop.beans.JavaBean; import org.jdesktop.swingx.plaf.LookAndFeelAddons; import org.jdesktop.swingx.plaf.TaskPaneAddon; import org.jdesktop.swingx.plaf.TaskPaneUI; /** * <code>JXTaskPane</code> is a container for tasks and other * arbitrary components. * * <p> * Several <code>JXTaskPane</code>s are usually grouped together within a * {@link org.jdesktop.swingx.JXTaskPaneContainer}. However it is not mandatory * to use a JXTaskPaneContainer as the parent for JXTaskPane. The JXTaskPane can * be added to any other container. See * {@link org.jdesktop.swingx.JXTaskPaneContainer} to understand the benefits of * using it as the parent container. * * <p> * <code>JXTaskPane</code> provides control to expand and * collapse the content area in order to show or hide the task list. It can have an * <code>icon</code>, a <code>title</code> and can be marked as * <code>special</code>. Marking a <code>JXTaskPane</code> as * <code>special</code> ({@link #setSpecial(boolean)} is only a hint for * the pluggable UI which will usually paint it differently (by example by * using another color for the border of the pane). * * <p> * When the JXTaskPane is expanded or collapsed, it will be * animated with a fade effect. The animated can be disabled on a per * component basis through {@link #setAnimated(boolean)}. * * To disable the animation for all newly created <code>JXTaskPane</code>, * use the UIManager property: * <code>UIManager.put("TaskPane.animate", Boolean.FALSE);</code>. * * <p> * Example: * <pre> * <code> * JXFrame frame = new JXFrame(); * * // a container to put all JXTaskPane together * JXTaskPaneContainer taskPaneContainer = new JXTaskPaneContainer(); * * // create a first taskPane with common actions * JXTaskPane actionPane = new JXTaskPane(); * actionPane.setTitle("Files and Folders"); * actionPane.setSpecial(true); * * // actions can be added, a hyperlink will be created * Action renameSelectedFile = createRenameFileAction(); * actionPane.add(renameSelectedFile); * actionPane.add(createDeleteFileAction()); * * // add this taskPane to the taskPaneContainer * taskPaneContainer.add(actionPane); * * // create another taskPane, it will show details of the selected file * JXTaskPane details = new JXTaskPane(); * details.setTitle("Details"); * * // add standard components to the details taskPane * JLabel searchLabel = new JLabel("Search:"); * JTextField searchField = new JTextField(""); * details.add(searchLabel); * details.add(searchField); * * taskPaneContainer.add(details); * * // put the action list on the left * frame.add(taskPaneContainer, BorderLayout.EAST); * * // and a file browser in the middle * frame.add(fileBrowser, BorderLayout.CENTER); * * frame.pack(); * frame.setVisible(true); * </code> * </pre> * * @see org.jdesktop.swingx.JXTaskPaneContainer * @see org.jdesktop.swingx.JXCollapsiblePane * @author <a href="mailto:fred@L2FProd.com">Frederic Lavigne</a> * @author Karl George Schaefer * * @javabean.attribute * name="isContainer" * value="Boolean.TRUE" * rtexpr="true" * * @javabean.attribute * name="containerDelegate" * value="getContentPane" * * @javabean.class * name="JXTaskPane" * shortDescription="JXTaskPane is a container for tasks and other arbitrary components." * stopClass="java.awt.Component" * * @javabean.icons * mono16="JXTaskPane16-mono.gif" * color16="JXTaskPane16.gif" * mono32="JXTaskPane32-mono.gif" * color32="JXTaskPane32.gif" */ @JavaBean @SuppressWarnings("nls") public class JXTaskPane extends JPanel implements JXCollapsiblePane.CollapsiblePaneContainer, Mnemonicable { /** * JXTaskPane pluggable UI key <i>swingx/TaskPaneUI</i> */ public final static String uiClassID = "swingx/TaskPaneUI"; // ensure at least the default ui is registered static { LookAndFeelAddons.contribute(new TaskPaneAddon()); } /** * Used when generating PropertyChangeEvents for the "scrollOnExpand" property */ public static final String SCROLL_ON_EXPAND_CHANGED_KEY = "scrollOnExpand"; /** * Used when generating PropertyChangeEvents for the "title" property */ public static final String TITLE_CHANGED_KEY = "title"; /** * Used when generating PropertyChangeEvents for the "icon" property */ public static final String ICON_CHANGED_KEY = "icon"; /** * Used when generating PropertyChangeEvents for the "special" property */ public static final String SPECIAL_CHANGED_KEY = "special"; /** * Used when generating PropertyChangeEvents for the "animated" property */ public static final String ANIMATED_CHANGED_KEY = "animated"; private String title; private Icon icon; private boolean special; private boolean scrollOnExpand; private int mnemonic; private int mnemonicIndex = -1; private JXCollapsiblePane collapsePane; /** * Creates a new empty <code>JXTaskPane</code>. */ public JXTaskPane() { this((String) null); } /** * Creates a new task pane with the specified title. * * @param title * the title to use */ public JXTaskPane(String title) { this(title, null); } /** * Creates a new task pane with the specified icon. * * @param icon * the icon to use */ public JXTaskPane(Icon icon) { this(null, icon); } /** * Creates a new task pane with the specified title and icon. * * @param title * the title to use * @param icon * the icon to use */ public JXTaskPane(String title, Icon icon) { collapsePane = new JXCollapsiblePane(); super.setLayout(new BorderLayout(0, 0)); super.addImpl(collapsePane, BorderLayout.CENTER, -1); setTitle(title); setIcon(icon); updateUI(); setFocusable(true); // disable animation if specified in UIManager setAnimated(!Boolean.FALSE.equals(UIManager.get("TaskPane.animate"))); // listen for animation events and forward them to registered listeners collapsePane.addPropertyChangeListener("collapsed", new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { JXTaskPane.this.firePropertyChange(evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); } }); } /** * Returns the contentPane object for this JXTaskPane. * @return the contentPane property */ public Container getContentPane() { return collapsePane.getContentPane(); } /** * Notification from the <code>UIManager</code> that the L&F has changed. * Replaces the current UI object with the latest version from the <code>UIManager</code>. * * @see javax.swing.JComponent#updateUI */ @Override public void updateUI() { // collapsePane is null when updateUI() is called by the "super()" // constructor if (collapsePane == null) { return; } setUI((TaskPaneUI)LookAndFeelAddons.getUI(this, TaskPaneUI.class)); } /** * Sets the L&F object that renders this component. * * @param ui the <code>TaskPaneUI</code> L&F object * @see javax.swing.UIDefaults#getUI * * @beaninfo bound: true hidden: true description: The UI object that * implements the taskpane group's LookAndFeel. */ public void setUI(TaskPaneUI ui) { super.setUI(ui); } /** * Returns the name of the L&F class that renders this component. * * @return the string {@link #uiClassID} * @see javax.swing.JComponent#getUIClassID * @see javax.swing.UIDefaults#getUI */ @Override public String getUIClassID() { return uiClassID; } /** * Returns the title currently displayed in the border of this pane. * * @return the title currently displayed in the border of this pane */ public String getTitle() { return title; } /** * Sets the title to be displayed in the border of this pane. * * @param title the title to be displayed in the border of this pane * @javabean.property * bound="true" * preferred="true" */ public void setTitle(String title) { String old = this.title; this.title = title; firePropertyChange(TITLE_CHANGED_KEY, old, title); } /** * Returns the icon currently displayed in the border of this pane. * * @return the icon currently displayed in the border of this pane */ public Icon getIcon() { return icon; } /** * Sets the icon to be displayed in the border of this pane. Some pluggable * UIs may impose size constraints for the icon. A size of 16x16 pixels is * the recommended icon size. * * @param icon the icon to be displayed in the border of this pane * @javabean.property * bound="true" * preferred="true" */ public void setIcon(Icon icon) { Icon old = this.icon; this.icon = icon; firePropertyChange(ICON_CHANGED_KEY, old, icon); } /** * Returns true if this pane is "special". * * @return true if this pane is "special" * @see #setSpecial(boolean) */ public boolean isSpecial() { return special; } /** * Sets this pane to be "special" or not. Marking a <code>JXTaskPane</code> * as <code>special</code> is only a hint for the pluggable UI which will * usually paint it differently (by example by using another color for the * border of the pane). * * <p> * Usually the first JXTaskPane in a JXTaskPaneContainer is marked as special * because it contains the default set of actions which can be executed given * the current context. * * @param special * true if this pane is "special", false otherwise * @javabean.property bound="true" preferred="true" */ public void setSpecial(boolean special) { boolean oldValue = isSpecial(); this.special = special; firePropertyChange(SPECIAL_CHANGED_KEY, oldValue, isSpecial()); } /** * Should this group be scrolled to be visible on expand. * * @param scrollOnExpand true to scroll this group to be * visible if this group is expanded. * * @see #setCollapsed(boolean) * * @javabean.property * bound="true" * preferred="true" */ public void setScrollOnExpand(boolean scrollOnExpand) { boolean oldValue = isScrollOnExpand(); this.scrollOnExpand = scrollOnExpand; firePropertyChange(SCROLL_ON_EXPAND_CHANGED_KEY, oldValue, isScrollOnExpand()); } /** * Should this group scroll to be visible after * this group was expanded. * * @return true if we should scroll false if nothing * should be done. */ public boolean isScrollOnExpand() { return scrollOnExpand; } /** * Expands or collapses this group. * <p> * As of SwingX 1.6.3, the property change event only fires when the * state is accurate. As such, animated task panes fire once the * animation is complete. * * @param collapsed * true to collapse the group, false to expand it * @javabean.property * bound="true" * preferred="false" */ public void setCollapsed(boolean collapsed) { collapsePane.setCollapsed(collapsed); } /** * Returns the collapsed state of this task pane. * * @return {@code true} if the task pane is collapsed; {@code false} * otherwise */ public boolean isCollapsed() { return collapsePane.isCollapsed(); } /** * Enables or disables animation during expand/collapse transition. * * @param animated * @javabean.property * bound="true" * preferred="true" */ public void setAnimated(boolean animated) { boolean oldValue = isAnimated(); collapsePane.setAnimated(animated); firePropertyChange(ANIMATED_CHANGED_KEY, oldValue, isAnimated()); } /** * Returns true if this task pane is animated during expand/collapse * transition. * * @return true if this task pane is animated during expand/collapse * transition. */ public boolean isAnimated() { return collapsePane.isAnimated(); } /** * {@inheritDoc} * <p> * If the character defined by the mnemonic is found within the task pane's * text string, the first occurrence of it will be underlined to indicate * the mnemonic to the user. */ @Override public int getMnemonic() { return mnemonic; } /** * {@inheritDoc} */ @Override public void setMnemonic(int mnemonic) { int oldValue = getMnemonic(); this.mnemonic = mnemonic; firePropertyChange("mnemonic", oldValue, getMnemonic()); updateDisplayedMnemonicIndex(getTitle(), mnemonic); revalidate(); repaint(); } /** * Update the displayedMnemonicIndex property. This method * is called when either text or mnemonic changes. The new * value of the displayedMnemonicIndex property is the index * of the first occurrence of mnemonic in text. */ private void updateDisplayedMnemonicIndex(String text, int mnemonic) { if (text == null || mnemonic == '\0') { mnemonicIndex = -1; return; } char uc = Character.toUpperCase((char)mnemonic); char lc = Character.toLowerCase((char)mnemonic); int uci = text.indexOf(uc); int lci = text.indexOf(lc); if (uci == -1) { mnemonicIndex = lci; } else if(lci == -1) { mnemonicIndex = uci; } else { mnemonicIndex = (lci < uci) ? lci : uci; } } /** * {@inheritDoc} */ @Override public int getDisplayedMnemonicIndex() { return mnemonicIndex; } /** * {@inheritDoc} */ @Override public void setDisplayedMnemonicIndex(int index) throws IllegalArgumentException { int oldValue = mnemonicIndex; if (index == -1) { mnemonicIndex = -1; } else { String text = getTitle(); int textLength = (text == null) ? 0 : text.length(); if (index < -1 || index >= textLength) { // index out of range throw new IllegalArgumentException("index == " + index); } } mnemonicIndex = index; firePropertyChange("displayedMnemonicIndex", oldValue, index); if (index != oldValue) { revalidate(); repaint(); } } /** * Adds an action to this <code>JXTaskPane</code>. Returns a * component built from the action. The returned component has been * added to the <code>JXTaskPane</code>. * * @param action * @return a component built from the action */ public Component add(Action action) { Component c = ((TaskPaneUI)ui).createAction(action); add(c); return c; } /** * @see JXCollapsiblePane.CollapsiblePaneContainer */ @Override public Container getValidatingContainer() { return getParent(); } /** * Overridden to redirect call to the content pane. */ @Override protected void addImpl(Component comp, Object constraints, int index) { getContentPane().add(comp, constraints, index); //Fixes SwingX #364; adding to internal component we need to revalidate ourself revalidate(); } /** * Overridden to redirect call to the content pane. */ @Override public void setLayout(LayoutManager mgr) { if (collapsePane != null) { getContentPane().setLayout(mgr); } } /** * Overridden to redirect call to the content pane */ @Override public void remove(Component comp) { getContentPane().remove(comp); } /** * Overridden to redirect call to the content pane. */ @Override public void remove(int index) { getContentPane().remove(index); } /** * Overridden to redirect call to the content pane. */ @Override public void removeAll() { getContentPane().removeAll(); } /** * @see JComponent#paramString() */ @Override protected String paramString() { return super.paramString() + ",title=" + getTitle() + ",icon=" + getIcon() + ",collapsed=" + String.valueOf(isCollapsed()) + ",special=" + String.valueOf(isSpecial()) + ",scrollOnExpand=" + String.valueOf(isScrollOnExpand()) + ",ui=" + getUI(); } }
package acmi.l2.clientmod.io; import java.io.EOFException; import java.io.UncheckedIOException; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.Arrays; public class RandomAccessMemory implements RandomAccess { private static final int DEFAULT_CAPACITY = 1 << 16; private final String name; private final Charset charset; private ByteBuffer buffer; public RandomAccessMemory(String name, byte[] data, Charset charset) { this.name = name; this.buffer = ByteBuffer.wrap(data); this.charset = charset; } public RandomAccessMemory(String name, Charset charset) { this(name, new byte[DEFAULT_CAPACITY], charset); } @Override public String getName() { return name; } @Override public Charset getCharset() { return charset; } @Override public int getPosition() { return buffer.position(); } @Override public void setPosition(int position) { ensureCapacity(position); buffer.position(position); } @Override public void trimToPosition() { buffer.limit(buffer.position()); } @Override public int readUnsignedByte() throws UncheckedIOException { if (buffer.position() >= buffer.limit()) throw new UncheckedIOException(new EOFException()); return buffer.get() & 0xff; } @Override public void readFully(byte[] b, int off, int len) throws UncheckedIOException { if (b == null) { throw new NullPointerException(); } else if (off < 0 || len < 0 || len > b.length - off) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } if (buffer.position() + len > buffer.limit()) throw new UncheckedIOException(new EOFException()); buffer.get(b, off, len); } @Override public void writeByte(int b) { ensureCapacity(buffer.position() + 1); buffer.put((byte) b); } @Override public void writeBytes(byte[] b, int off, int len) throws UncheckedIOException { if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) - b.length > 0)) { throw new IndexOutOfBoundsException(); } ensureCapacity(buffer.position() + len); buffer.put(b, off, len); } private void ensureCapacity(int minCapacity) { if (minCapacity > buffer.capacity()) grow(minCapacity); if (minCapacity > buffer.limit()) buffer.limit(minCapacity); } private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = buffer.capacity(); int newCapacity = oldCapacity << 1; if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); int limit = buffer.limit(); int position = buffer.position(); buffer = ByteBuffer.wrap(Arrays.copyOf(buffer.array(), newCapacity)); buffer.limit(limit); buffer.position(position); } private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } @Override public RandomAccess openNewSession(boolean readOnly) { return this; } @Override public void close() { } public void writeTo(DataOutput output) throws UncheckedIOException { output.writeBytes(buffer.array(), 0, buffer.limit()); } }
package be.isach.samaritan.command; import net.dv8tion.jda.MessageHistory; import net.dv8tion.jda.entities.Message; import net.dv8tion.jda.entities.MessageChannel; import net.dv8tion.jda.entities.TextChannel; import java.time.ZoneId; import java.time.format.DateTimeFormatter; public class CommandQuote extends Command { public static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss"); /** * Command Constructor. * * @param messageChannel The text Channel where command is called. * @param commandData The Command Data, providing the Guild, the executor and the Samaritan instance. * @param args The args provided when command was called. */ CommandQuote(MessageChannel messageChannel, CommandData commandData, String[] args) { super(messageChannel, commandData, args); } /** * Called when command is executed. * * @param args Arguments provided by user. */ @Override void onExecute(String[] args) { String s = buildStringFromArgs(); MessageHistory messageHistory = new MessageHistory(getMessageChannel()); messageHistory.retrieve(1500); for (Message message : messageHistory.getRecent()) { if (message.getContent().toLowerCase().contains(s.toLowerCase()) && !message.getContent().startsWith("-") && !message.getAuthor().isBot()) { String messageToSend = "```\n" + "(" + message.getTime().toZonedDateTime().withZoneSameInstant(ZoneId.of("Europe/Paris")).format(DATE_FORMAT) + " " + message.getAuthor().getUsername() + "): " + message.getContent() + "\n" + "```"; getMessageChannel().sendMessage(messageToSend); return; } } getMessageChannel().sendMessage("No message found."); } }
package beaform.gui.formulaeditor; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Iterator; import java.util.List; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.transaction.NotSupportedException; import javax.transaction.SystemException; import org.apache.commons.collections.IteratorUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import beaform.entities.Formula; import beaform.entities.FormulaDAO; import beaform.entities.FormulaTag; import beaform.entities.Ingredient; /** * This class represents a GUI for editing formulas. * * @author Steven Post * */ public class FormulaEditor extends JPanel { /** A serial */ private static final long serialVersionUID = 2557014310487638917L; /** A logger */ private static final Logger LOG = LoggerFactory.getLogger(FormulaEditor.class); /** Dimensions for most text fields */ private static final Dimension DIM_TEXTFIELDS = new Dimension(100, 30); /** Dimensions for the description field */ private static final Dimension DIM_TEXTAREA = new Dimension(100, 90); /** A label for the total amount of a formula */ private static final JLabel LBL_TOTAL_AMOUNT = new JLabel("Total amount", SwingConstants.RIGHT); /** A label for the name of a formula */ private static final JLabel LBL_NAME = new JLabel("Name", SwingConstants.RIGHT); /** A label for the description of a formula */ private static final JLabel LBL_DESCRIPTION = new JLabel("Description", SwingConstants.RIGHT); /** A text field for the name of the formula */ private final JTextField txtName = new JTextField(); /** A text field for the description of a formula */ private final JTextArea txtDescription = new JTextArea(); /** A text field for the total amount of a formula */ private final JTextField txtTotalAmount = new JTextField(); /** The 'save' button */ private final JButton btnSubmit = new JButton("Submit"); /** The panel with all the tag components */ private final TagPane tagPane = new TagPane(); /** The panel with all the ingredient components */ private final IngredientPane ingredientPane = new IngredientPane(); /** The formula that needs editing */ private Formula formula; /** A panel for the general components */ private final JPanel panel = new JPanel(new GridBagLayout()); /** * Main constructor for this editor to add a new formula. * If you want to edit an existing one, * use the overridden constructor that takes a formula as argument. */ public FormulaEditor() { super(); init(); this.btnSubmit.addActionListener(new ActionListener() { /** * Invoked when the button is pressed. */ @Override public void actionPerformed(final ActionEvent event) { addNewFormula(); } }); } /** * Constructor that makes this an editor for existing formulas. * * @param formula The formula that needs editing. */ public FormulaEditor(final Formula formula) { super(); init(); this.txtName.setEnabled(false); this.formula = formula; this.txtName.setText(formula.getName()); this.txtDescription.setText(formula.getDescription()); this.txtTotalAmount.setText(formula.getTotalAmount()); try { // Add ingredients to the list final List<Ingredient> ingredientList = new FormulaDAO().getIngredients(formula); for (final Ingredient ingredient : ingredientList) { this.ingredientPane.addIngredient(ingredient); } // Add tags to the list final Iterator<FormulaTag> tagIterator = formula.getTags(); this.tagPane.addMultipleTags(tagIterator); } catch (NotSupportedException | SystemException e) { LOG.error("Failed to add all tags and ingredients", e); } this.btnSubmit.addActionListener(new ActionListener() { /** * Invoked when the button is pressed. */ @Override public void actionPerformed(final ActionEvent event) { updateFormula(); } }); } private void init() { this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS)); final JPanel generalPanel = createGeneralComponentsPanel(); this.add(generalPanel); // Ingredients this.add(this.ingredientPane); // Tags this.add(this.tagPane); // Submit this.add(this.btnSubmit); } private JPanel createGeneralComponentsPanel() { final GridBagConstraints constraints = new GridBagConstraints(); constraints.weightx = 0.1; constraints.weighty = 0.1; constraints.anchor = GridBagConstraints.LINE_END; constraints.fill = GridBagConstraints.HORIZONTAL; // Formula requirements constraints.gridx = 0; constraints.gridy = 0; this.panel.add(LBL_NAME, constraints); constraints.gridx = 1; constraints.gridy = 0; setDimensions(this.txtName, DIM_TEXTFIELDS); this.panel.add(this.txtName, constraints); constraints.gridx = 2; constraints.gridy = 0; this.panel.add(LBL_DESCRIPTION, constraints); constraints.gridx = 0; constraints.gridy = 1; setDimensions(LBL_TOTAL_AMOUNT, DIM_TEXTFIELDS); this.panel.add(LBL_TOTAL_AMOUNT, constraints); constraints.gridx = 1; constraints.gridy = 1; setDimensions(this.txtTotalAmount, DIM_TEXTFIELDS); this.panel.add(this.txtTotalAmount, constraints); constraints.gridx = 3; constraints.gridy = 0; constraints.gridheight = 2; constraints.fill = GridBagConstraints.BOTH; this.txtDescription.setBorder(BorderFactory.createLineBorder(Color.BLACK)); setDimensions(this.txtDescription, DIM_TEXTAREA); this.panel.add(this.txtDescription, constraints); return this.panel; } /** * This method sets 3 different sizes to a component: * minimum, preferred and maximum * * @param comp The component * @param dim The dimensions for the sizing */ private void setDimensions(final JComponent comp, final Dimension dim) { comp.setMinimumSize(dim); comp.setPreferredSize(dim); comp.setMaximumSize(dim); } /** * Invoked when the action occurs. * */ public void addNewFormula() { final String name = this.txtName.getText(); final String description = this.txtDescription.getText(); final String totalAmount = this.txtTotalAmount.getText(); if (LOG.isInfoEnabled()) { LOG.info("Add: " + name + " with description: " + description); } final List<Ingredient> ingredients = getIngredientList(); final List<FormulaTag> tags = getTagList(); try { new FormulaDAO().addFormula(name, description, totalAmount, ingredients, tags); } catch (SystemException | NotSupportedException e1) { LOG.error("Something wen wrong adding the new formula", e1); } } @SuppressWarnings("unchecked") private List<Ingredient> getIngredientList() { final Iterator<Ingredient> ingredients = this.ingredientPane.getIngredients(); return IteratorUtils.toList(ingredients); } @SuppressWarnings("unchecked") private List<FormulaTag> getTagList() { final Iterator<FormulaTag> tags = this.tagPane.getTags(); return IteratorUtils.toList(tags); } /** * Updates an existing formula. */ public void updateFormula() { if (LOG.isInfoEnabled()) { final String name = this.formula.getName(); final String description = this.txtDescription.getText(); LOG.info("Edit: " + name + " with description: " + description); } final List<Ingredient> ingredients = getIngredientList(); final List<FormulaTag> tags = getTagList(); try { final String name = this.formula.getName(); final String description = this.txtDescription.getText(); final String totalAmount = this.txtTotalAmount.getText(); new FormulaDAO().updateExisting(name, description, totalAmount, ingredients, tags); } catch (SystemException | NotSupportedException e1) { LOG.error("Something went wrong updating the formula", e1); } } }
package org.spongepowered.test; import org.spongepowered.api.Sponge; import org.spongepowered.api.command.CommandException; import org.spongepowered.api.command.CommandResult; import org.spongepowered.api.command.args.GenericArguments; import org.spongepowered.api.command.spec.CommandSpec; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.event.Listener; import org.spongepowered.api.event.Order; import org.spongepowered.api.event.cause.entity.damage.DamageTypes; import org.spongepowered.api.event.cause.entity.damage.source.DamageSource; import org.spongepowered.api.event.entity.DamageEntityEvent; import org.spongepowered.api.event.filter.Getter; import org.spongepowered.api.event.filter.cause.Root; import org.spongepowered.api.event.game.state.GameInitializationEvent; import org.spongepowered.api.plugin.Plugin; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.format.TextColors; import java.util.HashSet; import java.util.Set; import java.util.UUID; @Plugin(id = "damagesourcetest", name = "Damage Source Test", description = "A plugin to test damage sources") public final class DamageSourceTest { private final Set<UUID> activated = new HashSet<>(); @Listener public void onInit(GameInitializationEvent event) { Sponge.getCommandManager().register(this, CommandSpec.builder() .executor((src, args) -> { if (src instanceof Player) { final UUID uuid = ((Player) src).getUniqueId(); if (this.activated.contains(uuid)) { this.activated.remove(uuid); src.sendMessage(Text.of("You have deactivated damage source analysis.")); } else { this.activated.add(uuid); src.sendMessage(Text.of("You have activated damage source analysis.")); } return CommandResult.success(); } throw new CommandException(Text.of(TextColors.RED, "You must be a player to execute this command!")); }) .build(), "dstest"); final DamageSource damageSource = DamageSource.builder() .type(DamageTypes.CUSTOM) .exhaustion(5) .scalesWithDifficulty() .build(); Sponge.getCommandManager().register(this, CommandSpec.builder() .executor((src, args) -> { if (src instanceof Player) { final Player player = (Player) src; player.damage(args.<Double>getOne("damage").orElse(2.0), damageSource); player.sendMessage(Text.of("You have damaged yourself with the custom damage source.")); return CommandResult.success(); } throw new CommandException(Text.of(TextColors.RED, "You must be a player to execute this command!")); }) .arguments(GenericArguments.doubleNum(Text.of("damage"))) .build(), "dsdamage"); } @Listener(order = Order.POST) public void onPlayerDamage(DamageEntityEvent event, @Getter("getTargetEntity") Player player, @Root DamageSource source) { if (this.activated.contains(player.getUniqueId())) { player.sendMessage(Text.of(TextColors.BLUE, "You have been damaged by the following source for " + event.getFinalDamage())); player.sendMessage(Text.of(TextColors.GOLD, "=======================================")); player.sendMessage(Text.of(TextColors.GOLD, "Damage type: ", TextColors.GRAY, source.getType().getName())); player.sendMessage(Text.of(TextColors.GOLD, "Affects creative: ", TextColors.GRAY, source.doesAffectCreative())); player.sendMessage(Text.of(TextColors.GOLD, "Exhaustion: ", TextColors.GRAY, source.getExhaustion())); player.sendMessage(Text.of(TextColors.GOLD, "Absolute: ", TextColors.GRAY, source.isAbsolute())); player.sendMessage(Text.of(TextColors.GOLD, "Bypassing armor: ", TextColors.GRAY, source.isBypassingArmor())); player.sendMessage(Text.of(TextColors.GOLD, "Explosive: ", TextColors.GRAY, source.isExplosive())); player.sendMessage(Text.of(TextColors.GOLD, "Magic: ", TextColors.GRAY, source.isMagic())); player.sendMessage(Text.of(TextColors.GOLD, "Scaled by difficulty: ", TextColors.GRAY, source.isScaledByDifficulty())); } } }
package com.backendless; import java.io.IOException; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import android.content.Context; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaPlayer.OnPreparedListener; import android.view.SurfaceHolder; import com.backendless.exceptions.BackendlessException; import com.backendless.media.DisplayOrientation; import com.backendless.media.Session; import com.backendless.media.SessionBuilder; import com.backendless.media.StreamProtocolType; import com.backendless.media.StreamQuality; import com.backendless.media.StreamType; import com.backendless.media.audio.AudioQuality; import com.backendless.media.gl.SurfaceView; import com.backendless.media.rtsp.RtspClient; import com.backendless.media.video.VideoQuality; public final class Media { private final static String WOWZA_SERVER_IP = "media.backendless.com"; private final static String WOWZA_SERVER_LIVE_APP_NAME = "mediaAppLive"; private final static String WOWZA_SERVER_VOD_APP_NAME = "mediaAppVod"; private final static Integer WOWZA_SERVER_PORT = 1935; private final static String RTSP_PROTOCOL = StreamProtocolType.RTSP.getValue(); private final static String HLS_PROTOCOL = StreamProtocolType.HLS.getValue(); private static final String MEDIA_FILES_LOCATION = "/files/media/"; private static final String HLS_PLAYLIST_CONSTANT = "/playlist.m3u8"; private RtspClient rtspClient; private Session session; private MediaPlayer mediaPlayer; private StreamProtocolType protocolType; private static final Media instance = new Media(); static Media getInstance() { return instance; } public void toggleFlash() { checkSessionIsNull(); session.toggleFlash(); } public StreamQuality getStreamQuality() { checkSessionIsNull(); // "176x144, 30 fps, 170 Kbps" VideoQuality videoQuality = session.getVideoTrack().getVideoQuality(); int width = videoQuality.resX; int height = videoQuality.resY; int framerate = videoQuality.framerate; int bitrate = videoQuality.bitrate; StreamQuality streamQuality = StreamQuality.valueOf( width + "x" + height + ", " + framerate + "fps, " + bitrate + " Kbps" ); return streamQuality; } public void setStreamQuality( StreamQuality streamQuality ) { checkSessionIsNull(); if( streamQuality == null ) { return; } VideoQuality videoQuality = convertVideoQuality( streamQuality ); session.setVideoQuality( videoQuality ); } private VideoQuality convertVideoQuality( StreamQuality streamQuality ) { Pattern pattern = Pattern.compile( "(\\d+)x(\\d+)\\D+(\\d+)\\D+(\\d+)" ); Matcher matcher = pattern.matcher( streamQuality.getValue() ); matcher.find(); int width = Integer.parseInt( matcher.group( 1 ) ); int height = Integer.parseInt( matcher.group( 2 ) ); int framerate = Integer.parseInt( matcher.group( 3 ) ); int bitrate = Integer.parseInt( matcher.group( 4 ) ) * 1000; VideoQuality videoQuality = new VideoQuality( width, height, framerate, bitrate ); return videoQuality; } public void setAudioQuality( int sampleRate, int bitRate ) { checkSessionIsNull(); session.setAudioQuality( new AudioQuality( sampleRate, bitRate ) ); } public void switchCamera() { checkSessionIsNull(); session.switchCamera(); } public void startPreview() { checkSessionIsNull(); session.startPreview(); } public void stopPreview() { checkSessionIsNull(); session.stopPreview(); } public void stopClientStream() { checkRtspClientIsNull(); rtspClient.stopStream(); } public void releaseSession() { checkSessionIsNull(); session.release(); } public void releaseClient() { checkRtspClientIsNull(); rtspClient.release(); } /** * <p> * default video quality to 176x144 20fps 500Kbps<br/> * default audio quality to 8000 sampleRate 32000 bitRate * </p> */ public void configureForPublish( Context context, SurfaceView mSurfaceView, DisplayOrientation orientation ) { session = getSession( context, mSurfaceView, orientation.getValue() ); rtspClient = getRtspClient( context, session ); } /** * StreamProtocolType sets to default value - RTSP * * @param mSurfaceHolder */ public void configureForPlay( SurfaceHolder mSurfaceHolder ) { configureForPlay( mSurfaceHolder, StreamProtocolType.RTSP ); } public void configureForPlay( SurfaceHolder mSurfaceHolder, StreamProtocolType protocolType ) { this.protocolType = protocolType; mediaPlayer = new MediaPlayer(); mediaPlayer.setDisplay( mSurfaceHolder ); mediaPlayer.setAudioStreamType( AudioManager.STREAM_MUSIC ); mediaPlayer.setOnPreparedListener( new OnPreparedListener() { @Override public void onPrepared( MediaPlayer mp ) { mp.start(); } } ); } public void publishRecordOrStop( String tube, String streamName ) { publishStreamOrStop( tube, streamName, StreamType.LIVE_RECORDING ); } public void publishLiveOrStop( String tube, String streamName ) { publishStreamOrStop( tube, streamName, StreamType.LIVE ); } public void playLiveOrStop( String tube, String streamName ) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException { playStreamOrStop( tube, streamName, StreamType.RECORDING ); } public void playRecordOrStop( String tube, String streamName ) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException { playStreamOrStop( tube, streamName, StreamType.AVAILABLE ); } private void publishStreamOrStop( String tube, String streamName, StreamType streamType ) { checkSessionIsNull(); checkRtspClientIsNull(); if( mediaPlayer != null ) { mediaPlayer.reset(); } if( streamName == null || streamName.isEmpty() ) { streamName = "default"; } else { streamName = streamName.trim().replace( '.', '_' ); } if( tube == null || tube.isEmpty() ) { tube = "default"; } else { tube = tube.trim(); } String operationType = getOperationType( streamType ); String params = getConnectParams( tube, operationType, streamName ); startOrStopStream( rtspClient, streamName, params ); } private void checkPlayerIsNull() { if( mediaPlayer == null ) { throw new BackendlessException( "Player client is null. Method configure( .. ) must be invoked" ); } } private void checkSessionIsNull() { if( session == null ) { throw new BackendlessException( "Session client is null. Method configure( .. ) must be invoked" ); } } private void checkRtspClientIsNull() { if( rtspClient == null ) { throw new BackendlessException( "Streaming client is null. Method configure( .. ) must be invoked" ); } } private String getOperationType( StreamType streamType ) { return ( streamType == StreamType.LIVE ) ? "publishLive" : "publishRecorded"; } private void playStreamOrStop( String tube, String streamName, StreamType streamType ) throws IllegalArgumentException, SecurityException, IllegalStateException, IOException { checkPlayerIsNull(); if( streamName == null || streamName.isEmpty() ) { streamName = "default"; } else { streamName = streamName.trim().replace( '.', '_' ); } if( tube == null || tube.isEmpty() ) { tube = "default"; } else { tube = tube.trim(); } if( mediaPlayer.isPlaying() ) { mediaPlayer.stop(); mediaPlayer.reset(); } else { if( session != null ) { session.stopPreview(); } mediaPlayer.reset(); if( protocolType == null ) { protocolType = StreamProtocolType.RTSP; } String protocol = getProtocol( protocolType ); String operationType = ( streamType == StreamType.RECORDING ) ? "playLive" : "playRecorded"; String wowzaAddress = WOWZA_SERVER_IP + ":" + WOWZA_SERVER_PORT + "/" + ( ( streamType == StreamType.RECORDING ) ? WOWZA_SERVER_LIVE_APP_NAME : WOWZA_SERVER_VOD_APP_NAME ) + "/_definst_/"; String params = getConnectParams( tube, operationType, streamName ); String streamPath = getStreamName( streamName, protocolType ); String url = protocol + wowzaAddress + streamPath + params; mediaPlayer.setDataSource( url ); mediaPlayer.prepare(); mediaPlayer.start(); } } private String getStreamName( String fileName, StreamProtocolType protocol ) { String subDir = Backendless.getApplicationId().toLowerCase() + MEDIA_FILES_LOCATION; String hlsAdditionalParameter = ( protocol == StreamProtocolType.HLS ) ? HLS_PLAYLIST_CONSTANT : ""; return subDir + fileName + hlsAdditionalParameter; } private String getProtocol( StreamProtocolType streamProtocolType ) { if( streamProtocolType.equals( StreamProtocolType.RTSP ) ) { return RTSP_PROTOCOL; } if( streamProtocolType.equals( StreamProtocolType.HLS ) ) { return HLS_PROTOCOL; } throw new BackendlessException( "Backendless Android SDK not supported protocol type '" + streamProtocolType + "'" ); } private Session getSession( Context context, SurfaceView mSurfaceView, int orientation ) { Session mSession = SessionBuilder.getInstance().setContext( context ).setAudioEncoder( SessionBuilder.AUDIO_AAC ) .setVideoEncoder( SessionBuilder.VIDEO_H264 ).setSurfaceView( mSurfaceView ).setPreviewOrientation( orientation ) .setCallback( (Session.Callback) context ).build(); return mSession; } private String getConnectParams( String tube, String operationType, String streamName ) { String paramsToSend; BackendlessUser currentUser = Backendless.UserService.CurrentUser(); Object identity = currentUser != null ? currentUser.getProperty( "user-token" ) : null; HashMap<String, String> map = new HashMap<String, String>(); map.putAll( HeadersManager.getInstance().getHeaders() ); map.put( "identity", identity != null ? identity.toString() : map.get( "user-token" ) ); paramsToSend = "?application-id=" + map.get( "application-id" ) + "&version=" + Backendless.getVersion() + "&identity=" + map.get( "identity" ) + "&tube=" + tube + "&operationType=" + operationType + "&streamName=" + streamName; return paramsToSend; } // Connects/disconnects to the RTSP server and starts/stops the stream private void startOrStopStream( RtspClient rtspClient, String streamName, String params ) { if( !rtspClient.isStreaming() ) { rtspClient.setServerAddress( WOWZA_SERVER_IP, WOWZA_SERVER_PORT ); rtspClient.setStreamPath( "/" + WOWZA_SERVER_LIVE_APP_NAME + "/" + streamName + params ); rtspClient.startStream(); } else { // Stops the stream and disconnects from the RTSP server rtspClient.stopStream(); } } private RtspClient getRtspClient( Context context, Session mSession ) { // Configures the RTSP client if( rtspClient == null ) { rtspClient = new RtspClient(); rtspClient.setSession( mSession ); rtspClient.setCallback( (RtspClient.Callback) context ); } return rtspClient; } public StreamProtocolType getProtocolType() { return protocolType; } public void setProtocolType( StreamProtocolType protocolType ) { this.protocolType = protocolType; } }
package com.bona.Entity; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.jgrapht.DirectedGraph; import org.jgrapht.EdgeFactory; import org.jgrapht.GraphPath; public class Graph implements DirectedGraph<Vertex, Edge>, GraphPath { List<Vertex> vertices = new ArrayList<Vertex>(); List<Edge> edges = new ArrayList<Edge>(); public Vertex searchList(Vertex vertex) { for(int i = 0; i < vertices.size(); i++) { if(vertices.get(i).getId().equals(vertex.getId())) { return vertices.get(i); } } return null; } public Vertex addVertex (String id, String type, String label) { Vertex vertex = new Vertex(id, type, label); vertices.add(vertex); return vertex; } /* * Checks to see if it has an incoming edge * */ public boolean containsIncomingEdge(Vertex v) { if(v.getIncomingEdges().size() != 0) { return true; } return false; } /* * Checks to see if it has an outgoing edge * */ public boolean containsOutgoingEdge(Vertex v) { if(v.getOutgoingEdges().size() != 0) { return true; } return false; } /* * Implemented from the Graph Path section */ @Override public Graph getGraph() { // TODO Auto-generated method stub return this; } @Override public Object getStartVertex() { // TODO Auto-generated method stub return null; } @Override public Object getEndVertex() { // TODO Auto-generated method stub return null; } @Override public List getEdgeList() { // TODO Auto-generated method stub return null; } @Override public double getWeight() { // TODO Auto-generated method stub return 0; } public List<Vertex> getVertices() { return vertices; } public void setVertices(List<Vertex> vertices) { this.vertices = vertices; } public List<Edge> getEdges() { return edges; } public void setEdges(List<Edge> edges) { this.edges = edges; } /* * (non-Javadoc) * @see org.jgrapht.Graph#getAllEdges(java.lang.Object, java.lang.Object) */ @Override public Set<Edge> getAllEdges(Vertex sourceVertex, Vertex targetVertex) { // TODO Auto-generated method stub return null; } @Override public Edge getEdge(Vertex sourceVertex, Vertex targetVertex) { // TODO Auto-generated method stub return null; } @Override public EdgeFactory<Vertex, Edge> getEdgeFactory() { // TODO Auto-generated method stub return null; } @Override public Edge addEdge(Vertex sourceVertex, Vertex targetVertex) { int i = 0; Vertex source = new Vertex(); Vertex target = new Vertex(); source = this.searchList((Vertex)sourceVertex); target = this.searchList((Vertex)targetVertex); Edge edge = new Edge(i ,source ,target); edge.setSourceVertex(sourceVertex); source.getOutgoingEdges().add(edge); edge.setTargetVertex(targetVertex); target.getIncomingEdges().add(edge); edges.add(edge); i++; return edge; } @Override public boolean addEdge(Vertex sourceVertex, Vertex targetVertex, Edge e) { // TODO Auto-generated method stub return false; } @Override public boolean addVertex(Vertex vertex) { vertices.add(vertex); return false; } @Override public boolean containsEdge(Vertex sourceVertex, Vertex targetVertex) { // TODO Auto-generated method stub return false; } @Override public boolean containsEdge(Edge e) { // TODO Auto-generated method stub return false; } @Override public boolean containsVertex(Vertex v) { for(int i = 0; i < vertices.size(); i++) { if(vertices.get(i).getId() == v.getId()) { return true; } } return false; } @Override public Set<Edge> edgeSet() { Set<Edge> edgeSet = new HashSet<Edge>(); for(int i = 0; i < edges.size(); i++){ edgeSet.add(edges.get(i)); } return edgeSet; } @Override public Set<Edge> edgesOf(Vertex vertex) { return null; } @Override public boolean removeAllEdges(Collection<? extends Edge> edges) { // TODO Auto-generated method stub return false; } @Override public Set<Edge> removeAllEdges(Vertex sourceVertex, Vertex targetVertex) { // TODO Auto-generated method stub return null; } @Override public boolean removeAllVertices(Collection<? extends Vertex> vertices) { // TODO Auto-generated method stub return false; } @Override public Edge removeEdge(Vertex sourceVertex, Vertex targetVertex) { // TODO Auto-generated method stub return null; } @Override public boolean removeEdge(Edge e) { // TODO Auto-generated method stub return false; } @Override public boolean removeVertex(Vertex v) { // TODO Auto-generated method stub return false; } @Override public Set<Vertex> vertexSet() { Set<Vertex> vertexSet = new HashSet<Vertex>(); for(int i = 0; i < vertices.size(); i++) { vertexSet.add(vertices.get(i)); } return vertexSet; } @Override public Vertex getEdgeSource(Edge e) { return e.getTargetVertex(); } @Override public Vertex getEdgeTarget(Edge e) { return e.getTargetVertex(); } @Override public double getEdgeWeight(Edge e) { // TODO Auto-generated method stub return 0; } @Override public int inDegreeOf(Vertex vertex) { // TODO Auto-generated method stub int inDegree = (vertex).getIncomingEdges().size(); return inDegree; } @Override public Set<Edge> incomingEdgesOf(Vertex vertex) { Set<Edge> incomingEdges = new HashSet<Edge>(); for(Edge edges : vertex.getIncomingEdges()){ incomingEdges.add(edges); } return incomingEdges; } @Override public int outDegreeOf(Vertex vertex) { int outDegree = (vertex).getOutgoingEdges().size(); return outDegree; } @Override public Set<Edge> outgoingEdgesOf(Vertex vertex) { Set<Edge> outGoingEdges = new HashSet<Edge>(); for(Edge edges : vertex.getOutgoingEdges()){ outGoingEdges.add(edges); } return outGoingEdges; } }
//This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //This library is distributed in the hope that it will be useful, //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //You should have received a copy of the GNU Lesser General Public //Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. package opennlp.tools.parser; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; import opennlp.tools.util.Span; //import java.text.DecimalFormat; /** Data structure for holding parse constitents. */ public class Parse implements Cloneable, Comparable { /** The text string on which this parse is based. This object is shared amonung all parses for the same sentence. */ private String text; /** The character offsets into the text for this constituent. */ private Span span; /** The syntactic type of this parse. */ private String type; /** The sub-constituents of this parse. */ private List parts; /** The head parse of this parse. A parse can be its own head.*/ private Parse head; /** The outcome assigned to this parse during cconstruction of its parent parse. */ private String label; /** The parent parse of this parse. */ private Parse parent; /** The probability associated with the syntactic type assigned to this parse. */ private double prob; /** The string buffer used to track the derivation of this parse. */ private StringBuffer derivation; /** The pattern used to find the base constituent label of a Penn Treebank labeled constituent. */ private static Pattern typePattern = Pattern.compile("^([^ =-]+)"); /** The pattern used to find the function tags. */ private static Pattern funTypePattern = Pattern.compile("^[^ =-]+-([^ =-]+)"); /** The patter used to identify tokens in Penn Treebank labeled constituents. */ private static Pattern tokenPattern = Pattern.compile("^[^ ()]+ ([^ ()]+)\\s*\\)"); /** The set of punctuation parses which are between this parse and the previous parse. */ private Collection prevPunctSet; /** The set of punctuation parses which are between this parse and the subsequent parse. */ private Collection nextPunctSet; private static boolean useFunctionTags; public Parse clone() { Parse p = new Parse(this.text, this.span, this.type, this.prob, this.head); p.parts = (List) ((LinkedList) this.parts).clone(); if (derivation != null) { p.derivation = new StringBuffer(100); p.derivation.append(this.derivation.toString()); } p.label = this.label; return (p); } public static void useFunctionTags(boolean uft) { useFunctionTags = uft; } public Parse(String text, Span span, String type, double p) { this.text = text; this.span = span; this.type = type; this.prob = p; this.head = this; this.parts = new LinkedList(); this.label = null; this.parent = null; } public Parse(String text, Span span, String type, double p, Parse h) { this(text, span, type, p); this.head = h; } /** * Set the type of this constituent to the specified type. * @param type The type of this constituent. */ public void setType(String type) { this.type = type; } /** * Returns the constituent label for this node of the parse. * @return The constituent label for this node of the parse. */ public String getType() { return type; } /** * Returns the set of punctuation parses that occur immediately before this parse. * @return the set of punctuation parses that occur immediately before this parse. */ public Collection getPreviousPunctuationSet() { return prevPunctSet; } /** * Designates that the specifed punctuation should is prior to this parse. * @param punct The punctuation. */ public void addPreviousPunctuation(Parse punct) { if (this.prevPunctSet == null) { this.prevPunctSet = new LinkedHashSet(); } prevPunctSet.add(punct); } /** * Returns the set of punctuation parses that occur immediately after this parse. * @return the set of punctuation parses that occur immediately after this parse. */ public Collection getNextPunctuationSet() { return nextPunctSet; } /** * Designates that the specifed punctuation follows this parse. * @param punct The punctuation set. */ public void addNextPunctuation(Parse punct) { if (this.nextPunctSet == null) { this.nextPunctSet = new LinkedHashSet(); } nextPunctSet.add(punct); } /** * Sets the set of punctuation tags which follow this parse. * @param punctSet The set of puncuation tags which follow this parse. */ public void setNextPunctuation(Collection punctSet) { this.nextPunctSet = punctSet; } /** * Sets the set of punctuation tags which preceed this parse. * @param punctSet The set of puncuation tags which preceed this parse. */ public void setPrevPunctuation(Collection punctSet) { this.prevPunctSet = punctSet; } /** * Inserts the specified constituent into this parse based on its text span. This * method assumes that the specified constituent can be inserted into this parse. * @param constituent The constituent to be inserted. */ public void insert(final Parse constituent) { Span ic = constituent.span; if (span.contains(ic)) { //double oprob=c.prob; int pi=0; int pn = parts.size(); for (; pi < pn; pi++) { Parse subPart = (Parse) parts.get(pi); //System.err.println("Parse.insert:con="+constituent+" sp["+pi+"] "+subPart+" "+subPart.getType()); Span sp = subPart.span; if (sp.getStart() >= ic.getEnd()) { break; } // constituent contains subPart else if (ic.contains(sp)) { //System.err.println("Parse.insert:con contains subPart"); parts.remove(pi); pi constituent.parts.add(subPart); subPart.setParent(constituent); //System.err.println("Parse.insert: "+subPart.hashCode()+" -> "+subPart.getParent().hashCode()); pn = parts.size(); } else if (sp.contains(ic)) { //System.err.println("Parse.insert:subPart contains con"); subPart.insert(constituent); return; } } //System.err.println("Parse.insert:adding con="+constituent+" to "+this); parts.add(pi, constituent); constituent.setParent(this); //System.err.println("Parse.insert: "+constituent.hashCode()+" -> "+constituent.getParent().hashCode()); } else { throw (new InternalError("Inserting constituent not contained in the sentence!")); } } /** * Appends the specified string buffer with a string representation of this parse. * @param sb A string buffer into which the parse string can be appended. */ public void show(StringBuffer sb) { int start; start = span.getStart(); if (!type.equals(ParserME.TOK_NODE)) { sb.append("("); sb.append(type +" "); //System.out.print(label+" "); //System.out.print(head+" "); //System.out.print(df.format(prob)+" "); } for (Iterator i = parts.iterator(); i.hasNext();) { Parse c = (Parse) i.next(); Span s = c.span; if (start < s.getStart()) { //System.out.println("pre "+start+" "+s.getStart()); sb.append(text.substring(start, s.getStart())); } c.show(sb); start = s.getEnd(); } sb.append(text.substring(start, span.getEnd())); if (!type.equals(ParserME.TOK_NODE)) { sb.append(")"); } } /** * Displays this parse using Penn Treebank-style formatting. */ public void show() { StringBuffer sb = new StringBuffer(text.length()*4); show(sb); System.out.println(sb); } /** * Returns the probability associed with the pos-tag sequence assigned to this parse. * @return The probability associed with the pos-tag sequence assigned to this parse. */ public double getTagSequenceProb() { //System.err.println("Parse.getTagSequenceProb: "+type+" "+this); if (parts.size() == 1 && ((Parse) parts.get(0)).type.equals(ParserME.TOK_NODE)) { //System.err.println(this+" "+prob); return (Math.log(prob)); } else if (parts.size() == 0) { System.err.println("Parse.getTagSequenceProb: Wrong base case!"); return (0.0); } else { double sum = 0.0; for (Iterator pi = parts.iterator(); pi.hasNext();) { sum += ((Parse) pi.next()).getTagSequenceProb(); } return (sum); } } /** * Returns whether this parse is complete. * @return Returns true if the parse contains a single top-most node. */ public boolean complete() { return (parts.size() == 1); } public String toString() { return (text.substring(span.getStart(), span.getEnd())); } /** * Returns the text of the sentence over which this parse was formed. * @return The text of the sentence over which this parse was formed. */ public String getText() { return text; } /** * Returns the character offsets for this constituent. * @return The character offsets for this constituent. */ public Span getSpan() { return span; } /** * Returns the log of the product of the probability associated with all the decisions which formed this constituent. * @return The log of the product of the probability associated with all the decisions which formed this constituent. */ public double getProb() { return prob; } /** * Adds the specified probability log to this current log for this parse. * @param logProb The probaility of an action performed on this parse. */ public void addProb(double logProb) { this.prob+=logProb; } /** * Returns the child constituents of this constiuent. * @return The child constituents of this constiuent. */ public Parse[] getChildren() { return (Parse[]) parts.toArray(new Parse[parts.size()]); } /** * Replaces the child at the specified index with a new child with the specified label. * @param index The index of the child to be replaced. * @param label The label to be assigned to the new child. */ public void setChild(int index, String label) { Parse newChild = (Parse) ((Parse) parts.get(index)).clone(); newChild.setLabel(label); parts.set(index,newChild); } /** * Returns the number of children for this parse node. * @return the number of children for this parse node. */ public int getChildCount() { return parts.size(); } /** * Returns the index of this specified child. * @param child A child of this parse. * @return the index of this specified child or -1 if the specified child is not a child of this parse. */ public int indexOf(Parse child) { return parts.indexOf(child); } /** Returns the head constituent associated with this constituent. * @return The head constituent associated with this constituent. */ public Parse getHead() { return head; } /** * Returns the label assigned to this parse node during parsing * which specifies how this node will be formed into a constituent. * @return The outcome label assigned to this node during parsing. */ public String getLabel() { return label; } /** * Assigns this parse the specified label. * @param label A label indicating the constituent this parse node will become part of. */ public void setLabel(String label) { this.label = label; } private static String getType(String rest) { if (rest.startsWith("-LCB-")) { return "-LCB-"; } else if (rest.startsWith("-RCB-")) { return "-RCB-"; } else if (rest.startsWith("-LRB-")) { return "-LRB-"; } else if (rest.startsWith("-RRB-")) { return "-RRB-"; } else { Matcher typeMatcher = typePattern.matcher(rest); if (typeMatcher.find()) { String type = typeMatcher.group(1); if (useFunctionTags) { Matcher funMatcher = funTypePattern.matcher(rest); if (funMatcher.find()) { String ftag = funMatcher.group(1); type = type+"-"+ftag; } } return type; } } return null; } private static String getToken(String rest) { Matcher tokenMatcher = tokenPattern.matcher(rest); if (tokenMatcher.find()) { return tokenMatcher.group(1); } return null; } /** * Computes the head parses for this parse and its sub-parses and stores this information * in the parse data structure. * @param rules The head rules which determine how the head of the parse is computed. */ public void updateHeads(HeadRules rules) { if (parts != null && parts.size() != 0) { for (int pi=0,pn=parts.size();pi<pn;pi++) { Parse c = (Parse) parts.get(pi); c.updateHeads(rules); } this.head = rules.getHead((Parse[]) parts.toArray(new Parse[parts.size()]), type); if (head == null) { head = this; } } else { this.head = this; } } /** * Parses the specified tree-bank style parse string and return a Parse structure for that string. * @param parse A tree-bank style parse string. * @return a Parse structure for the specified tree-bank style parse string. */ public static Parse parseParse(String parse) { StringBuffer text = new StringBuffer(); int offset = 0; Stack stack = new Stack(); List tokens = new LinkedList(); List tags = new LinkedList(); List cons = new LinkedList(); for (int ci = 0, cl = parse.length(); ci < cl; ci++) { char c = parse.charAt(ci); if (c == '(') { String rest = parse.substring(ci + 1); String type = getType(rest); if (type == null) { System.err.println("null type for: " + rest); } String token = getToken(rest); stack.push(new Object[] { type, new Integer(offset)}); if (token != null && !type.equals("-NONE-")) { cons.add(new Object[] { ParserME.TOK_NODE, new Span(offset, offset + token.length())}); text.append(token).append(" "); offset += token.length() + 1; } } else if (c == ')') { Object[] parts = (Object[]) stack.pop(); String type = (String) parts[0]; if (!type.equals("-NONE-")) { int start = ((Integer) parts[1]).intValue(); cons.add(new Object[] { parts[0], new Span(start, offset - 1)}); } } } String txt = text.toString(); Parse p = new Parse(txt, new Span(0, txt.length()), ParserME.TOP_NODE, 1); /* for (int ti=0;ti < tokens.size();ti++) { Object[] parts = (Object[]) cons.get(ti); String type = (String) parts[0]; if (!type.equals(ParserME.TOP_NODE)) { Parse con = new Parse(txt, (Span) parts[1], type, 1); System.err.println("insert "+type+" "+con.toString()); p.insert(con); } } */ for (int ci=0;ci < cons.size();ci++) { Object[] parts = (Object[]) cons.get(ci); String type = (String) parts[0]; if (!type.equals(ParserME.TOP_NODE)) { Parse con = new Parse(txt, (Span) parts[1], type, 1); System.err.println("insert["+ci+"] "+type+" "+con.toString()+" "+con.hashCode()); p.insert(con); //codeTree(p); } } return p; } /** * Returns the parent parse node of this constituent. * @return The parent parse node of this constituent. */ public Parse getParent() { return parent; } /** * Specifies the parent parse node for this constituent. * @param parent The parent parse node for this constituent. */ public void setParent(Parse parent) { this.parent = parent; } /** * Indicates wether this parse node is a pos-tag. * @return true if this node is a pos-tag, false otherwise. */ public boolean isPosTag() { return (parts.size() == 1 && ((Parse) parts.get(0)).getType().equals(ParserME.TOK_NODE)); } /** * Returns the parse nodes which are children of this node and which are pos tags. * @return the parse nodes which are children of this node and which are pos tags. */ public Parse[] getTagNodes() { List tags = new LinkedList(); List nodes = new LinkedList(); nodes.addAll(this.parts); while(nodes.size() != 0) { Parse p = (Parse) nodes.remove(0); if (p.isPosTag()) { tags.add(p); } else { nodes.addAll(0,p.parts); } } return (Parse[]) tags.toArray(new Parse[tags.size()]); } /** * Returns the deepest shared parent of this node and the specified node. * If the nodes are identical then their parent is returned. * If one node is the parent of the other then the parent node is returned. * @param node The node from which parents are compared to this node's parents. * @return the deepest shared parent of this node and the specified node. */ public Parse getCommonParent(Parse node) { if (this == node) { return parent; } Set parents = new HashSet(); Parse parent = this; while(parent != null) { parents.add(parent); parent = parent.getParent(); } while (node != null) { if (parents.contains(node)) { return node; } node = node.getParent(); } return null; } public int compareTo(Object o) { Parse p = (Parse) o; if (this.getProb() > p.getProb()) { return -1; } else if (this.getProb() < p.getProb()) { return 1; } return 0; } /** * Returns the derivation string for this parse if one has been created. * @return the derivation string for this parse or null if no derivation string has been created. */ public StringBuffer getDerivation() { return derivation; } /** * Specifies the derivation string to be associated with this parse. * @param derivation The derivation string to be associated with this parse. */ public void setDerivation(StringBuffer derivation) { this.derivation = derivation; } private void codeTree(Parse p,int[] levels) { Parse[] kids = p.getChildren(); StringBuffer levelsBuff = new StringBuffer(); levelsBuff.append("["); int[] nlevels = new int[levels.length+1]; for (int li=0;li<levels.length;li++) { nlevels[li] = levels[li]; levelsBuff.append(levels[li]).append("."); } for (int ki=0;ki<kids.length;ki++) { nlevels[levels.length] = ki; System.out.println(levelsBuff.toString()+ki+"] "+kids[ki].getType()+" "+kids[ki].hashCode()+" -> "+kids[ki].getParent().hashCode()+" "+kids[ki].getParent().getType()+" "+kids[ki].toString()); codeTree(kids[ki],nlevels); } } /** * Prints to standard out a representation of the specified parse which contains hash codes so that * parent/child relationships can be explicitly seen. * @param p The parse to display. */ public void showCodeTree() { codeTree(this,new int[0]); } /** * Reads training parses (one-sentence-per-line) and displays parse structure. * @param args The head rules files. * @throws java.io.IOException If the head rules file can not be opened and read. */ public static void main(String[] args) throws java.io.IOException { if (args.length == 0) { System.err.println("Usage: Parse -fun head_rules < train_parses"); System.err.println("Reads training parses (one-sentence-per-line) and displays parse structure."); System.exit(1); } int ai=0; if (args[0].equals("-fun")) { Parse.useFunctionTags(true); ai++; } HeadRules rules = new opennlp.tools.lang.english.HeadRules(args[ai]); java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); for (String line = in.readLine(); line != null; line = in.readLine()) { Parse p = Parse.parseParse(line); //p.updateHeads(rules); //p.show(); p.showCodeTree(); System.out.println(); } } }
package com.colinrtwhite; import java.io.*; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; class Main { private static final String JPG = ".jpg", JPEG = ".jpeg", PNG = ".png", WEBP = ".webp", NINE_PATCH = ".9.png", ORIGINAL = ".original"; private static final int BUTTERAUGLI_MINIMUM_SIZE = 32; private static final DirectoryFilenameFilter DIRECTORY_FILTER = new DirectoryFilenameFilter(); private static final ImageFilenameFilter IMAGE_FILTER = new ImageFilenameFilter(); private static boolean allowLossless = false, isRecursive = false; private static int numCPUs = 2; private static double qualityThreshold = 1; private static long totalOriginalSize = 0, bytesSaved = 0; public static void main(final String[] args) { File directory = parseArguments(args); if (directory == null) { printUsage(); return; } try { // Backup the input directory before compressing its files. new ProcessBuilder("cp", "-r", directory.getPath(), directory.getPath() + "_old").start().waitFor(); ExecutorService executor = Executors.newFixedThreadPool(numCPUs); if (!directory.exists()) { System.out.println("The input directory does not exist."); } else if (!directory.isDirectory()) { System.out.println("The input path is not a directory."); } else { traverseDirectory(executor, directory); } executor.shutdown(); executor.awaitTermination(7, TimeUnit.DAYS); // Essentially, run until done or killed. System.out.println(String.format("Total compression savings: %d bytes (%.2f%% size reduction).", bytesSaved, totalOriginalSize > 0 ? (100.0 * bytesSaved) / totalOriginalSize : 0)); } catch (Exception e) { e.printStackTrace(); } } private static File parseArguments(final String[] args) { try { if (args.length < 1) { return null; } // Read in and validate any optional arguments. boolean expectsNumCPUsNext = false, expectsQualityNext = false; for (int i = 1; i < args.length; i++) { switch (args[i]) { case "-n": expectsNumCPUsNext = true; break; case "-q": expectsQualityNext = true; break; case "-r": isRecursive = true; break; case "-l": allowLossless = true; break; default: if (expectsNumCPUsNext) { numCPUs = Integer.valueOf(args[i]); expectsNumCPUsNext = false; } else if (expectsQualityNext) { qualityThreshold = Double.valueOf(args[i]); expectsQualityNext = false; } break; } } // Return the directory to show that we parse the arguments successfully. return new File(args[0]); } catch (Exception e) { return null; } } private static void printUsage() { System.out.println("Usage: java -jar webpify.jar /path/to/target/directory [[-n <number_of_processes>] [-q <quality_threshold>] [-r] [-l]]"); } private static void traverseDirectory(final ExecutorService executor, final File directory) { Arrays.stream(getImagesOrDirectories(directory, true)).forEach(file -> executor.execute(() -> { // Compute some initial information about the image file. String path = file.getPath(); String basePath = path.substring(0, path.lastIndexOf(".")); String webPPath = basePath + WEBP; File webPFile = new File(webPPath); boolean needsConvertToPng = !file.getName().endsWith(PNG); boolean hasError = false; long fileSize = file.length(); totalOriginalSize += fileSize; try { if (searchForOptimalQuality(file, path, basePath, webPPath, webPFile, needsConvertToPng)) { // Attempt lossless compression if enabled (requires minSdk >= 18 on Android). if (allowLossless && getImageDissimilarity(100, path, basePath, webPPath, needsConvertToPng, true) < qualityThreshold && isSmallerFile(webPFile, file)) { bytesSaved += fileSize - webPFile.length(); new ProcessBuilder("rm", path).start(); System.out.println("Successfully compressed file: " + path); } else { new ProcessBuilder("rm", webPPath).start(); System.out.println("The following image couldn't be compressed any further: " + path); } } else { bytesSaved += (fileSize - webPFile.length()); new ProcessBuilder("rm", path).start(); System.out.println("Successfully compressed file: " + path); } } catch (Exception e) { System.out.println("An error occurred while compressing image: " + path); hasError = true; } finally { // Clean up any temporary PNG images. try { new ProcessBuilder("rm", webPPath + PNG).start(); if (needsConvertToPng) { new ProcessBuilder("rm", basePath + PNG).start(); } if (hasError) { new ProcessBuilder("rm", webPPath).start(); } } catch (Exception e) { /* Consume the exception. */ } } })); // Traverse any subdirectories. if (isRecursive) { Arrays.stream(getImagesOrDirectories(directory, false)).forEach(file -> traverseDirectory(executor, file)); } } private static File[] getImagesOrDirectories(final File directory, final boolean getImages) { File[] files = getImages ? directory.listFiles(IMAGE_FILTER) : directory.listFiles(DIRECTORY_FILTER); return files != null ? files : new File[0]; } private static boolean searchForOptimalQuality(final File file, final String path, final String basePath, final String webPPath, final File webPFile, final boolean needsConvertToPng) throws IOException, InterruptedException { // Perform binary search to find the best WebP compression value. long min = 0, max = 100; while (min != max) { // Generate the temporary PNG images. long quality = Math.round((min + max) / 2.0); if (getImageDissimilarity(quality, path, basePath, webPPath, needsConvertToPng, false) < qualityThreshold && isSmallerFile(webPFile, file)) { // The image can be compressed more. if (max == quality) { break; // Prevent infinite loops. } else { max = quality; } } else { // Compression is now visible to the human eye (or the file got larger). // Scale the compression back a bit (if we can). if (min == quality) { break; // Prevent infinite loops. } else { min = quality; } } } // Return true if the binary search failed to find a valid compression value. return min == 100; } private static double getImageDissimilarity(final long quality, final String path, final String basePath, final String webPPath, final boolean needsConvertToPng, final boolean isLossless) throws IOException, InterruptedException { // Generate WebP and PNG versions of the image at the input quality. List<String> arguments = Arrays.asList("cwebp", "-q", String.valueOf(quality), path, "-o", webPPath); if (isLossless) { arguments.add(1, "-lossless"); } new ProcessBuilder(arguments).start().waitFor(); new ProcessBuilder("dwebp", webPPath, "-o", webPPath + PNG).start().waitFor(); if (needsConvertToPng) { new ProcessBuilder("sips", "-s", "format", "png", path, "--out", basePath + PNG).start().waitFor(); } // Verify that the image dimensions aren't too small to work with Butteraugli. BufferedReader input = new BufferedReader(new InputStreamReader( new ProcessBuilder("file", basePath + PNG).start().getInputStream())); String[] dimensions = input.readLine().split(",")[1].split("x"); input.close(); double width = Integer.valueOf(dimensions[0].trim()); double height = Integer.valueOf(dimensions[1].trim()); boolean performResize = Math.min(width, height) < BUTTERAUGLI_MINIMUM_SIZE; if (performResize) { // The image is too small to work with Butteraugli. Resize it. new ProcessBuilder("cp", "-r", path, path + ORIGINAL).start().waitFor(); new ProcessBuilder("cp", "-r", webPPath, webPPath + ORIGINAL).start().waitFor(); int newHeight = (int) Math.ceil((BUTTERAUGLI_MINIMUM_SIZE / Math.min(width, height)) * Math.max(width, height)); new ProcessBuilder("sips", "-Z", String.valueOf(newHeight), basePath + PNG).start().waitFor(); new ProcessBuilder("sips", "-Z", String.valueOf(newHeight), webPPath + PNG).start().waitFor(); } // Read in the dissimilarity result from Butteraugli. input = new BufferedReader(new InputStreamReader( new ProcessBuilder("compare_pngs", webPPath + PNG, basePath + PNG).start().getInputStream())); String line = input.readLine(); input.close(); if (performResize) { new ProcessBuilder("mv", path + ORIGINAL, path).start().waitFor(); new ProcessBuilder("mv", webPPath + ORIGINAL, webPPath).start().waitFor(); } return Double.valueOf(line); } private static boolean isSmallerFile(final File fileA, final File fileB) { return fileA.length() < fileB.length(); } private static class ImageFilenameFilter implements FilenameFilter { @Override public boolean accept(final File current, final String name) { // 9-patch images are not supported in the WebP format. return name.endsWith(JPG) || name.endsWith(JPEG) || (name.endsWith(PNG) && !name.endsWith(NINE_PATCH)); } } private static class DirectoryFilenameFilter implements FileFilter { @Override public boolean accept(final File file) { return file.isDirectory(); } } }
package org.apache.james.util; import java.util.Hashtable; /** * @author Federico Barbieri <fede@apache.org> */ public class Lock { private Hashtable locks = new Hashtable(); public boolean isLocked(final Object key) { return (locks.get(key) != null); } public boolean canI(final Object key) { Object o = locks.get( key ); if (null == o || o == this.getCallerId()) { return true; } return false; } public boolean lock(final Object key) { Object theLock; synchronized(this) { theLock = locks.get(key); if (null == theLock) { locks.put(key, getCallerId()); return true; } else if (getCallerId() == theLock) { return true; } else { return false; } } } public boolean unlock(final Object key) { Object theLock; synchronized (this) { theLock = locks.get(key); if (null == theLock) { return true; } else if (getCallerId() == theLock) { locks.remove(key); return true; } else { return false; } } } private Object getCallerId() { return Thread.currentThread(); } }
package com.binatechnologies.varsim; import org.apache.log4j.Logger; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.kohsuke.args4j.Option; import java.io.*; import java.util.Random; /** * @author johnmu */ public class RandBED2VCF extends randVCFgenerator { private final static Logger log = Logger.getLogger(RandBED2VCF.class.getName()); SimpleReference ref; int num_novel_added = 0; int var_idx = 0; byte[] insert_seq = null; // parameters static final int MIN_LEN_ARG = 50; @Option(name = "-min_len", usage = "Minimum variant length ["+MIN_LEN_ARG+"], inclusive") int min_length_lim = MIN_LEN_ARG; static final int MAX_LEN_ARG = 1000000; @Option(name = "-max_len", usage = "Maximum variant length ["+MAX_LEN_ARG+"], inclusive") int max_length_lim = MAX_LEN_ARG; static final int SEED_ARG = 333; @Option(name = "-seed", usage = "Seed for random sampling ["+SEED_ARG+"]") int seed = 333; @Option(name = "-ref", usage = "Reference Genome",metaVar = "file",required = true) String reference_filename; @Option(name = "-ins", usage = "Known Insertion Sequences",metaVar = "file",required = true) String insert_filename; @Option(name = "-ins_bed", usage = "Known Insertion BED file",metaVar = "BED_file",required = true) String ins_bed_filename; @Option(name = "-del_bed", usage = "Known Deletion BED file",metaVar = "BED_file",required = true) String del_bed_filename; RandBED2VCF() { super(); num_novel_added = 0; var_idx = 0; } /** * @param args */ public static void main(String[] args) { RandBED2VCF runner = new RandBED2VCF(); runner.run(args); } // outputs VCF record with random phase void rand_output_vcf_record(BufferedWriter bw, Variant var) throws IOException { // this is ok if both the same genotype // the second call will return fill_in_seq(var, insert_seq, var.getGeno().geno[0]); fill_in_seq(var, insert_seq, var.getGeno().geno[1]); output_vcf_record(bw, var); } // remember BED is 0-based Variant parse_bed_line(String line, Variant.Type type) { String[] ll = line.split("\t"); if (ll.length < 4) { return new Variant(); } // String chr_name, int chr, int pos, int del, byte[] ref, // FlexSeq[] alts, byte[] phase, String var_id, String filter, // String ref_deleted int chr_idx = variantFileParser.getChromIndex(ll[0]); int pos = Integer.parseInt(ll[1]); int end = Integer.parseInt(ll[2]); int len = Integer.parseInt(ll[3]); if (len > max_length_lim || len < min_length_lim) { return null; } FlexSeq[] alts = new FlexSeq[1]; String var_idx_str = ""; byte[] ref_seq; if (type == Variant.Type.Deletion) { alts[0] = new FlexSeq(); var_idx_str = "del_"; ref_seq = ref.byteRange(chr_idx, pos, end); } else if (type == Variant.Type.Insertion) { alts[0] = new FlexSeq(FlexSeq.Type.INS, len); var_idx_str = "ins_"; ref_seq = new byte[0]; } else { log.error("Bad type!"); return null; } var_idx_str += var_idx; var_idx++; Genotypes geno = new Genotypes(chr_idx, 1, rand); return new Variant(ll[0], chr_idx, pos, ref_seq.length, ref_seq, alts, geno.geno, false, var_idx_str, "PASS", ""); } private void process_bed(BufferedWriter out, BufferedReader bed_reader, Variant.Type type) throws IOException { String line; while ((line = bed_reader.readLine()) != null) { Variant var = parse_bed_line(line, type); if (var == null) { // System.err.println("Bad variant or not a variant line"); continue; } // write out variant try { if (!var.isRef()) { rand_output_vcf_record(out, var); } } catch (IOException e) { e.printStackTrace(); } } } public void run(String[] args) { String usage = "Generates a VCF file (to stdout) from an insertion and a deletion BED file. Insertions sequences\n" + "are randomly sampled from the insert_seq file. This is designed for the Venter SV BED files. \n"; CmdLineParser parser = new CmdLineParser(this); // if you have a wider console, you could increase the value; // here 80 is also the default parser.setUsageWidth(80); try { parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); System.err.println("java -jar randbed2vcf [options...] arguments..."); // print the list of available options parser.printUsage(System.err); System.err.println(usage); System.err.println(); return; } if (max_length_lim < min_length_lim) { log.error("Bad lengths"); } rand = new Random(seed); log.info("Reading reference"); ref = new SimpleReference(reference_filename); // read in the insert sequences log.info("Reading insert sequences"); insert_seq = null; try { FileReader fileReader = new FileReader(insert_filename); BufferedReader bufferedReader = new BufferedReader(fileReader); StringBuilder sb = new StringBuilder(); String line = null; while ((line = bufferedReader.readLine()) != null) { line = line.trim(); sb.append(line); } bufferedReader.close(); insert_seq = sb.toString().getBytes("US-ASCII"); } catch (IOException e) { e.printStackTrace(); } BufferedReader ins_bed_reader = null; BufferedReader del_bed_reader = null; try { ins_bed_reader = new BufferedReader(new FileReader(ins_bed_filename)); del_bed_reader = new BufferedReader(new FileReader(del_bed_filename)); } catch (IOException e) { e.printStackTrace(); return; } // read through DGV file again and output the new sampled VCF file log.info("Writing VCF file"); // write the header System.out.print("##fileformat=VCFv4.0\n"); System.out .print("##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">\n"); System.out .print("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\tVenter\n"); BufferedWriter out = null; try { out = new BufferedWriter(new OutputStreamWriter(System.out)); } catch (Exception e) { e.printStackTrace(); } try { process_bed(out, del_bed_reader, Variant.Type.Deletion); process_bed(out, ins_bed_reader, Variant.Type.Insertion); out.flush(); out.close(); } catch (IOException e) { log.error(e); } } }
package org.voltdb.regressionsuites; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLDecoder; import junit.framework.Test; import org.voltdb.BackendTarget; import org.voltdb.VoltTable; import org.voltdb.VoltDB.Configuration; import org.voltdb.benchmark.tpcc.TPCCProjectBuilder; import org.voltdb.catalog.LoadCatalogToString; import org.voltdb.client.Client; /** * Tests a mix of multi-partition and single partition procedures on a * mix of replicated and partititioned tables on a mix of single-site and * multi-site VoltDB instances. * */ public class TestCatalogUpdateSuite extends RegressionSuite { // procedures used by these tests static Class<?>[] BASEPROCS = { org.voltdb.benchmark.tpcc.procedures.InsertNewOrder.class, org.voltdb.benchmark.tpcc.procedures.SelectAll.class, org.voltdb.benchmark.tpcc.procedures.delivery.class }; static Class<?>[] EXPANDEDPROCS = { org.voltdb.benchmark.tpcc.procedures.InsertNewOrder.class, org.voltdb.benchmark.tpcc.procedures.SelectAll.class, org.voltdb.benchmark.tpcc.procedures.delivery.class, org.voltdb.benchmark.tpcc.procedures.slev.class }; static Class<?>[] CONFLICTPROCS = { org.voltdb.catalog.InsertNewOrder.class, org.voltdb.benchmark.tpcc.procedures.SelectAll.class, org.voltdb.benchmark.tpcc.procedures.delivery.class }; static Class<?>[] SOMANYPROCS = { org.voltdb.catalog.InsertNewOrder.class, org.voltdb.benchmark.tpcc.procedures.SelectAll.class, org.voltdb.benchmark.tpcc.procedures.neworder.class, org.voltdb.benchmark.tpcc.procedures.ostatByCustomerId.class, org.voltdb.benchmark.tpcc.procedures.ostatByCustomerName.class, org.voltdb.benchmark.tpcc.procedures.paymentByCustomerId.class, org.voltdb.benchmark.tpcc.procedures.paymentByCustomerName.class, org.voltdb.benchmark.tpcc.procedures.slev.class, org.voltdb.benchmark.tpcc.procedures.delivery.class }; /** * Constructor needed for JUnit. Should just pass on parameters to superclass. * @param name The name of the method to test. This is just passed to the superclass. */ public TestCatalogUpdateSuite(String name) { super(name); } public void testUpdate() throws Exception { Client client = getClient(); String newCatalogURL; VoltTable[] results; testStuffThatShouldObviouslyFail(client); newCatalogURL = Configuration.getPathToCatalogForTest("catalogupdate-onesite-expanded.jar"); results = client.callProcedure("@UpdateApplicationCatalog", newCatalogURL); assertTrue(results.length == 0); newCatalogURL = Configuration.getPathToCatalogForTest("catalogupdate-onesite-expanded.jar"); results = client.callProcedure("@UpdateApplicationCatalog", newCatalogURL); assertTrue(results.length == 0); newCatalogURL = Configuration.getPathToCatalogForTest("catalogupdate-onesite-base.jar"); results = client.callProcedure("@UpdateApplicationCatalog", newCatalogURL); assertTrue(results.length == 0); newCatalogURL = Configuration.getPathToCatalogForTest("catalogupdate-onesite-conflict.jar"); results = client.callProcedure("@UpdateApplicationCatalog", newCatalogURL); assertTrue(results.length == 0); assertTrue(true); } public void loadSomeData() { } public void queryAndVerifySomeData() { } public void testStuffThatShouldObviouslyFail(Client client) throws UnsupportedEncodingException { String newCatalogURL; newCatalogURL = Configuration.getPathToCatalogForTest("catalogupdate-onesite-addtables.jar"); try { client.callProcedure("@UpdateApplicationCatalog", newCatalogURL); fail(); } catch (Exception e) { assertTrue(e.getMessage().startsWith("The requested catalog change is not")); } URL url = LoadCatalogToString.class.getResource("catalog.txt"); newCatalogURL = URLDecoder.decode(url.getPath(), "UTF-8"); try { client.callProcedure("@UpdateApplicationCatalog", newCatalogURL); fail(); } catch (Exception e) { assertTrue(e.getMessage().startsWith("Unable to read from catalog")); } newCatalogURL = Configuration.getPathToCatalogForTest("catalogupdate-onesite-many.jar"); try { client.callProcedure("@UpdateApplicationCatalog", newCatalogURL); fail(); } catch (Exception e) { assertTrue(e.getMessage().startsWith("The requested catalog change is too large")); } } /** * Build a list of the tests that will be run when TestTPCCSuite gets run by JUnit. * Use helper classes that are part of the RegressionSuite framework. * This particular class runs all tests on the the local JNI backend with both * one and two partition configurations, as well as on the hsql backend. * * @return The TestSuite containing all the tests to be run. */ static public Test suite() { // the suite made here will all be using the tests from this class MultiConfigSuiteBuilder builder = new MultiConfigSuiteBuilder(TestCatalogUpdateSuite.class); // CONFIG #1: 1 Local Site/Partitions running on JNI backend // get a server config for the native backend with one sites/partitions VoltServerConfig config = new LocalSingleProcessServer("catalogupdate-onesite-base.jar", 1, BackendTarget.NATIVE_EE_JNI); // build up a project builder for the workload TPCCProjectBuilder project = new TPCCProjectBuilder(); project.addDefaultSchema(); project.addDefaultPartitioning(); project.addProcedures(BASEPROCS); // build the jarfile config.compile(project); // add this config to the set of tests to run builder.addServerConfig(config); // DELTA CATALOGS FOR TESTING // Build a new catalog config = new LocalSingleProcessServer("catalogupdate-onesite-addtables.jar", 1, BackendTarget.NATIVE_EE_JNI); project = new TPCCProjectBuilder(); project.addDefaultSchema(); project.addSchema(TestCatalogUpdateSuite.class.getResource("testorderby-ddl.sql").getPath()); project.addDefaultPartitioning(); project.addProcedures(BASEPROCS); config.compile(project); // Build a new catalog config = new LocalSingleProcessServer("catalogupdate-onesite-expanded.jar", 1, BackendTarget.NATIVE_EE_JNI); project = new TPCCProjectBuilder(); project.addDefaultSchema(); project.addDefaultPartitioning(); project.addProcedures(EXPANDEDPROCS); config.compile(project); // Build a new catalog config = new LocalSingleProcessServer("catalogupdate-onesite-conflict.jar", 1, BackendTarget.NATIVE_EE_JNI); project = new TPCCProjectBuilder(); project.addDefaultSchema(); project.addDefaultPartitioning(); project.addProcedures(CONFLICTPROCS); config.compile(project); // Build a new catalog config = new LocalSingleProcessServer("catalogupdate-onesite-many.jar", 1, BackendTarget.NATIVE_EE_JNI); project = new TPCCProjectBuilder(); project.addDefaultSchema(); project.addDefaultPartitioning(); project.addProcedures(SOMANYPROCS); config.compile(project); // Build a new catalog /*config = new LocalSingleProcessServer("catalogupdate-onesite-expanded.jar", 1, BackendTarget.NATIVE_EE_JNI); project = new TPCCProjectBuilder(); project.addDefaultSchema(); project.addDefaultPartitioning(); project.addProcedures(BASEPROCS); UserInfo[] users; project.addUsers(users) config.compile(project);*/ return builder; } }
package com.jme.math; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.logging.Level; import com.jme.util.LoggingSystem; /* * -- Added *Local methods to cut down on object creation - JS */ /** * <code>Vector3f</code> defines a Vector for a three float value tuple. * <code>Vector3f</code> can represent any three dimensional value, such as a * vertex, a normal, etc. Utility methods are also included to aid in * mathematical calculations. * * @author Mark Powell * @author Joshua Slack * @version $Id: Vector3f.java,v 1.41 2006-04-20 14:53:21 nca Exp $ */ public class Vector3f implements Externalizable { private static final long serialVersionUID = 1L; public final static Vector3f ZERO = new Vector3f(0, 0, 0); public final static Vector3f UNIT_X = new Vector3f(1, 0, 0); public final static Vector3f UNIT_Y = new Vector3f(0, 1, 0); public final static Vector3f UNIT_Z = new Vector3f(0, 0, 1); public final static Vector3f UNIT_XYZ = new Vector3f(1, 1, 1); /** * the x value of the vector. */ public float x; /** * the y value of the vector. */ public float y; /** * the z value of the vector. */ public float z; /** * Constructor instantiates a new <code>Vector3f</code> with default * values of (0,0,0). * */ public Vector3f() { x = y = z = 0; } /** * Constructor instantiates a new <code>Vector3f</code> with provides * values. * * @param x * the x value of the vector. * @param y * the y value of the vector. * @param z * the z value of the vector. */ public Vector3f(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } /** * Constructor instantiates a new <code>Vector3f</code> that is a copy * of the provided vector * @param copy The Vector3f to copy */ public Vector3f(Vector3f copy) { this.set(copy); } /** * <code>set</code> sets the x,y,z values of the vector based on passed * parameters. * * @param x * the x value of the vector. * @param y * the y value of the vector. * @param z * the z value of the vector. * @return this vector */ public Vector3f set(float x, float y, float z) { this.x = x; this.y = y; this.z = z; return this; } /** * <code>set</code> sets the x,y,z values of the vector by copying the * supplied vector. * * @param vect * the vector to copy. * @return this vector */ public Vector3f set(Vector3f vect) { this.x = vect.x; this.y = vect.y; this.z = vect.z; return this; } /** * * <code>add</code> adds a provided vector to this vector creating a * resultant vector which is returned. If the provided vector is null, null * is returned. * * @param vec * the vector to add to this. * @return the resultant vector. */ public Vector3f add(Vector3f vec) { if (null == vec) { LoggingSystem.getLogger().log(Level.WARNING, "Provided vector is " + "null, null returned."); return null; } return new Vector3f(x + vec.x, y + vec.y, z + vec.z); } /** * * <code>add</code> adds the values of a provided vector storing the * values in the supplied vector. * * @param vec * the vector to add to this * @param result * the vector to store the result in * @return result returns the supplied result vector. */ public Vector3f add(Vector3f vec, Vector3f result) { result.x = x + vec.x; result.y = y + vec.y; result.z = z + vec.z; return result; } /** * <code>addLocal</code> adds a provided vector to this vector internally, * and returns a handle to this vector for easy chaining of calls. If the * provided vector is null, null is returned. * * @param vec * the vector to add to this vector. * @return this */ public Vector3f addLocal(Vector3f vec) { if (null == vec) { LoggingSystem.getLogger().log(Level.WARNING, "Provided vector is " + "null, null returned."); return null; } x += vec.x; y += vec.y; z += vec.z; return this; } /** * * <code>add</code> adds the provided values to this vector, creating a * new vector that is then returned. * * @param addX * the x value to add. * @param addY * the y value to add. * @param addZ * the z value to add. * @return the result vector. */ public Vector3f add(float addX, float addY, float addZ) { return new Vector3f(x + addX, y + addY, z + addZ); } /** * <code>addLocal</code> adds the provided values to this vector * internally, and returns a handle to this vector for easy chaining of * calls. * * @param addX * value to add to x * @param addY * value to add to y * @param addZ * value to add to z * @return this */ public Vector3f addLocal(float addX, float addY, float addZ) { x += addX; y += addY; z += addZ; return this; } /** * * <code>scaleAdd</code> multiplies this vector by a scalar then adds the * given Vector3f. * * @param scalar * the value to multiply this vector by. * @param add * the value to add */ public void scaleAdd(float scalar, Vector3f add) { x = x * scalar + add.x; y = y * scalar + add.y; z = z * scalar + add.z; } /** * * <code>scaleAdd</code> multiplies the given vector by a scalar then adds * the given vector. * * @param scalar * the value to multiply this vector by. * @param mult * the value to multiply the scalar by * @param add * the value to add */ public void scaleAdd(float scalar, Vector3f mult, Vector3f add) { this.x = mult.x * scalar + add.x; this.y = mult.y * scalar + add.y; this.z = mult.z * scalar + add.z; } /** * * <code>dot</code> calculates the dot product of this vector with a * provided vector. If the provided vector is null, 0 is returned. * * @param vec * the vector to dot with this vector. * @return the resultant dot product of this vector and a given vector. */ public float dot(Vector3f vec) { if (null == vec) { LoggingSystem.getLogger().log(Level.WARNING, "Provided vector is " + "null, 0 returned."); return 0; } return x * vec.x + y * vec.y + z * vec.z; } /** * <code>cross</code> calculates the cross product of this vector with a * parameter vector v. * * @param v * the vector to take the cross product of with this. * @return the cross product vector. */ public Vector3f cross(Vector3f v) { return new Vector3f(((y * v.z) - (z * v.y)), ((z * v.x) - (x * v.z)), ((x * v.y) - (y * v.x))); } /** * <code>cross</code> calculates the cross product of this vector with a * parameter vector v. The result is stored in <code>result</code> * * @param v * the vector to take the cross product of with this. * @param result * the vector to store the cross product result. * @return result, after recieving the cross product vector. */ public Vector3f cross(Vector3f v,Vector3f result) { float resX = ((y * v.z) - (z * v.y)); float resY = ((z * v.x) - (x * v.z)); float resZ = ((x * v.y) - (y * v.x)); result.set(resX, resY, resZ); return result; } /** * <code>crossLocal</code> calculates the cross product of this vector * with a parameter vector v. * * @param v * the vector to take the cross product of with this. * @return this. */ public Vector3f crossLocal(Vector3f v) { float tempx, tempy; tempx = (y * v.z) - (z * v.y); tempy = (z * v.x) - (x * v.z); z = (x * v.y) - (y * v.x); x = tempx; y = tempy; return this; } /** * <code>length</code> calculates the magnitude of this vector. * * @return the length or magnitude of the vector. */ public float length() { return FastMath.sqrt(lengthSquared()); } /** * <code>lengthSquared</code> calculates the squared value of the * magnitude of the vector. * * @return the magnitude squared of the vector. */ public float lengthSquared() { return x * x + y * y + z * z; } /** * <code>distanceSquared</code> calculates the distance squared between * this vector and vector v. * * @param v the second vector to determine the distance squared. * @return the distance squared between the two vectors. */ public float distanceSquared(Vector3f v) { double dx = x - v.x; double dy = y - v.y; double dz = z - v.z; return (float) (dx * dx + dy * dy + dz * dz); } /** * <code>distance</code> calculates the distance between this vector and * vector v. * * @param v the second vector to determine the distance. * @return the distance between the two vectors. */ public float distance(Vector3f v) { return FastMath.sqrt(distanceSquared(v)); } /** * * <code>mult</code> multiplies this vector by a scalar. The resultant * vector is returned. * * @param scalar * the value to multiply this vector by. * @return the new vector. */ public Vector3f mult(float scalar) { return new Vector3f(x * scalar, y * scalar, z * scalar); } /** * * <code>mult</code> multiplies this vector by a scalar. The resultant * vector is supplied as the second parameter and returned. * * @param scalar the scalar to multiply this vector by. * @param product the product to store the result in. * @return product */ public Vector3f mult(float scalar, Vector3f product) { if (null == product) { product = new Vector3f(); } product.x = x * scalar; product.y = y * scalar; product.z = z * scalar; return product; } /** * <code>multLocal</code> multiplies this vector by a scalar internally, * and returns a handle to this vector for easy chaining of calls. * * @param scalar * the value to multiply this vector by. * @return this */ public Vector3f multLocal(float scalar) { x *= scalar; y *= scalar; z *= scalar; return this; } /** * <code>multLocal</code> multiplies a provided vector to this vector * internally, and returns a handle to this vector for easy chaining of * calls. If the provided vector is null, null is returned. * * @param vec * the vector to mult to this vector. * @return this */ public Vector3f multLocal(Vector3f vec) { if (null == vec) { LoggingSystem.getLogger().log(Level.WARNING, "Provided vector is " + "null, null returned."); return null; } x *= vec.x; y *= vec.y; z *= vec.z; return this; } /** * <code>multLocal</code> multiplies a provided vector to this vector * internally, and returns a handle to this vector for easy chaining of * calls. If the provided vector is null, null is returned. * * @param vec * the vector to mult to this vector. * @return this */ public Vector3f mult(Vector3f vec) { if (null == vec) { LoggingSystem.getLogger().log(Level.WARNING, "Provided vector is " + "null, null returned."); return null; } return new Vector3f(x * vec.x, y * vec.y, z * vec.z); } /** * <code>divide</code> divides the values of this vector by a scalar and * returns the result. The values of this vector remain untouched. * * @param scalar * the value to divide this vectors attributes by. * @return the result <code>Vector</code>. */ public Vector3f divide(float scalar) { scalar = 1f/scalar; return new Vector3f(x * scalar, y * scalar, z * scalar); } /** * <code>divideLocal</code> divides this vector by a scalar internally, * and returns a handle to this vector for easy chaining of calls. Dividing * by zero will result in an exception. * * @param scalar * the value to divides this vector by. * @return this */ public Vector3f divideLocal(float scalar) { scalar = 1f/scalar; x *= scalar; y *= scalar; z *= scalar; return this; } /** * <code>divide</code> divides the values of this vector by a scalar and * returns the result. The values of this vector remain untouched. * * @param scalar * the value to divide this vectors attributes by. * @return the result <code>Vector</code>. */ public Vector3f divide(Vector3f scalar) { return new Vector3f(x / scalar.x, y / scalar.y, z / scalar.z); } /** * <code>divideLocal</code> divides this vector by a scalar internally, * and returns a handle to this vector for easy chaining of calls. Dividing * by zero will result in an exception. * * @param scalar * the value to divides this vector by. * @return this */ public Vector3f divideLocal(Vector3f scalar) { x /= scalar.x; y /= scalar.y; z /= scalar.z; return this; } /** * * <code>negate</code> returns the negative of this vector. All values are * negated and set to a new vector. * * @return the negated vector. */ public Vector3f negate() { return new Vector3f(-x, -y, -z); } /** * * <code>negateLocal</code> negates the internal values of this vector. * * @return this. */ public Vector3f negateLocal() { x = -x; y = -y; z = -z; return this; } /** * * <code>subtract</code> subtracts the values of a given vector from those * of this vector creating a new vector object. If the provided vector is * null, null is returned. * * @param vec * the vector to subtract from this vector. * @return the result vector. */ public Vector3f subtract(Vector3f vec) { return new Vector3f(x - vec.x, y - vec.y, z - vec.z); } /** * <code>subtractLocal</code> subtracts a provided vector to this vector * internally, and returns a handle to this vector for easy chaining of * calls. If the provided vector is null, null is returned. * * @param vec * the vector to subtract * @return this */ public Vector3f subtractLocal(Vector3f vec) { if (null == vec) { LoggingSystem.getLogger().log(Level.WARNING, "Provided vector is " + "null, null returned."); return null; } x -= vec.x; y -= vec.y; z -= vec.z; return this; } /** * * <code>subtract</code> * * @param vec * the vector to subtract from this * @param result * the vector to store the result in * @return result */ public Vector3f subtract(Vector3f vec, Vector3f result) { if(result == null) { result = new Vector3f(); } result.x = x - vec.x; result.y = y - vec.y; result.z = z - vec.z; return result; } /** * * <code>subtract</code> subtracts the provided values from this vector, * creating a new vector that is then returned. * * @param subtractX * the x value to subtract. * @param subtractY * the y value to subtract. * @param subtractZ * the z value to subtract. * @return the result vector. */ public Vector3f subtract(float subtractX, float subtractY, float subtractZ) { return new Vector3f(x - subtractX, y - subtractY, z - subtractZ); } /** * <code>subtractLocal</code> subtracts the provided values from this vector * internally, and returns a handle to this vector for easy chaining of * calls. * * @param subtractX * the x value to subtract. * @param subtractY * the y value to subtract. * @param subtractZ * the z value to subtract. * @return this */ public Vector3f subtractLocal(float subtractX, float subtractY, float subtractZ) { x -= subtractX; y -= subtractY; z -= subtractZ; return this; } /** * <code>normalize</code> returns the unit vector of this vector. * * @return unit vector of this vector. */ public Vector3f normalize() { float length = length(); if (length != 0) { return divide(length); } else { return divide(1); } } /** * <code>normalizeLocal</code> makes this vector into a unit vector of * itself. * * @return this. */ public Vector3f normalizeLocal() { float length = length(); if (length != 0) { return divideLocal(length); } else { return this; } } /** * <code>zero</code> resets this vector's data to zero internally. */ public void zero() { x = y = z = 0; } /** * <code>angleBetween</code> returns (in radians) the angle between two vectors. * It is assumed that both this vector and the given vector are unit vectors (iow, normalized). * * @param otherVector a unit vector to find the angle against * @return the angle in radians. */ public float angleBetween(Vector3f otherVector) { float dotProduct = dot(otherVector); float angle = FastMath.acos(dotProduct); return angle; } /** * Sets this vector to the interpolation by changeAmnt from this to the finalVec * this=(1-changeAmnt)*this + changeAmnt * finalVec * @param finalVec The final vector to interpolate towards * @param changeAmnt An amount between 0.0 - 1.0 representing a precentage * change from this towards finalVec */ public void interpolate(Vector3f finalVec, float changeAmnt) { this.x=(1-changeAmnt)*this.x + changeAmnt*finalVec.x; this.y=(1-changeAmnt)*this.y + changeAmnt*finalVec.y; this.z=(1-changeAmnt)*this.z + changeAmnt*finalVec.z; } /** * Sets this vector to the interpolation by changeAmnt from beginVec to finalVec * this=(1-changeAmnt)*beginVec + changeAmnt * finalVec * @param beginVec the beging vector (changeAmnt=0) * @param finalVec The final vector to interpolate towards * @param changeAmnt An amount between 0.0 - 1.0 representing a precentage * change from beginVec towards finalVec */ public void interpolate(Vector3f beginVec,Vector3f finalVec, float changeAmnt) { this.x=(1-changeAmnt)*beginVec.x + changeAmnt*finalVec.x; this.y=(1-changeAmnt)*beginVec.y + changeAmnt*finalVec.y; this.z=(1-changeAmnt)*beginVec.z + changeAmnt*finalVec.z; } /** * Check a vector... if it is null or its floats are NaN or infinite, * return false. Else return true. * @param vector the vector to check * @return true or false as stated above. */ public static boolean isValidVector(Vector3f vector) { if (vector == null) return false; if (Float.isNaN(vector.x) || Float.isNaN(vector.y) || Float.isNaN(vector.z)) return false; if (Float.isInfinite(vector.x) || Float.isInfinite(vector.y) || Float.isInfinite(vector.z)) return false; return true; } /** * <code>clone</code> creates a new Vector3f object containing the same * data as this one. * * @return the new Vector3f */ public Object clone() { return new Vector3f(x, y, z); } /** * Saves this Vector3f into the given float[] object. * @param floats The float[] to take this vector3f * @return The floats[] after saving. */ public float[] toArray(float[] floats) { floats[0]=x;floats[1]=y;floats[2]=z; return floats; } /** * are these two vectors the same? they are is they both have the same x,y, * and z values. * * @param o * the object to compare for equality * @return true if they are equal */ public boolean equals(Object o) { if (!(o instanceof Vector3f)) { return false; } if (this == o) { return true; } Vector3f comp = (Vector3f) o; if (x != comp.x) return false; if (y != comp.y) return false; if (z != comp.z) return false; return true; } /** * <code>hashCode</code> returns a unique code for this vector object based * on it's values. If two vectors are logically equivalent, they will return * the same hash code value. * @return the hash code value of this vector. */ public int hashCode() { int hash = 7; hash += 31 * hash + Float.floatToIntBits(x); hash += 31 * hash + Float.floatToIntBits(y); hash += 31 * hash + Float.floatToIntBits(z); return hash; } /** * <code>toString</code> returns the string representation of this vector. * The format is: * * org.jme.math.Vector3f [X=XX.XXXX, Y=YY.YYYY, Z=ZZ.ZZZZ] * * @return the string representation of this vector. */ public String toString() { return "com.jme.math.Vector3f [X=" + x + ", Y=" + y + ", Z=" + z + "]"; } /** * Used with serialization. Not to be called manually. * @param in * @throws IOException * @throws ClassNotFoundException * @see java.io.Externalizable */ public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { x=in.readFloat(); y=in.readFloat(); z=in.readFloat(); } /** * Used with serialization. Not to be called manually. * @param out * @throws IOException * @see java.io.Externalizable */ public void writeExternal(ObjectOutput out) throws IOException { out.writeFloat(x); out.writeFloat(y); out.writeFloat(z); } }
package com.blocklaunch.spongewarps; import java.io.File; import java.io.IOException; import ninja.leaping.configurate.ConfigurationNode; import ninja.leaping.configurate.commented.CommentedConfigurationNode; import ninja.leaping.configurate.loader.ConfigurationLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongepowered.api.Game; import org.spongepowered.api.event.Subscribe; import org.spongepowered.api.event.state.PreInitializationEvent; import org.spongepowered.api.plugin.Plugin; import org.spongepowered.api.plugin.PluginContainer; import org.spongepowered.api.service.command.CommandService; import org.spongepowered.api.service.config.DefaultConfig; import org.spongepowered.api.service.scheduler.SynchronousScheduler; import com.blocklaunch.spongewarps.commands.DeleteWarpCommand; import com.blocklaunch.spongewarps.commands.ListWarpsCommand; import com.blocklaunch.spongewarps.commands.SetWarpCommand; import com.blocklaunch.spongewarps.commands.WarpCommand; import com.google.inject.Inject; @Plugin(id = "SpongeWarps", name = "SpongeWarps", version = "1.0") public class SpongeWarps { /** * Prefix to display at the beginning of messages to player, console * outputs, etc. */ public static final String PREFIX = "[Warps]"; public static Game game; public static PluginContainer plugin; public static SynchronousScheduler scheduler; public static Logger logger = LoggerFactory.getLogger(SpongeWarps.class); public static File configFolder; public static File warpsFile; @Inject @DefaultConfig(sharedRoot = true) private File configFile; @Inject @DefaultConfig(sharedRoot = true) private ConfigurationLoader<CommentedConfigurationNode> configManager; /** * Called when the server is being started. Similar to Bukkit's onEnable() * function * * @param event */ @Subscribe public void preInit(PreInitializationEvent event) { game = event.getGame(); scheduler = game.getSyncScheduler(); plugin = game.getPluginManager().getPlugin("SpongeWarps").get(); configFolder = configFile.getParentFile(); warpsFile = new File(SpongeWarps.configFolder, "warps.json"); // Create default config if it doesn't exist if (!configFile.exists()) { saveDefaultConfig(); } else { loadConfig(); } // Load warps WarpManager.loadWarps(); // Register commands CommandService cmdService = game.getCommandDispatcher(); logger.info(PREFIX + " Registering commands"); cmdService.register(plugin, new SetWarpCommand(), "setwarp", "addwarp"); cmdService.register(plugin, new WarpCommand(), "warp"); cmdService.register(plugin, new DeleteWarpCommand(), "deletewarp", "delwarp"); cmdService.register(plugin, new ListWarpsCommand(), "listwarps", "listwarp"); } /** * Reads in config values supplied from the ConfigManager. Falls back on the * default configuration values in Settings */ private void loadConfig() { ConfigurationNode config = null; try { config = configManager.load(); Settings.warpDelay = config.getNode("warp-delay").getInt(); Settings.pvpProtect = config.getNode("pvp-protect").getBoolean(); } catch (IOException e) { logger.warn(PREFIX + " The configuration could not be loaded! Using the default configuration"); } } /** * Saves a config file with default values if it does not already exist * * @return true if default config was successfully created, false if the * file was not created */ public void saveDefaultConfig() { try { if (!configFile.exists()) { logger.info(PREFIX + " Generating config file..."); configFile.createNewFile(); ConfigurationNode config = configManager.load(); // Populate config with default values config.getNode("warp-delay").setValue(Settings.warpDelay); config.getNode("pvp-protect").setValue(Settings.pvpProtect); configManager.save(config); logger.info(PREFIX + " Config file successfully generated."); } else { return; } } catch (IOException exception) { logger.warn(PREFIX + " The default configuration could not be created!"); } } }
package org.voltdb.regressionsuites; import java.io.IOException; import org.voltdb.BackendTarget; import org.voltdb.VoltTable; import org.voltdb.client.Client; import org.voltdb.client.ProcCallException; import org.voltdb.compiler.VoltProjectBuilder; public class TestFailureDetectSuite extends RegressionSuite { public void testMultiPartitionTxnAfterFailure() throws IOException, ProcCallException { Client client = getClient(); VoltTable[] results = client.callProcedure("InsertMultiPart", 1, "desc", 100, 14.5); assertEquals(1, results[0].asScalarLong()); results = client.callProcedure("SelectMultiPart"); System.out.println(results[0].toString()); assertEquals(1, results[0].getRowCount()); LocalCluster config = (LocalCluster) m_config; config.shutDownSingleHost(0); for (int i = 0; i < 100; i++) { results = client.callProcedure("SelectMultiPart"); assertEquals(1, results[0].getRowCount()); } } public void testSinglePartitionTxnAfterFailure() throws IOException, ProcCallException { Client client = getClient(); VoltTable[] results = client.callProcedure("InsertSinglePart", 1, "desc", 100, 14.5); assertEquals(1, results[0].asScalarLong()); results = client.callProcedure("SelectSinglePart", 1); System.out.println(results[0].toString()); assertEquals(1, results[0].getRowCount()); LocalCluster config = (LocalCluster) m_config; config.shutDownSingleHost(0); // It takes a few transactions for the external volt process to actually // die, so we'll just try to do a bunch of transactions, and this will // be roughly like pulling the plug for (int i = 0; i < 100; i++) { results = client.callProcedure("UpdateSinglePart", 1, 200); assertEquals(1, results[0].getRowCount()); } } public TestFailureDetectSuite(String name) { super(name); } static public junit.framework.Test suite() { VoltServerConfig config = null; MultiConfigSuiteBuilder builder = new MultiConfigSuiteBuilder(TestFailureDetectSuite.class); VoltProjectBuilder project = new VoltProjectBuilder(); project.addSchema(TestReplicationSuite.class.getResource("replication-ddl.sql")); project.addPartitionInfo("P1", "ID"); project.addStmtProcedure("InsertSinglePart", "INSERT INTO P1 VALUES (?, ?, ?, ?);", "P1.ID: 0"); project.addStmtProcedure("UpdateSinglePart", "UPDATE P1 SET P1.NUM = ? WHERE P1.ID = ?", "P1.ID: 0"); project.addStmtProcedure("SelectSinglePart", "SELECT * FROM P1 WHERE P1.ID = ?", "P1.ID: 0"); project.addStmtProcedure("InsertMultiPart", "INSERT INTO P1 VALUES (?, ?, ?, ?);"); project.addStmtProcedure("SelectMultiPart", "SELECT * FROM P1"); project.addStmtProcedure("UpdateMultiPart", "UPDATE P1 SET P1.NUM = ?"); project.addStmtProcedure("InsertMultiPartRepl", "INSERT INTO R1 VALUES (?, ?, ?, ?);"); project.addStmtProcedure("SelectMultiPartRepl", "SELECT * FROM R1"); project.addStmtProcedure("UpdateMultiPartRepl", "UPDATE R1 SET R1.NUM = ?"); // CLUSTER, two hosts, each with two sites, replication of 1 config = new LocalCluster("replication-1-cluster.jar", 2, 2, 1, BackendTarget.NATIVE_EE_JNI); config.compile(project); builder.addServerConfig(config); // CLUSTER, three hosts, each with two sites, replication of 2 config = new LocalCluster("replication-2-cluster.jar", 2, 3, 2, BackendTarget.NATIVE_EE_JNI); config.compile(project); builder.addServerConfig(config); // // CLUSTER, four hosts, each with three sites, replication of 2 // config = new LocalCluster("replication-2-cluster.jar", 3, 4, // 2, BackendTarget.NATIVE_EE_JNI); // config.compile(project); // builder.addServerConfig(config); // // CLUSTER, 3 hosts, each with one site, replication of 1 // config = new LocalCluster("replication-odd-cluster.jar", 1, 3, // 1, BackendTarget.NATIVE_EE_JNI); // config.compile(project); // builder.addServerConfig(config); return builder; } }
package com.jme.scene; import java.io.Serializable; import java.util.*; import com.jme.bounding.BoundingVolume; import com.jme.intersection.CollisionResults; import com.jme.intersection.PickResults; import com.jme.math.Matrix3f; import com.jme.math.Quaternion; import com.jme.math.Ray; import com.jme.math.Vector3f; import com.jme.renderer.Camera; import com.jme.renderer.CloneCreator; import com.jme.renderer.Renderer; import com.jme.scene.state.LightState; import com.jme.scene.state.RenderState; import com.jme.scene.state.TextureState; import com.jme.system.DisplaySystem; /** * <code>Spatial</code> defines the base class for scene graph nodes. It * maintains a link to a parent, it's local transforms and the world's * transforms. All other nodes, such as <code>Node</code> and * <code>Geometry</code> are subclasses of <code>Spatial</code>. * * @author Mark Powell * @author Joshua Slack * @version $Id: Spatial.java,v 1.96 2006-02-20 23:28:47 llama Exp $ */ public abstract class Spatial implements Serializable { public static final int NODE = 1; public static final int GEOMETRY = 2; public static final int TRIMESH = 4; public static final int SHARED_MESH = 8; public static final int SKY_BOX = 16; public static final int TERRAIN_BLOCK = 32; public static final int TERRAIN_PAGE = 64; public static final int COMPOSITE_MESH = 128; public static final int CULL_INHERIT = 0; public static final int CULL_DYNAMIC = 1; public static final int CULL_ALWAYS = 2; public static final int CULL_NEVER = 3; public static final int LOCKED_BOUNDS = 1; public static final int LOCKED_MESH_DATA = 2; public static final int LOCKED_TRANSFORMS = 4; /** Spatial's rotation relative to its parent. */ protected Quaternion localRotation; /** Spatial's world absolute rotation. */ protected Quaternion worldRotation; /** Spatial's translation relative to its parent. */ protected Vector3f localTranslation; /** Spatial's world absolute translation. */ protected Vector3f worldTranslation; /** Spatial's scale relative to its parent. */ protected Vector3f localScale; /** Spatial's world absolute scale. */ protected Vector3f worldScale; /** * A flag indicating if scene culling should be done on this object by * inheritance, dynamically, never, or always. */ private int cullMode = CULL_INHERIT; /** Spatial's bounding volume relative to the world. */ protected BoundingVolume worldBound; /** Spatial's parent, or null if it has none. */ protected transient Node parent; /** List of default states all spatials take if none is set. */ public final static RenderState[] defaultStateList = new RenderState[RenderState.RS_MAX_STATE]; /** List of states that override any set states on a spatial if not null. */ public final static RenderState[] enforcedStateList = new RenderState[RenderState.RS_MAX_STATE]; /** RenderStates a Spatial contains during rendering. */ protected final static RenderState[] currentStates = new RenderState[RenderState.RS_MAX_STATE]; /** The render states of this spatial. */ private RenderState[] renderStateList; protected int renderQueueMode = Renderer.QUEUE_INHERIT; /** Used to determine draw order for ortho mode rendering. */ protected int zOrder = 0; /** * Used to indicate this spatial (and any below it in the case of Node) is * locked against certain changes. */ protected int lockedMode = 0; public transient float queueDistance = Float.NEGATIVE_INFINITY; /** * Flag signaling how lights are combined for this node. By default set to * INHERIT. */ protected int lightCombineMode = LightState.INHERIT; /** * Flag signaling how textures are combined for this node. By default set to * INHERIT. */ protected int textureCombineMode = TextureState.INHERIT; /** ArrayList of controllers for this spatial. */ protected ArrayList geometricalControllers = new ArrayList(); /** This spatial's name. */ protected String name; // scale values protected int frustrumIntersects = Camera.INTERSECTS_FRUSTUM; /** Defines if this spatial will be used in intersection operations or not. Default is true*/ protected boolean isCollidable = true; private static final Vector3f compVecA = new Vector3f(); private static final Quaternion compQuat = new Quaternion(); /** * Empty Constructor to be used internally only. */ public Spatial() { } /** * Constructor instantiates a new <code>Spatial</code> object setting the * rotation, translation and scale value to defaults. * * @param name * the name of the scene element. This is required for * identification and comparision purposes. */ public Spatial(String name) { this.name = name; localRotation = new Quaternion(); worldRotation = new Quaternion(); localTranslation = new Vector3f(); worldTranslation = new Vector3f(); localScale = new Vector3f(1.0f, 1.0f, 1.0f); worldScale = new Vector3f(1.0f, 1.0f, 1.0f); } /** * Sets the name of this spatial. * * @param name * The spatial's new name. */ public void setName(String name) { this.name = name; } /** * Returns the name of this spatial. * * @return This spatial's name. */ public String getName() { return name; } /** * Sets if this Spatial is to be used in intersection (collision and picking) calculations. * By default this is true. * @param isCollidable true if this Spatial is to be used in intersection calculations, false otherwise. */ public void setIsCollidable(boolean isCollidable) { this.isCollidable = isCollidable; } /** * Defines if this Spatial is to be used in intersection (collision and picking) calculations. * By default this is true. * @return true if this Spatial is to be used in intersection calculations, false otherwise. */ public boolean isCollidable() { return this.isCollidable; } /** * Adds a Controller to this Spatial's list of controllers. * * @param controller * The Controller to add * @see com.jme.scene.Controller */ public void addController(Controller controller) { if (geometricalControllers == null) { geometricalControllers = new ArrayList(); } geometricalControllers.add(controller); } /** * Removes a Controller to this Spatial's list of controllers, if it exist. * * @param controller * The Controller to remove * @return True if the Controller was in the list to remove. * @see com.jme.scene.Controller */ public boolean removeController(Controller controller) { if (geometricalControllers == null) { geometricalControllers = new ArrayList(); } return geometricalControllers.remove(controller); } /** * Returns the controller in this list of controllers at index i. * * @param i * The index to get a controller from. * @return The controller at index i. * @see com.jme.scene.Controller */ public Controller getController(int i) { if (geometricalControllers == null) { geometricalControllers = new ArrayList(); } return (Controller) geometricalControllers.get(i); } /** * Returns the ArrayList that contains this spatial's Controllers. * * @return This spatial's geometricalControllers. */ public ArrayList getControllers() { if (geometricalControllers == null) { geometricalControllers = new ArrayList(); } return geometricalControllers; } /** * * <code>getWorldBound</code> retrieves the world bound at this node * level. * * @return the world bound at this level. */ public BoundingVolume getWorldBound() { return worldBound; } /** * * <code>onDraw</code> checks the spatial with the camera to see if it should * be culled, if not, the node's draw method is called. * * @param r * the renderer used for display. */ public void onDraw(Renderer r) { int cm = getCullMode(); if (cm == CULL_ALWAYS) { return; } Camera camera = r.getCamera(); int state = camera.getPlaneState(); // check to see if we can cull this node frustrumIntersects = (parent != null ? parent.frustrumIntersects : Camera.INTERSECTS_FRUSTUM); if (cm == CULL_DYNAMIC && frustrumIntersects == Camera.INTERSECTS_FRUSTUM) { frustrumIntersects = camera.contains(worldBound); } if (cm == CULL_NEVER || frustrumIntersects != Camera.OUTSIDE_FRUSTUM) { draw(r); } camera.setPlaneState(state); } /** * <code>getType</code> returns an int representing the class type * of this Spatial. This allows avoidance of instanceof. Comparisons * are to be done via bitwise & allowing checking of superclass instance. */ public abstract int getType(); /** * * <code>draw</code> abstract method that handles drawing data to the * renderer if it is geometry and passing the call to it's children if it is * a node. * * @param r * the renderer used for display. */ public abstract void draw(Renderer r); /** * * <code>getWorldRotation</code> retrieves the absolute rotation of the * Spatial. * * @return the Spatial's world rotation matrix. */ public Quaternion getWorldRotation() { return worldRotation; } /** * * <code>getWorldTranslation</code> retrieves the absolute translation of * the spatial. * * @return the world's tranlsation vector. */ public Vector3f getWorldTranslation() { return worldTranslation; } /** * * <code>getWorldScale</code> retrieves the absolute scale factor of the * spatial. * * @return the world's scale factor. */ public Vector3f getWorldScale() { return worldScale; } /** * <code>setCullMode</code> sets how scene culling should work on this * spatial during drawing. * * CULL_DYNAMIC: Determine via the defined Camera planes whether or not this * Spatial should be culled. * * CULL_ALWAYS: Always throw away this object and any children during draw * commands. * * CULL_NEVER: Never throw away this object (always draw it) * * CULL_INHERIT: Look for a non-inherit parent and use its cull mode. * * NOTE: You must set this AFTER attaching to a parent or it will be reset * with the parent's cullMode value. * * @param mode * one of CULL_DYNAMIC, CULL_ALWAYS, CULL_INHERIT or CULL_NEVER */ public void setCullMode(int mode) { cullMode = mode; } /** * @see #setCullMode(int) * * @return the cull mode of this spatial */ public int getCullMode() { if (cullMode != CULL_INHERIT) return cullMode; else if (parent != null) return parent.getCullMode(); else return CULL_DYNAMIC; } /** * <code>rotateUpTo</code> is a util function that alters the * localrotation to point the Y axis in the direction given by newUp. * * @param newUp the up vector to use - assumed to be a unit vector. */ public void rotateUpTo(Vector3f newUp) { //First figure out the current up vector. Vector3f upY = compVecA.set(Vector3f.UNIT_Y); localRotation.multLocal(upY); // get angle between vectors float angle = upY.angleBetween(newUp); //figure out rotation axis by taking cross product Vector3f rotAxis = upY.crossLocal(newUp); // Build a rotation quat and apply current local rotation. Quaternion q = compQuat; q.fromAngleAxis(angle, rotAxis); q.mult(localRotation, localRotation); } /** * <code>lookAt</code> is a convienence method for auto-setting the * local rotation based on a position and an up vector. It computes * the rotation to transform the z-axis to point onto 'position' * and the y-axis to 'up'. Unlike {@link Quaternion#lookAt} this method * takes a world position to look at not a relative direction. * * @param position * where to look at in terms of world coordinates * @param upVector * a vector indicating the (local) up direction. * (typically {0, 1, 0} in jME.) */ public void lookAt(Vector3f position, Vector3f upVector) { compVecA.set( position ).subtractLocal( getWorldTranslation() ); getLocalRotation().lookAt( compVecA, upVector ); } /** * Calling this method tells the scenegraph that it is not necessary to * update bounds from this point in the scenegraph on down to the leaves. * This is useful for performance gains where you have scene items that do * not move (at all) or change shape and thus do not need constant * re-calculation of boundaries. * * When you call lock, the bounds are first updated to ensure current bounds * are accurate. * * @see #unlockBounds() */ public void lockBounds() { updateGeometricState(0, true); lockedMode |= LOCKED_BOUNDS; } /** * Flags this spatial and those below it in the scenegraph to not * recalculate world transforms such as translation, rotation and scale on * every update. * * This is useful for efficiency when you have scene items that stay in one * place all the time as it avoids needless recalculation of transforms. * * @see #unlockTransforms() */ public void lockTransforms() { updateWorldVectors(); lockedMode |= LOCKED_TRANSFORMS; } /** * Flags this spatial and those below it that any meshes in the specified * scenegraph location or lower will not have changes in vertex, texcoord, * normal or color data. This allows optimizations by the engine such as * creating display lists from the data. * * Calling this method does not provide a guarentee that data changes will * not be allowed or will/won't show up in the scene. It is merely a hint to * the engine. * * @param r A renderer to lock against. * @see #unlockMeshes(Renderer) */ public void lockMeshes(Renderer r) { updateRenderState(); lockedMode |= LOCKED_MESH_DATA; } /** * Flags this spatial and those below it that any meshes in the specified * scenegraph location or lower will not have changes in vertex, texcoord, * normal or color data. This allows optimizations by the engine such as * creating display lists from the data. * * Calling this method does not provide a guarentee that data changes will * not be allowed or will/won't show up in the scene. It is merely a hint to * the engine. * * Calls lockMeshes(Renderer) with the current display system's renderer. * * @see #lockMeshes(Renderer) */ public void lockMeshes() { lockMeshes(DisplaySystem.getDisplaySystem().getRenderer()); } /** * Convienence function for locking all aspects of a Spatial. * @see #lockBounds() * @see #lockTransforms() * @see #lockMeshes(Renderer) */ public void lock(Renderer r) { lockBounds(); lockTransforms(); lockMeshes(r); } /** * Convienence function for locking all aspects of a Spatial. For lockMeshes * it calls: * <code>lockMeshes(DisplaySystem.getDisplaySystem().getRenderer());</code> * * @see #lockBounds() * @see #lockTransforms() * @see #lockMeshes(Renderer) */ public void lock() { lockBounds(); lockTransforms(); lockMeshes(); } /** * Flags this spatial and those below it to allow for bounds updating (the * default). * * @see #lockBounds() */ public void unlockBounds() { lockedMode &= ~LOCKED_BOUNDS; } /** * Flags this spatial and those below it to allow for transform updating (the * default). * * @see #lockTransforms() */ public void unlockTransforms() { lockedMode &= ~LOCKED_TRANSFORMS; } /** * Flags this spatial and those below it to allow for mesh updating (the * default). Generally this means that any display lists setup will be * erased and released. * * @param r The renderer used to lock against. * @see #lockMeshes(Renderer) */ public void unlockMeshes(Renderer r) { lockedMode &= ~LOCKED_MESH_DATA; } /** * Convienence function for unlocking all aspects of a Spatial. * @see #unlockBounds() * @see #unlockTransforms() * @see #unlockMeshes(Renderer) */ public void unlock(Renderer r) { unlockBounds(); unlockTransforms(); unlockMeshes(r); } /** * Convienence function for unlocking all aspects of a Spatial. For * unlockMeshes it calls: * <code>unlockMeshes(DisplaySystem.getDisplaySystem().getRenderer());</code> * * @see #unlockBounds() * @see #unlockTransforms() * @see #unlockMeshes(Renderer) */ public void unlock() { unlockBounds(); unlockTransforms(); unlockMeshes(DisplaySystem.getDisplaySystem().getRenderer()); } /** * @return a bitwise combination of the current locks established on this * Spatial. */ public int getLocks() { return lockedMode; } /** * * <code>updateGeometricState</code> updates all the geometry information * for the node. * * @param time * the frame time. * @param initiator * true if this node started the update process. */ public void updateGeometricState(float time, boolean initiator) { updateWorldData(time); if ((lockedMode & LOCKED_BOUNDS) == 0) { updateWorldBound(); if (initiator) { propagateBoundToRoot(); } } } /** * * <code>updateWorldData</code> updates the world transforms from the * parent down to the leaf. * * @param time * the frame time. */ public void updateWorldData(float time) { // update spatial state via controllers Object controller; for (int i = 0, gSize = geometricalControllers.size(); i < gSize; i++) { try { controller = geometricalControllers.get( i ); } catch ( IndexOutOfBoundsException e ) { // a controller was removed in Controller.update (note: this may skip one controller) break; } if ( controller != null ) { ( (Controller) controller ).update( time ); } } updateWorldVectors(); } public void updateWorldVectors() { if ((lockedMode & LOCKED_TRANSFORMS) == 0) { updateWorldScale(); updateWorldRotation(); updateWorldTranslation(); } } private void updateWorldTranslation() { if (parent != null) { worldTranslation = parent.localToWorld( localTranslation, worldTranslation ); } else { worldTranslation.set(localTranslation); } } /** * Convert a vector (in) from this spatials local coordinate space to world coordinate space. * @param in vector to read from * @param store where to write the result (null to create a new vector, may be same as in) * @return the result (store) */ public Vector3f localToWorld( final Vector3f in, final Vector3f store ) { return getWorldRotation().mult(in, store ).multLocal( getWorldScale()) .addLocal( getWorldTranslation()); } private void updateWorldRotation() { if (parent != null) { parent.getWorldRotation().mult(localRotation, worldRotation); } else { worldRotation.set(localRotation); } } private void updateWorldScale() { if (parent != null) { worldScale.set(parent.getWorldScale()).multLocal(localScale); } else { worldScale.set(localScale); } } /** * * <code>updateWorldBound</code> updates the bounding volume of the world. * Abstract, geometry transforms the bound while node merges the children's * bound. In most cases, users will want to call updateModelBound() and let * this function be called automatically during updateGeometricState(). * */ public abstract void updateWorldBound(); /** * Updates the render state values of this Spatial and and children it has. * Should be called whenever render states change. */ public void updateRenderState() { updateRenderState(null); } /** * Called internally. Updates the render states of this Spatial. The stack * contains parent render states. * * @param parentStates * The list of parent renderstates. */ protected void updateRenderState(Stack[] parentStates) { boolean initiator = (parentStates == null); // first we need to get all the states from parent to us. if (initiator) { // grab all states from root to here. parentStates = new Stack[RenderState.RS_MAX_STATE]; for (int x = 0; x < parentStates.length; x++) parentStates[x] = new Stack(); propagateStatesFromRoot(parentStates); } else { for (int x = 0; x < RenderState.RS_MAX_STATE; x++) { if (getRenderState(x) != null) parentStates[x].push(getRenderState(x)); } } applyRenderState(parentStates); // restore previous if we are not the initiator if (!initiator) { for (int x = 0; x < RenderState.RS_MAX_STATE; x++) if (getRenderState(x) != null) parentStates[x].pop(); } } /** * Called during updateRenderState(Stack[]), this function determines how * the render states are actually applied to the spatial and any children it * may have. By default, this function does nothing. * * @param states * An array of stacks for each state. */ protected void applyRenderState(Stack[] states) { } /** * Called during updateRenderState(Stack[]), this function goes up the scene * graph tree until the parent is null and pushes RenderStates onto the * states Stack array. * * @param states * The Stack[] to push states onto. */ protected void propagateStatesFromRoot(Stack[] states) { // traverse to root to allow downward state propagation if (parent != null) parent.propagateStatesFromRoot(states); // push states onto current render state stack for (int x = 0; x < RenderState.RS_MAX_STATE; x++) if (getRenderState(x) != null) states[x].push(getRenderState(x)); } /** * * <code>propagateBoundToRoot</code> passes the new world bound up the * tree to the root. * */ public void propagateBoundToRoot() { if (parent != null) { parent.updateWorldBound(); parent.propagateBoundToRoot(); } } /** * <code>getParent</code> retrieve's this node's parent. If the parent is * null this is the root node. * * @return the parent of this node. */ public Node getParent() { return parent; } /** * Called by {@link Node#attachChild(Spatial)} and {@link Node#detachChild(Spatial)} - don't call directly. * <code>setParent</code> sets the parent of this node. * * @param parent * the parent of this node. */ protected void setParent(Node parent) { this.parent = parent; } /** * <code>removeFromParent</code> removes this Spatial from it's parent. * * @return true if it has a parent and performed the remove. */ public boolean removeFromParent() { if (parent != null) { parent.detachChild(this); return true; } return false; } /** * <code>getLocalRotation</code> retrieves the local rotation of this * node. * * @return the local rotation of this node. */ public Quaternion getLocalRotation() { return localRotation; } /** * <code>setLocalRotation</code> sets the local rotation of this node. * * @param rotation * the new local rotation. */ public void setLocalRotation(Matrix3f rotation) { if (localRotation == null) localRotation = new Quaternion(); localRotation.fromRotationMatrix(rotation); this.worldRotation.set(this.localRotation); } /** * * <code>setLocalRotation</code> sets the local rotation of this node, * using a quaterion to build the matrix. * * @param quaternion * the quaternion that defines the matrix. */ public void setLocalRotation(Quaternion quaternion) { localRotation = quaternion; this.worldRotation.set(this.localRotation); } /** * <code>getLocalScale</code> retrieves the local scale of this node. * * @return the local scale of this node. */ public Vector3f getLocalScale() { return localScale; } /** * <code>setLocalScale</code> sets the local scale of this node. * * @param localScale * the new local scale, applied to x, y and z */ public void setLocalScale(float localScale) { this.localScale.x = localScale; this.localScale.y = localScale; this.localScale.z = localScale; this.worldScale.set(this.localScale); } /** * <code>setLocalScale</code> sets the local scale of this node. * * @param localScale * the new local scale. */ public void setLocalScale(Vector3f localScale) { this.localScale = localScale; this.worldScale.set(this.localScale); } /** * <code>getLocalTranslation</code> retrieves the local translation of * this node. * * @return the local translation of this node. */ public Vector3f getLocalTranslation() { return localTranslation; } /** * <code>setLocalTranslation</code> sets the local translation of this * node. * * @param localTranslation * the local translation of this node. */ public void setLocalTranslation(Vector3f localTranslation) { this.localTranslation = localTranslation; this.worldTranslation.set(this.localTranslation); } /** * * <code>setRenderState</code> sets a render state for this node. Note, * there can only be one render state per type per node. That is, there can * only be a single AlphaState a single TextureState, etc. If there is * already a render state for a type set the old render state will be * returned. Otherwise, null is returned. * * @param rs * the render state to add. * @return the old render state. */ public RenderState setRenderState(RenderState rs) { if ( renderStateList == null ) { renderStateList = new RenderState[RenderState.RS_MAX_STATE]; } RenderState oldState = renderStateList[rs.getType()]; renderStateList[rs.getType()] = rs; return oldState; } /** * Returns the requested RenderState that this Spatial currently has set or * null if none is set. * * @param type * the renderstate type to retrieve * @return a renderstate at the given position or null */ public RenderState getRenderState( int type ) { return renderStateList != null ? renderStateList[type] : null; } /** * Clears a given render state index by setting it to null. * * @param renderStateType * The index of a RenderState to clear * @see com.jme.scene.state.RenderState#getType() */ public void clearRenderState(int renderStateType) { if ( renderStateList != null ) { renderStateList[renderStateType] = null; } } /** * Enforce a particular state. In other words, the given state will override * any state of the same type set on a scene object. Remember to clear the * state when done enforcing. Very useful for multipass techniques where * multiple sets of states need to be applied to a scenegraph drawn multiple * times. * * @param state * state to enforce */ public static void enforceState(RenderState state) { Spatial.enforcedStateList[state.getType()] = state; } /** * Clears an enforced render state index by setting it to null. This allows * object specific states to be used. * * @param renderStateType * The type of RenderState to clear enforcement on. */ public static void clearEnforcedState(int renderStateType) { if ( enforcedStateList != null ) { enforcedStateList[renderStateType] = null; } } /** * sets all enforced states to null. * * @see com.jme.scene.Spatial#clearEnforcedState(int) */ public static void clearEnforcedStates() { for (int i = 0; i < enforcedStateList.length; i++) enforcedStateList[i] = null; } /** * <code>setRenderQueueMode</code> determines at what phase of the * rendering proces this Spatial will rendered. There are 4 different * phases: * * QUEUE_SKIP - The spatial will be drawn as soon as possible, before the * other phases of rendering. * * QUEUE_OPAQUE - The renderer will try to find the optimal order for * rendering all objects using this mode. You should use this mode for most * normal objects, except transparant ones, as it could give a nice * performance boost to your application. * * QUEUE_TRANSPARENT - This is the mode you should use for object with * transparancy in them. It will ensure the objects furthest away are * rendered first. That ensures when another transparent object is drawn on * top of previously drawn objects, you can see those (and the object drawn * using SKIP and OPAQUE) through the tranparant parts of the newly drawn * object. * * QUEUE_ORTHO - This is a special mode, for drawing 2D object without * prespective (such as GUI or HUD parts) * * Lastly, there is a special mode, QUEUE_INHERIT, that will ensure that * this spatial uses the same mode as the parent Node does. * * @param renderQueueMode * The mode to use for this Spatial. */ public void setRenderQueueMode(int renderQueueMode) { this.renderQueueMode = renderQueueMode; } public int getRenderQueueMode() { if (renderQueueMode != Renderer.QUEUE_INHERIT) return renderQueueMode; else if (parent != null) return parent.getRenderQueueMode(); else return Renderer.QUEUE_SKIP; } public void setZOrder(int zOrder) { this.zOrder = zOrder; } public int getZOrder() { return zOrder; } /** * Sets how lights from parents should be combined for this spatial. * * @param lightCombineMode * The light combine mode for this spatial * @see com.jme.scene.state.LightState#COMBINE_CLOSEST * @see com.jme.scene.state.LightState#COMBINE_FIRST * @see com.jme.scene.state.LightState#COMBINE_RECENT_ENABLED * @see com.jme.scene.state.LightState#INHERIT * @see com.jme.scene.state.LightState#OFF * @see com.jme.scene.state.LightState#REPLACE */ public void setLightCombineMode(int lightCombineMode) { this.lightCombineMode = lightCombineMode; } /** * Returns this spatial's light combine mode. If the mode is set to inherit, * then the spatial gets its combine mode from its parent. * * @return The spatial's light current combine mode. */ public int getLightCombineMode() { if (lightCombineMode != LightState.INHERIT) return lightCombineMode; else if (parent != null) return parent.getLightCombineMode(); else return LightState.COMBINE_FIRST; } /** * Sets how textures from parents should be combined for this Spatial. * * @param textureCombineMode * The new texture combine mode for this spatial. * @see com.jme.scene.state.TextureState#COMBINE_CLOSEST * @see com.jme.scene.state.TextureState#COMBINE_FIRST * @see com.jme.scene.state.TextureState#COMBINE_RECENT_ENABLED * @see com.jme.scene.state.TextureState#INHERIT * @see com.jme.scene.state.TextureState#OFF * @see com.jme.scene.state.TextureState#REPLACE */ public void setTextureCombineMode(int textureCombineMode) { this.textureCombineMode = textureCombineMode; } /** * Returns this spatial's texture combine mode. If the mode is set to * inherit, then the spatial gets its combine mode from its parent. * * @return The spatial's texture current combine mode. */ public int getTextureCombineMode() { if (textureCombineMode != TextureState.INHERIT) return textureCombineMode; else if (parent != null) return parent.getTextureCombineMode(); else return TextureState.COMBINE_CLOSEST; } /** * Returns this spatial's last frustum intersection result. This int is set * when a check is made to determine if the bounds of the object fall inside * a camera's frustum. If a parent is found to fall outside the frustum, the * value for this spatial will not be updated. * * Possible values include: Camera.OUTSIDE_FRUSTUM, * Camera.INTERSECTS_FRUSTUM, and Camera.INSIDE_FRUSTUM * * @return The spatial's last frustum intersection result. */ public int getLastFrustumIntersection() { return frustrumIntersects; } /** * Overrides the last intersection result. This is useful for * operations that want to start rendering at the middle of a * scene tree and don't want the parent of that node to * influence culling. (See texture renderer code for example.) * * Possible values include: Camera.OUTSIDE_FRUSTUM, * Camera.INTERSECTS_FRUSTUM, and Camera.INSIDE_FRUSTUM * @param intersects the new value, one of those given above. */ public void setLastFrustumIntersection(int intersects) { frustrumIntersects = intersects; } /** * sets all current states to null, and therefore forces the use of the * default states. * */ public static void clearCurrentStates() { for (int i = 0; i < currentStates.length; i++) currentStates[i] = null; } /** * clears the specified state. The state is referenced by it's int value, * and therefore should be called via RenderState's constant list. For * example, RenderState.RS_ALPHA. * * @param state * the state to clear. */ public static void clearCurrentState(int state) { currentStates[state] = null; } public static RenderState getCurrentState(int state) { return currentStates[state]; } /** * All non null default states are applied to the renderer. */ public static void applyDefaultStates() { for (int i = 0; i < defaultStateList.length; i++) { if (defaultStateList[i] != null) defaultStateList[i].apply(); } } /** * * <code>calculateCollisions</code> calls findCollisions to populate the * CollisionResults object then processes the collision results. * * @param scene * the scene to test against. * @param results * the results object. */ public void calculateCollisions(Spatial scene, CollisionResults results) { findCollisions(scene, results); results.processCollisions(); } /** * checks this spatial against a second spatial, any collisions are stored * in the results object. * * @param scene * the scene to test against. * @param results * the results of the collisions. */ public abstract void findCollisions(Spatial scene, CollisionResults results); public abstract boolean hasCollision(Spatial scene, boolean checkTriangles); public void calculatePick(Ray ray, PickResults results) { findPick(ray, results); results.processPick(); } public abstract void findPick(Ray toTest, PickResults results); /** * This method updates the exact bounding tree of any this Spatial. If this * spatial has children, the function is called recursivly on its children. * Spatial objects, such as text, which don't make sense to have an exact * bounds are ignored. */ public void updateCollisionTree() { } /** * Returns the Spatial's name followed by the class of the spatial <br> * Example: "MyNode (com.jme.scene.Spatial) * * @return Spatial's name followed by the class of the Spatial */ public String toString() { return name + " (" + this.getClass().getName() + ')'; } public Spatial putClone(Spatial store, CloneCreator properties) { if (store == null) return null; store.renderQueueMode = this.renderQueueMode; store.setLocalTranslation(new Vector3f(getLocalTranslation())); store.setLocalRotation(new Quaternion(getLocalRotation())); store.setLocalScale(new Vector3f(getLocalScale())); if ( renderStateList != null ) { if (store.renderStateList == null) store.renderStateList = new RenderState[RenderState.RS_MAX_STATE]; System.arraycopy( renderStateList, 0, store.renderStateList, 0, renderStateList.length ); } Iterator I = geometricalControllers.iterator(); while (I.hasNext()) { Controller c = (Controller) I.next(); Controller toAdd = c.putClone(null, properties); if (toAdd != null) store.addController(toAdd); } properties.originalToCopy.put(this, store); return store; } }
package com.cobalt.cdpipeline.cdresult; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; /** * CDResult contains all the information needed for one single row * of the table display for CDPipeline Plugin Project. */ public class CDResult { private String projectName, planName; private Date lastDeploymentTime, lastUpdate; private int numChanges; private Set<Contributor> contributors; private Build currentBuild; private List<PipelineStage> pipelineStages; /** * Construct a CDResult Object. * Access modifier left out intentionally for package protection. * * @param projectName * @param planName */ CDResult(String projectName, String planName) { this.projectName = projectName; this.planName = planName; contributors = new HashSet<Contributor>(); pipelineStages = new ArrayList<PipelineStage>(); } /** * Set lastDeploymentTime to the given date. * Access modifier left out intentionally for package protection. * * @param lastDeployment */ void setLastDeploymentTime(Date lastDeployment) { this.lastDeploymentTime = lastDeployment; } /** * Set lastUpdate time to the given date. * Access modifier left out intentionally for package protection. * * @param lastUpdate */ void setLastUpdateTime(Date lastUpdate) { this.lastUpdate = lastUpdate; } /** * Set number of changes to the given number. * Access modifier left out intentionally for package protection. * * @param numChanges */ void setNumChanges(int numChanges) { this.numChanges = numChanges; } /** * Add given contributor to contributors set. * Access modifier left out intentionally for package protection. * * @param contributor */ void addContributor(Contributor contributor) { contributors.add(contributor); } /** * Add given PipelineStage to the pipelineStages list. * Access modifier left out intentionally for package protection. * * @param stage */ void addPipelineStageToList(PipelineStage stage) { pipelineStages.add(stage); } /** * Set current build information to the given Build * * @param current */ void setCurrentBuild(Build current){ this.currentBuild = current; } /** * Get the project name associated with this result. * * @return project name */ public String getProjectName() { return projectName; } /** * Get the plan name associated with this result. * * @return plan name */ public String getPlanName() { return planName; } /** * Return last deployment date and time. * Return null if there's no deployment yet. * * @return date/time of last deployment */ public Date getLastDeploymentTime(){ if(lastDeploymentTime == null){ return null; } return new Date(lastDeploymentTime.getTime()); } /** * Return days since last deployment until given date * Return -1 if given date is before last deployment date or * no last deployment is found. * * @param currentDate The date to compare to * @return the number of days from last deployment date to given date */ public int getDaysSinceDeploymentFromCurrent(){ Date currentDate = new Date(); if(this.lastDeploymentTime == null || this.lastDeploymentTime.compareTo(currentDate) > 0){ return -1; } long deploymentTime = this.lastDeploymentTime.getTime(); long currentTime = currentDate.getTime(); return (int) ((currentTime - deploymentTime) / (1000 * 60 * 60 * 24)); } /** * Return last update (the most current build) date and time * * @return date/time of last update */ public Date getLastUpdateTime(){ if(lastUpdate == null){ return null; }else{ return new Date(lastUpdate.getTime()); } } /** * Return changes(commits) since last deployment * * @return number of changes since last deployment */ public int getNumChanges(){ return this.numChanges; } /** * Return current build information. * Return null if there's no build yet. * * @return a Build object that contains information about the most * current build. */ public Build getCurrentBuild(){ return this.currentBuild; } /** * Return all contributors since last deployment. * * @return a Set of Contributor */ public Set<Contributor> getContributors(){ return Collections.unmodifiableSet(contributors); } /** * Return all pipeline stages of the current build. * * @return a List of PipelineStates with the list starting with the first stage. */ public List<PipelineStage> getPipelineStages(){ return Collections.unmodifiableList(pipelineStages); } }
package com.rcv; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileOutputStream; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; public class ResultsWriter { // number of round needed to declare a winner private int numRounds; // map of round to map of candidateID to tally private Map<Integer, Map<String, Integer>> roundTallies; // map of candidate to round in which they were eliminated private Map<String, Integer> candidatesToRoundEliminated; // the winning candidateID private String winner; // configuration file in use for this election private ElectionConfig config; // function: setNumRound // purpose: setter for total number of rounds to declare a winner // param: numRounds total number of rounds to declare a winner public ResultsWriter setNumRounds(int numRounds) { this.numRounds = numRounds; return this; } // function: setRoundTallies // purpose: setter for round to tally object // param: roundTallies map of round to map of candidateID to their tally for that round public ResultsWriter setRoundTallies(Map<Integer, Map<String, Integer>> roundTallies) { this.roundTallies = roundTallies; return this; } // function: setCandidatesToRoundEliminated // purpose: setter for map of candidateID to round in which they were eliminated // param: candidatesToRoundEliminated map of candidateID to round in which they were eliminated public ResultsWriter setCandidatesToRoundEliminated( Map<String, Integer> candidatesToRoundEliminated ) { this.candidatesToRoundEliminated = candidatesToRoundEliminated; return this; } // function: setElection config // purpose: setter for ElectionConfig object // param: config the ElectionConfig object to use when writing results public ResultsWriter setElectionConfig(ElectionConfig config) { this.config = config; return this; } // function: setWinner // purpose: setter for the winning candidate ID // param: winner the winning candidate ID public ResultsWriter setWinner(String winner) { this.winner = winner; return this; } // function: generateSummarySpreadsheet // purpose: creates the summary spreadsheet xls file public void generateSummarySpreadsheet() { // some pre-processing on the tabulation data: // roundToCandidatesEliminated map is the inverse of candidatesToRoundEliminated map // so we can lookup who got eliminated for each round Map<Integer, List<String>> roundToCandidatesEliminated = new HashMap<>(); // candidate is used for indexing over all candidates in candidatesToRoundEliminated for (String candidate : candidatesToRoundEliminated.keySet()) { // round is the current candidate round of elimination int round = candidatesToRoundEliminated.get(candidate); // create a new entry for this round if needed if (roundToCandidatesEliminated.get(round) == null) { roundToCandidatesEliminated.put(round, new LinkedList<>()); } roundToCandidatesEliminated.get(round).add(candidate); } // Get all candidates sorted by their first round tally. This determines the display order. // container for firstRoundTally Map<String, Integer> firstRoundTally = roundTallies.get(1); // candidates sorted by first round tally List<String> sortedCandidates = sortTally(firstRoundTally); // totalActiveVotesPerRound is a map of total votes cast in each round // this will be used to calculate the percentage of total votes each candidate achieves Map<Integer, Integer> totalActiveVotesPerRound = new HashMap<>(); // round is index for iterating all rounds for (int round = 1; round <= numRounds; round++) { // tally is the tally for the current round Map<String, Integer> tally = roundTallies.get(round); // total will contain total votes for this candidate in this round int total = 0; for (int votes : tally.values()) { total += votes; } totalActiveVotesPerRound.put(round, total); } // create the output workbook XSSFWorkbook workbook = new XSSFWorkbook(); // create the output worksheet XSSFSheet worksheet = workbook.createSheet(config.jurisdiction() + " " + config.office()); // rowCounter contains the next empty row after all header rows have been created // this is where we start adding the round-by-round reports int rowCounter = addHeaderRows(worksheet, totalActiveVotesPerRound); // each round has three pieces of data for each candidate row: // change in votes from previous round // total votes in current round // percentage of total active votes int COLUMNS_PER_ROUND = 3; // column indexes are computed for all cells as we create the output xlsx spreadsheet int columnIndex; // Round headers: // headerRow1 is the row for round headers org.apache.poi.ss.usermodel.Row headerRow1 = worksheet.createRow(rowCounter++); // the round header title cell will be used to create all the round headers Cell roundTitleHeaderCell = headerRow1.createCell(0); roundTitleHeaderCell.setCellValue("Round Title"); // round indexes from 1 to rounds+1 to include a "final results" column for (int round = 1; round <= numRounds+1; round++) { // columnIndex = round - 1 (rounds are 1-based cells are 0-based) // columnIndex is offset by 1 to account for row headers columnIndex = ((round-1)*COLUMNS_PER_ROUND)+1; // label string will have the actual text which goes in the cell String label; if(round == 1) { label = "Initial Count"; } else if (round == numRounds+1) { label = "Final Results"; } else { label = String.format("Round %d", round); } for(int i = 0; i < COLUMNS_PER_ROUND; i++) { Cell roundLabelCell = headerRow1.createCell(columnIndex++); roundLabelCell.setCellValue(label); } } // Winner: show them in final round and in final results // Action row and header org.apache.poi.ss.usermodel.Row actionRow = worksheet.createRow(rowCounter++); Cell actionLabelCell = actionRow.createCell(0); actionLabelCell.setCellValue("Action in this round"); // Candidate eliminations for each round org.apache.poi.ss.usermodel.Row eliminationsRow = worksheet.createRow(rowCounter++); Cell eliminationsRowHeader = eliminationsRow.createCell(0); eliminationsRowHeader.setCellValue("Candidates defeated"); for (int round = 1; round < numRounds; round++) { List<String> eliminated = roundToCandidatesEliminated.get(round); // note we shift the eliminated candidate(s) display and action into the subsequent column if(eliminated.size() > 0) { String eliminatedCellText = String.join("; ", eliminated); columnIndex = ((round - 1 + 1) * COLUMNS_PER_ROUND) + 1; Cell cell = eliminationsRow.createCell(columnIndex); cell.setCellValue(eliminatedCellText); Cell actionCell = actionRow.createCell(columnIndex); actionCell.setCellValue("Elimination"); } } // Winner -- note display is shifted to subsequent round for display org.apache.poi.ss.usermodel.Row electedRow = worksheet.createRow(rowCounter++); Cell electedCell = electedRow.createCell(0); electedCell.setCellValue("Winners"); columnIndex = (numRounds*COLUMNS_PER_ROUND)+1; electedCell = electedRow.createCell(columnIndex); electedCell.setCellValue(winner); // Winner action Cell actionCell = actionRow.createCell(((numRounds*COLUMNS_PER_ROUND)+1)); actionCell.setCellValue("Winner"); // Create a row for the number of votes redistributed per round. We'll fill it in after we // tabulate all the candidates' data. org.apache.poi.ss.usermodel.Row votesRedistributedRow = worksheet.createRow(rowCounter++); Cell votesRedistributedHeaderCell = votesRedistributedRow.createCell(0); votesRedistributedHeaderCell.setCellValue("Votes redistributed"); int[] votesRedistributedEachRound = new int[numRounds+1]; // Headers for total, change, percentage for each round org.apache.poi.ss.usermodel.Row headerRow2 = worksheet.createRow(rowCounter++); Cell candidateNameCell = headerRow2.createCell(0); candidateNameCell.setCellValue("Candidate Name"); for (int round = 1; round <= numRounds+1; round++) { columnIndex = ((round-1)*COLUMNS_PER_ROUND)+1; String roundDeltaText = "Vote change"; Cell roundDeltaCell = headerRow2.createCell(columnIndex); roundDeltaCell.setCellValue(roundDeltaText); columnIndex++; Cell roundTotalCell = headerRow2.createCell(columnIndex++); String roundTotalText = (round == 1) ? "First preferences" : "Result of round"; roundTotalCell.setCellValue(roundTotalText); String roundPercentageText = "% of vote"; Cell roundPercentageCell = headerRow2.createCell(columnIndex); roundPercentageCell.setCellValue(roundPercentageText); } org.apache.poi.ss.usermodel.Row specialCasesHeaderRow = null; // Candidate votes [total, delta, percentage] // percentage of total. for (String candidate : sortedCandidates) { if (candidate.equals(config.undeclaredWriteInLabel())) { specialCasesHeaderRow = worksheet.createRow(rowCounter++); populateSpecialCasesHeaderRow(specialCasesHeaderRow); } // show each candidate row with their totals for each round org.apache.poi.ss.usermodel.Row candidateRow = worksheet.createRow(rowCounter++); Cell rowHeaderCell = candidateRow.createCell(0); String candidateDisplayName = this.config.getNameForCandidateID(candidate); rowHeaderCell.setCellValue(candidateDisplayName); for (int displayRound = 1; displayRound <= numRounds+1; displayRound++) { boolean isFinalResults = displayRound == numRounds + 1; // For the Final Results "round", we're mostly copying the data from the final round. int round = isFinalResults ? numRounds : displayRound; // not all candidates may have a tally in every round Integer total = roundTallies.get(round).get(candidate); if (total == null) { total = 0; } // get previous tally to calculate delta Integer prevTotal = 0; if (round > 1) { prevTotal = roundTallies.get(round - 1).get(candidate); if (prevTotal == null) { prevTotal = 0; } } int delta = isFinalResults ? 0 : total - prevTotal; // sum total votes redistributed if (delta > 0) { votesRedistributedEachRound[round] += delta; } // percentage Integer totalActiveVotes = totalActiveVotesPerRound.get(round); float percentage = ((float)total / (float)totalActiveVotes) * 100f; // create cells for spreadsheet columnIndex = ((displayRound-1)*COLUMNS_PER_ROUND)+1; Cell deltaVotesCell = candidateRow.createCell(columnIndex++); deltaVotesCell.setCellValue(delta); Cell totalVotesCell = candidateRow.createCell(columnIndex++); totalVotesCell.setCellValue(total); Cell percentageCell = candidateRow.createCell(columnIndex); String percentageText = String.format("%.2f%%", percentage); percentageCell.setCellValue(percentageText); } } // Bottom rows: if (specialCasesHeaderRow == null) { specialCasesHeaderRow = worksheet.createRow(rowCounter++); populateSpecialCasesHeaderRow(specialCasesHeaderRow); } // exhausted ballots for each round org.apache.poi.ss.usermodel.Row inactiveBallotRow = worksheet.createRow(rowCounter++); Cell exhaustedRowHeaderCell = inactiveBallotRow.createCell(0); exhaustedRowHeaderCell.setCellValue("Inactive ballots"); int totalActiveVotesFirstRound = totalActiveVotesPerRound.get(1); for (int displayRound = 1; displayRound <= numRounds+1; displayRound++) { boolean isFinalResults = displayRound == numRounds+1; int round = isFinalResults ? numRounds : displayRound; int thisRoundExhausted = 0; int deltaExhausted = 0; // Exhausted count is the difference between the total votes in round 1 and the total votes in // the current round. if (round > 1) { thisRoundExhausted = totalActiveVotesFirstRound - totalActiveVotesPerRound.get(round); int prevRoundExhausted = totalActiveVotesFirstRound - totalActiveVotesPerRound.get(round - 1); deltaExhausted = isFinalResults ? 0 : thisRoundExhausted - prevRoundExhausted; // add exhausted votes to the votes redistributed totals votesRedistributedEachRound[round] += deltaExhausted; } // Exhausted votes as percentage of ALL votes (note: this differs from the candidate vote // percentage, which are the percentage of ACTIVE votes for the given round. float percentage = ((float)thisRoundExhausted / (float)totalActiveVotesFirstRound) * 100f; // xls output columnIndex = ((displayRound-1)*COLUMNS_PER_ROUND)+1; Cell deltaVotesCell = inactiveBallotRow.createCell(columnIndex++); deltaVotesCell.setCellValue(deltaExhausted); Cell totalVotesCell = inactiveBallotRow.createCell(columnIndex++); totalVotesCell.setCellValue(thisRoundExhausted); String percentageText = String.format("%.2f%%", percentage); Cell percentageCell = inactiveBallotRow.createCell(columnIndex); percentageCell.setCellValue(percentageText); } // Total votes in this round org.apache.poi.ss.usermodel.Row totalVotesRow = worksheet.createRow(rowCounter++); Cell totalVotesHeader = totalVotesRow.createCell(0); totalVotesHeader.setCellValue("Balance check"); for (int displayRound = 1; displayRound <= numRounds+1; displayRound++) { columnIndex = ((displayRound-1)*COLUMNS_PER_ROUND)+2; Cell totalVotesCell = totalVotesRow.createCell(columnIndex); totalVotesCell.setCellValue(totalActiveVotesFirstRound); } // Total active votes in this round org.apache.poi.ss.usermodel.Row totalActiveVotesRow = worksheet.createRow(rowCounter++); Cell totalActiveVotesHeader = totalActiveVotesRow.createCell(0); totalActiveVotesHeader.setCellValue("Active votes"); for (int displayRound = 1; displayRound <= numRounds+1; displayRound++) { boolean isFinalResults = displayRound == numRounds+1; int total = totalActiveVotesPerRound.get(isFinalResults ? displayRound - 1 : displayRound); // xls output columnIndex = ((displayRound-1)*COLUMNS_PER_ROUND)+2; Cell totalVotesCell = totalActiveVotesRow.createCell(columnIndex); totalVotesCell.setCellValue(total); } // total votes redistributed // this calculation happens last because it depends on the inactive vote totals for (int round = 2; round <= numRounds+1; round++) { columnIndex = ((round - 1) * COLUMNS_PER_ROUND) + 1; Cell votesRedistributedRowCell = votesRedistributedRow.createCell(columnIndex); if (round <= numRounds) { int votesRedistributed = votesRedistributedEachRound[round]; votesRedistributedRowCell.setCellValue(votesRedistributed); } else { votesRedistributedRowCell.setCellValue("NA"); } } // write xls to disk try { FileOutputStream outputStream = new FileOutputStream(config.visualizerOutput()); workbook.write(outputStream); outputStream.close(); } catch (IOException e) { e.printStackTrace(); Logger.log("failed to write " + config.visualizerOutput() + " to disk!"); } } private void populateSpecialCasesHeaderRow(org.apache.poi.ss.usermodel.Row row) { Cell cell = row.createCell(0); cell.setCellValue("Special Cases Data"); } private int addHeaderRows(XSSFSheet worksheet, Map<Integer, Integer> totalActiveVotesPerRound) { int totalActiveVotesFirstRound = totalActiveVotesPerRound.get(1); DateFormat dateFormat = new SimpleDateFormat("M/d/yyyy"); String dateString = dateFormat.format(new Date()); Object[][] fields = { {"About this contest", null, false}, {"Date/time or version", "Updated " + dateString, false}, {"Contest information", null, false}, {"Enter information about the contest as it will be displayed", null, false}, {"Contest name", config.contestName(), false}, {"Jurisdiction name", config.jurisdiction(), false}, {"Office name", config.office(), false}, {"Election date", config.electionDate(), false}, {null, null, false}, {"Counting information", null, false}, {"Details of the tally to be used in the display screens", null, false}, {"Counting method", "Ranked-choice voting", false}, {"Formula for winning", "Half of total votes cast for office + 1", false}, {"Formula example", "n/a", false}, {"Threshold number", "50%", false}, {"Graph threshold label", "50% of votes required to win", false}, {null, null, false}, {"Contest summary data", null, false}, {"Tally detail", null, false}, {"Single/multi winner", "single-winner", false}, {"Number to be elected", 1, true}, {"Number of candidates", config.numCandidates(), true}, {"Number of votes cast", totalActiveVotesFirstRound, true}, {"Undervotes", 0, true}, {"Total # of rounds", totalActiveVotesPerRound.size(), true}, {null, null, false}, {"Tally Data Starts Here", null, false} }; int rowCounter = 0; for (Object[] rowFields : fields) { org.apache.poi.ss.usermodel.Row row = worksheet.createRow(rowCounter++); if (rowFields[0] != null) { row.createCell(0).setCellValue((String)rowFields[0]); } if (rowFields[1] != null) { if ((boolean)rowFields[2]) { row.createCell(1).setCellValue((int)rowFields[1]); } else { row.createCell(1).setCellValue((String)rowFields[1]); } } } return rowCounter; } // helper private List<String> sortTally(Map<String, Integer> tally) { List<Map.Entry<String, Integer>> entries = new LinkedList<>(tally.entrySet()); Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) { int ret; if (o1.getKey().equals(config.undeclaredWriteInLabel())) { ret = 1; } else if (o2.getKey().equals(config.undeclaredWriteInLabel())) { ret = -1; } else { ret = (o2.getValue()).compareTo(o1.getValue()); } return ret; } }); List<String> sortedCandidates = new LinkedList<String>(); for (Map.Entry<String, Integer> entry : entries) { sortedCandidates.add(entry.getKey()); } return sortedCandidates; } }
package com.commafeed.backend.opml; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import javax.inject.Inject; import javax.inject.Singleton; import lombok.RequiredArgsConstructor; import com.commafeed.backend.dao.FeedCategoryDAO; import com.commafeed.backend.dao.FeedSubscriptionDAO; import com.commafeed.backend.model.FeedCategory; import com.commafeed.backend.model.FeedSubscription; import com.commafeed.backend.model.User; import com.google.common.base.MoreObjects; import com.rometools.opml.feed.opml.Attribute; import com.rometools.opml.feed.opml.Opml; import com.rometools.opml.feed.opml.Outline; @RequiredArgsConstructor(onConstructor = @__({ @Inject })) @Singleton public class OPMLExporter { private final FeedCategoryDAO feedCategoryDAO; private final FeedSubscriptionDAO feedSubscriptionDAO; public Opml export(User user) { Opml opml = new Opml(); opml.setFeedType("opml_1.1"); opml.setTitle(String.format("%s subscriptions in CommaFeed", user.getName())); opml.setCreated(new Date()); List<FeedCategory> categories = feedCategoryDAO.findAll(user); Collections.sort(categories, (e1, e2) -> MoreObjects.firstNonNull(e1.getPosition(), 0) - MoreObjects.firstNonNull(e2.getPosition(), 0)); List<FeedSubscription> subscriptions = feedSubscriptionDAO.findAll(user); Collections.sort(subscriptions, (e1, e2) -> MoreObjects.firstNonNull(e1.getPosition(), 0) - MoreObjects.firstNonNull(e2.getPosition(), 0)); // export root categories for (FeedCategory cat : categories.stream().filter(c -> c.getParent() == null).collect(Collectors.toList())) { opml.getOutlines().add(buildCategoryOutline(cat, categories, subscriptions)); } // export root subscriptions for (FeedSubscription sub : subscriptions.stream().filter(s -> s.getCategory() == null).collect(Collectors.toList())) { opml.getOutlines().add(buildSubscriptionOutline(sub)); } return opml; } private Outline buildCategoryOutline(FeedCategory cat, List<FeedCategory> categories, List<FeedSubscription> subscriptions) { Outline outline = new Outline(); outline.setText(cat.getName()); outline.setTitle(cat.getName()); for (FeedCategory child : categories.stream().filter(c -> c.getParent() != null && c.getParent().getId().equals(cat.getId())) .collect(Collectors.toList())) { outline.getChildren().add(buildCategoryOutline(child, categories, subscriptions)); } for (FeedSubscription sub : subscriptions.stream() .filter(s -> s.getCategory() != null && s.getCategory().getId().equals(cat.getId())).collect(Collectors.toList())) { outline.getChildren().add(buildSubscriptionOutline(sub)); } return outline; } private Outline buildSubscriptionOutline(FeedSubscription sub) { Outline outline = new Outline(); outline.setText(sub.getTitle()); outline.setTitle(sub.getTitle()); outline.setType("rss"); outline.getAttributes().add(new Attribute("xmlUrl", sub.getFeed().getUrl())); if (sub.getFeed().getLink() != null) { outline.getAttributes().add(new Attribute("htmlUrl", sub.getFeed().getLink())); } return outline; } }
package com.rehab.world; import java.util.ArrayDeque; import com.rehab.animation.Drawable; import com.rehab.animation.Sprite; /** * <p> * Frame holds all shallow copies ({@link Frame.Renderable}) of game objects to be rendered. * </p> */ public class Frame { // Shallow copies of Drawables private ArrayDeque<Renderable> mRenderables = new ArrayDeque<Renderable>(FrameDepot.FRAME_CAPACITY); /** * Removes a Renderable in the Frame. * * @return the Renderable. * @see #push(Drawable) */ public Renderable poll() { Renderable obj = mRenderables.poll(); return obj; } /** * Adds a Drawable to the Frame. The Drawable itself is not referenced by the Frame but * a shallow copy is created in the form of a {@link Renderable}. * * @param drawable the Drawable to add. * @see #poll() */ public void push(Drawable drawable) { mRenderables.add(new Renderable(drawable)); } /** * Clears the Frame of any Renderables. */ public void clear() { mRenderables.clear(); } /** * Checks whether or not the Frame is empty of game objects. * * @return true if the Frame holds no game objects, false otherwise. */ public boolean isEmpty() { return mRenderables.isEmpty(); } /** * Gets all Renderables set in the Frame. These Renderables are meant to be drawn shortly * after this method is called and no more Renderables should be added to this Frame. * * @return the Iterable of Renderables. */ public Iterable<Renderable> renderables() { return mRenderables; } /** * <p> * Represents a shallow copy of a Drawable game object to be drawn on the screen. * Renderables are stored within a Frame to be drawn soon after. * </p> */ public static class Renderable { // Data for drawing private Sprite sprite; private boolean left; private float rotation; private double x, y; private int z; /** * Constructor to shallow copy a Drawable for the Sprite, x, y, and z * values and stores them for drawing. * * @param drawable the game object. */ public Renderable(Drawable drawable) { sprite = drawable.getSprite(); left = drawable.isFacingLeft(); rotation = drawable.getRotation(); x = drawable.getX(); y = drawable.getY(); z = drawable.getZ(); } /** * Gets the Sprite (image) of the game object. * * @return the Sprite to draw. */ public Sprite getSprite() { return sprite; } /** * Checks whether or not the Renderable's game object * is facing left. * * @return true if the object is facing left, false otherwise. */ public boolean isFacingLeft() { return left; } /** * Gets the rotation value in degrees. * * @return the angle offset. */ public float getRotation() { return rotation; } /** * Gets the x value of the game object. * * @return the x coordinate to draw at. */ public double getX() { return x; } /** * Gets the y value of the game object. * * @return the y coordinate to draw at. */ public double getY() { return y; } /** * Gets the z value (draw layer) of the game object. * * @return the layer to draw the object on. */ public int getZ() { return z; } } }
package com.opengamma.financial.batch.db; import static org.junit.Assert.assertEquals; import java.math.BigDecimal; import java.sql.Date; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.time.Instant; import org.junit.Before; import org.junit.Test; import org.springframework.orm.hibernate3.HibernateTemplate; import com.google.common.collect.Sets; import com.opengamma.engine.ComputationTargetType; import com.opengamma.engine.depgraph.DependencyGraph; import com.opengamma.engine.depgraph.DependencyNode; import com.opengamma.engine.function.EmptyFunctionParameters; import com.opengamma.engine.position.PositionImpl; import com.opengamma.engine.test.CalculationNodeUtils; import com.opengamma.engine.test.MockFunction; import com.opengamma.engine.test.TestCalculationNode; import com.opengamma.engine.test.TestDependencyGraphExecutor; import com.opengamma.engine.value.ComputedValue; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueSpecification; import com.opengamma.engine.view.ResultModelDefinition; import com.opengamma.engine.view.ResultOutputMode; import com.opengamma.engine.view.cache.ViewComputationCache; import com.opengamma.engine.view.calcnode.CalculationJob; import com.opengamma.engine.view.calcnode.CalculationJobItem; import com.opengamma.engine.view.calcnode.CalculationJobResult; import com.opengamma.engine.view.calcnode.CalculationJobResultItem; import com.opengamma.engine.view.calcnode.MissingInputException; import com.opengamma.id.Identifier; import com.opengamma.id.UniqueIdentifier; import com.opengamma.util.test.HibernateTest; import com.opengamma.util.time.DateUtil; public class BatchResultWriterTest extends HibernateTest { private RiskRun _riskRun; private ObservationDateTime _observationDateTime; private ObservationTime _observationTime; private CalculationConfiguration _calculationConfiguration; private OpenGammaVersion _openGammaVersion; private LiveDataSnapshot _liveDataSnapshot; private ComputeHost _computeHost; private ComputeNode _computeNode; private com.opengamma.engine.ComputationTarget _mockFunctionComputationTarget; private Object _mockFunctionOutput; private com.opengamma.financial.batch.db.ComputationTarget _dbComputationTarget; private Set<com.opengamma.financial.batch.db.ComputationTarget> _dbComputationTargets; private Set<RiskValueName> _valueNames; private MockFunction _mockFunction; private TestCalculationNode _calcNode; private CalculationJob _calcJob; private HibernateTemplate _hibernateTemplate; public BatchResultWriterTest(String databaseType, String databaseVersion) { super(databaseType, databaseVersion); } @Before public void setUp() throws Exception { super.setUp(); Instant now = Instant.nowSystemClock(); _hibernateTemplate = new HibernateTemplate(getSessionFactory()); _hibernateTemplate.setAllowCreate(false); getSessionFactory().getCurrentSession().beginTransaction(); _openGammaVersion = new OpenGammaVersion(); _openGammaVersion.setVersion("1.0"); _openGammaVersion.setHash("1a2c3d4f"); _hibernateTemplate.save(_openGammaVersion); _observationTime = new ObservationTime(); _observationTime.setLabel("LDN_CLOSE"); _hibernateTemplate.save(_observationTime); _observationDateTime = new ObservationDateTime(); _observationDateTime.setDate(new Date(now.toEpochMillisLong())); _observationDateTime.setObservationTime(_observationTime); _hibernateTemplate.save(_observationDateTime); _computeHost = new ComputeHost(); _computeHost.setHostName("test-host"); _hibernateTemplate.save(_computeHost); _computeNode = new ComputeNode(); _computeNode.setComputeHost(_computeHost); _computeNode.setConfigOid("1"); _computeNode.setConfigVersion(1); _computeNode.setNodeName("test-node"); _hibernateTemplate.save(_computeNode); _liveDataSnapshot = new LiveDataSnapshot(); _liveDataSnapshot.setComplete(true); _liveDataSnapshot.setSnapshotTime(_observationDateTime); _hibernateTemplate.save(_liveDataSnapshot); _riskRun = new RiskRun(); _riskRun.setOpenGammaVersion(_openGammaVersion); _riskRun.setMasterProcessHost(_computeHost); _riskRun.setRunReason("BatchResultWriterTest"); _riskRun.setRunTime(_observationDateTime); _riskRun.setValuationTime(DateUtil.toSqlTimestamp(now)); _riskRun.setViewOid("view-oid"); _riskRun.setViewVersion(1); _riskRun.setLiveDataSnapshot(_liveDataSnapshot); _riskRun.setCreateInstant(DateUtil.toSqlTimestamp(now)); _riskRun.setStartInstant(DateUtil.toSqlTimestamp(now)); _riskRun.setNumRestarts(0); _riskRun.setComplete(false); _hibernateTemplate.save(_riskRun); _calculationConfiguration = new CalculationConfiguration(); _calculationConfiguration.setName(CalculationNodeUtils.CALC_CONF_NAME); _calculationConfiguration.setRiskRun(_riskRun); _hibernateTemplate.save(_calculationConfiguration); _riskRun.addCalculationConfiguration(_calculationConfiguration); _valueNames = new HashSet<RiskValueName>(); RiskValueName valueName = new RiskValueName(); valueName.setName("OUTPUT"); _valueNames.add(valueName); valueName = new RiskValueName(); valueName.setName("OUTPUT1"); _valueNames.add(valueName); valueName = new RiskValueName(); valueName.setName("OUTPUT2"); _valueNames.add(valueName); _hibernateTemplate.saveOrUpdateAll(_valueNames); _mockFunctionComputationTarget = new com.opengamma.engine.ComputationTarget(ComputationTargetType.POSITION, new PositionImpl( UniqueIdentifier.of("Mock", "AAPL Stock UID"), new BigDecimal(500), new Identifier("Mock", "AAPL Stock ID"))); _mockFunctionOutput = new Double(4000.50); _mockFunction = CalculationNodeUtils.getMockFunction(_mockFunctionComputationTarget, _mockFunctionOutput); _dbComputationTargets = new HashSet<com.opengamma.financial.batch.db.ComputationTarget>(); _dbComputationTarget = new com.opengamma.financial.batch.db.ComputationTarget(); _dbComputationTarget.setComputationTargetType(_mockFunction.getTarget().getType()); _dbComputationTarget.setIdScheme(_mockFunction.getTarget().getUniqueIdentifier().getScheme()); _dbComputationTarget.setIdValue(_mockFunction.getTarget().getUniqueIdentifier().getValue()); _dbComputationTargets.add(_dbComputationTarget); _hibernateTemplate.saveOrUpdateAll(_dbComputationTargets); _calcNode = CalculationNodeUtils.getTestCalcNode(_mockFunction); _calcJob = CalculationNodeUtils.getCalculationJob(_mockFunction); getSessionFactory().getCurrentSession().getTransaction().commit(); } private BatchResultWriter getSuccessResultWriter() { CalculationJobResultItem item = new CalculationJobResultItem(_calcJob.getJobItems().get(0)); CalculationJobResult result = new CalculationJobResult( _calcJob.getSpecification(), 200, Collections.singletonList(item), "localhost"); return getResultWriter(result); } private BatchResultWriter getResultWriter(CalculationJobResult result) { Map<String, ViewComputationCache> cachesByCalculationConfiguration = new HashMap<String, ViewComputationCache>(); cachesByCalculationConfiguration.put(CalculationNodeUtils.CALC_CONF_NAME, getCache()); ResultModelDefinition resultModelDefinition = new ResultModelDefinition(); resultModelDefinition.setAggregatePositionOutputMode(ResultOutputMode.ALL); resultModelDefinition.setPositionOutputMode(ResultOutputMode.ALL); resultModelDefinition.setSecurityOutputMode(ResultOutputMode.NONE); resultModelDefinition.setPrimitiveOutputMode(ResultOutputMode.NONE); BatchResultWriter resultWriter = new BatchResultWriter( new TestDependencyGraphExecutor<CalculationJobResult>(result), resultModelDefinition, cachesByCalculationConfiguration); resultWriter.setJdbcUrl(getDbTool().getJdbcUrl()); resultWriter.setUsername(getDbTool().getUser()); resultWriter.setPassword(getDbTool().getPassword()); resultWriter.setTransactionManager(getTransactionManager()); resultWriter.setSessionFactory(getSessionFactory()); resultWriter.setRiskRun(_riskRun); resultWriter.setRiskValueNames(_valueNames); resultWriter.setComputationTargets(_dbComputationTargets); resultWriter.initialize(getDbTool()); return resultWriter; } private DependencyGraph getPositionDepGraph() { DependencyNode node = new DependencyNode(_mockFunction.getTarget()); node.setFunction(_mockFunction); node.addOutputValues(_mockFunction.getResultSpecs()); DependencyGraph graph = new DependencyGraph(CalculationNodeUtils.CALC_CONF_NAME); graph.addDependencyNode(node); return graph; } private DependencyGraph getPrimitiveDepGraph() { com.opengamma.engine.ComputationTarget primitiveTarget = new com.opengamma.engine.ComputationTarget(ComputationTargetType.PRIMITIVE, new String("foo")); MockFunction function = new MockFunction(primitiveTarget); DependencyNode node = new DependencyNode(primitiveTarget); node.setFunction(function); node.addOutputValues(_mockFunction.getResultSpecs()); DependencyGraph graph = new DependencyGraph(CalculationNodeUtils.CALC_CONF_NAME); graph.addDependencyNode(node); return graph; } private void setIsRestart(BatchResultWriter resultWriter) { _riskRun.setNumRestarts(1); resultWriter.setIsRestart(true); } @Test public void notARestart() { // should execute BatchResultWriter resultWriter = getSuccessResultWriter(); DependencyGraph originalGraph = getPositionDepGraph(); DependencyGraph graphToExecute = resultWriter.getGraphToExecute(originalGraph); assertEquals(originalGraph.getSize(), graphToExecute.getSize()); } @Test public void restartButNoStatusEntryInDb() { // should re-execute BatchResultWriter resultWriter = getSuccessResultWriter(); setIsRestart(resultWriter); DependencyGraph originalGraph = getPositionDepGraph(); DependencyGraph graphToExecute = resultWriter.getGraphToExecute(originalGraph); assertEquals(originalGraph.getSize(), graphToExecute.getSize()); } @Test public void restartSuccessButOutputsNotInCache() { // should re-execute, but not write results into DB. BatchResultWriter resultWriter = getSuccessResultWriter(); setIsRestart(resultWriter); resultWriter.openSession(); resultWriter.upsertStatusEntries( _calcJob.getSpecification(), StatusEntry.Status.SUCCESS, Sets.newHashSet(_dbComputationTarget.toSpec())); resultWriter.closeSession(); DependencyGraph originalGraph = getPositionDepGraph(); DependencyGraph graphToExecute = resultWriter.getGraphToExecute(originalGraph); assertEquals(originalGraph.getSize(), graphToExecute.getSize()); } @Test public void restartSuccessOutputInCache() { // should not re-execute putOutputToCache(); BatchResultWriter resultWriter = getSuccessResultWriter(); setIsRestart(resultWriter); resultWriter.openSession(); resultWriter.upsertStatusEntries( _calcJob.getSpecification(), StatusEntry.Status.SUCCESS, Sets.newHashSet(_dbComputationTarget.toSpec())); resultWriter.closeSession(); DependencyGraph originalGraph = getPositionDepGraph(); DependencyGraph graphToExecute = resultWriter.getGraphToExecute(originalGraph); assertEquals(0, graphToExecute.getSize()); } @Test public void restartFailed() { // should re-execute BatchResultWriter resultWriter = getSuccessResultWriter(); setIsRestart(resultWriter); resultWriter.openSession(); resultWriter.upsertStatusEntries( _calcJob.getSpecification(), StatusEntry.Status.FAILURE, Sets.newHashSet(_dbComputationTarget.toSpec())); resultWriter.closeSession(); DependencyGraph originalGraph = getPositionDepGraph(); DependencyGraph graphToExecute = resultWriter.getGraphToExecute(originalGraph); assertEquals(originalGraph.getSize(), graphToExecute.getSize()); } @Test public void restartRunning() { // should re-execute (assumption being that the previous batch attempt // was hard-killed while it was running and is no longer really running) BatchResultWriter resultWriter = getSuccessResultWriter(); setIsRestart(resultWriter); resultWriter.openSession(); resultWriter.upsertStatusEntries( _calcJob.getSpecification(), StatusEntry.Status.RUNNING, Sets.newHashSet(_dbComputationTarget.toSpec())); resultWriter.closeSession(); DependencyGraph originalGraph = getPositionDepGraph(); DependencyGraph graphToExecute = resultWriter.getGraphToExecute(originalGraph); assertEquals(originalGraph.getSize(), graphToExecute.getSize()); } @Test public void restartNotRunning() { // should re-execute BatchResultWriter resultWriter = getSuccessResultWriter(); setIsRestart(resultWriter); resultWriter.openSession(); resultWriter.upsertStatusEntries( _calcJob.getSpecification(), StatusEntry.Status.NOT_RUNNING, Sets.newHashSet(_dbComputationTarget.toSpec())); resultWriter.closeSession(); DependencyGraph originalGraph = getPositionDepGraph(); DependencyGraph graphToExecute = resultWriter.getGraphToExecute(originalGraph); assertEquals(originalGraph.getSize(), graphToExecute.getSize()); } @Test public void restartPrimitiveSuccess() { // should re-execute BatchResultWriter resultWriter = getSuccessResultWriter(); setIsRestart(resultWriter); DependencyGraph originalGraph = getPrimitiveDepGraph(); DependencyGraph graphToExecute = resultWriter.getGraphToExecute(originalGraph); assertEquals(originalGraph.getSize(), graphToExecute.getSize()); } @Test public void restartPrimitiveSuccessOutputsInCache() { // should not re-execute BatchResultWriter resultWriter = getSuccessResultWriter(); setIsRestart(resultWriter); DependencyGraph originalGraph = getPrimitiveDepGraph(); DependencyNode primitiveNode = originalGraph.getDependencyNodes().iterator().next(); putValue(new ComputedValue(primitiveNode.getOutputValues().iterator().next(), 500.50)); DependencyGraph graphToExecute = resultWriter.getGraphToExecute(originalGraph); assertEquals(0, graphToExecute.getSize()); } @Test public void emptyResult() { CalculationJobResult result = new CalculationJobResult( _calcJob.getSpecification(), 0, Collections.<CalculationJobResultItem>emptyList(), "localhost"); BatchResultWriter resultWriter = getSuccessResultWriter(); resultWriter.jobExecuted(result, null); assertEquals(0, resultWriter.getNumRiskRows()); assertEquals(0, resultWriter.getNumRiskFailureRows()); assertEquals(0, resultWriter.getNumRiskFailureReasonRows()); assertEquals(0, resultWriter.getNumRiskComputeFailureRows()); } @Test public void functionWasSuccessful() { CalculationJobResultItem item = new CalculationJobResultItem(_calcJob.getJobItems().get(0)); putOutputToCache(); CalculationJobResult result = new CalculationJobResult( _calcJob.getSpecification(), 200, Collections.singletonList(item), "localhost"); BatchResultWriter resultWriter = getSuccessResultWriter(); resultWriter.jobExecuted(result, null); assertEquals(1, resultWriter.getNumRiskRows()); RiskValue value = getValueFromDb(resultWriter); assertEquals(_mockFunction.getResult().getValue(), value.getValue()); assertEquals(0, resultWriter.getNumRiskFailureRows()); assertEquals(0, resultWriter.getNumRiskFailureReasonRows()); assertEquals(0, resultWriter.getNumRiskComputeFailureRows()); } @Test public void functionWasSuccessfulButProducesUnsupportedOutputType() { CalculationJobResultItem item = new CalculationJobResultItem(_calcJob.getJobItems().get(0)); ComputedValue outputWithANonDoubleValue = new ComputedValue( _mockFunction.getResultSpec(), "unsupported value type: String"); putValue(outputWithANonDoubleValue); CalculationJobResult result = new CalculationJobResult( _calcJob.getSpecification(), 200, Collections.singletonList(item), "localhost"); BatchResultWriter resultWriter = getSuccessResultWriter(); resultWriter.jobExecuted(result, null); assertEquals(0, resultWriter.getNumRiskRows()); assertEquals(1, resultWriter.getNumRiskFailureRows()); assertEquals(0, resultWriter.getNumRiskFailureReasonRows()); assertEquals(0, resultWriter.getNumRiskComputeFailureRows()); } @Test public void functionExecutionThrewException() { CalculationJobResultItem item = new CalculationJobResultItem( _calcJob.getJobItems().get(0), new RuntimeException("function execution failed")); CalculationJobResult result = new CalculationJobResult( _calcJob.getSpecification(), 200, Collections.singletonList(item), "localhost"); BatchResultWriter resultWriter = getSuccessResultWriter(); resultWriter.jobExecuted(result, null); assertEquals(0, resultWriter.getNumRiskRows()); assertEquals(1, resultWriter.getNumRiskFailureRows()); assertEquals(1, resultWriter.getNumRiskFailureReasonRows()); assertEquals(1, resultWriter.getNumRiskComputeFailureRows()); } @Test public void missingFunctionInputs() { CalculationJobResultItem item = new CalculationJobResultItem( _calcJob.getJobItems().get(0), new MissingInputException( _calcJob.getJobItems().get(0).getInputs(), _mockFunction.getUniqueIdentifier())); ComputeFailureKey inputFailureKey = new ComputeFailureKey( item.getItem().getFunctionUniqueIdentifier(), item.getExceptionClass(), item.getExceptionMsg(), item.getStackTrace()); BatchResultWriter resultWriter = getSuccessResultWriter(); resultWriter.openSession(); ComputeFailure inputFailure = resultWriter.saveComputeFailure(inputFailureKey); resultWriter.closeSession(); assertEquals(0, resultWriter.getNumRiskRows()); assertEquals(0, resultWriter.getNumRiskFailureRows()); assertEquals(0, resultWriter.getNumRiskFailureReasonRows()); assertEquals(1, resultWriter.getNumRiskComputeFailureRows()); BatchResultWriter.BatchResultWriterFailure cachedInputFailure = new BatchResultWriter.BatchResultWriterFailure(); cachedInputFailure.addComputeFailureId(inputFailure.getId()); ComputedValue cachedInputFailureValue = new ComputedValue(item.getItem().getInputs().iterator().next(), cachedInputFailure); putValue(cachedInputFailureValue); CalculationJobResult result = new CalculationJobResult( _calcJob.getSpecification(), 200, Collections.singletonList(item), "localhost"); resultWriter.jobExecuted(result, null); assertEquals(0, resultWriter.getNumRiskRows()); assertEquals(1, resultWriter.getNumRiskFailureRows()); assertEquals(1, resultWriter.getNumRiskFailureReasonRows()); assertEquals(1, resultWriter.getNumRiskComputeFailureRows()); } @Test public void missingFunctionInputsButNoInputFailureInformationInCache() { CalculationJobResultItem item = new CalculationJobResultItem( _calcJob.getJobItems().get(0), new MissingInputException( _calcJob.getJobItems().get(0).getInputs(), _mockFunction.getUniqueIdentifier())); CalculationJobResult result = new CalculationJobResult( _calcJob.getSpecification(), 200, Collections.singletonList(item), "localhost"); BatchResultWriter resultWriter = getSuccessResultWriter(); resultWriter.jobExecuted(result, null); assertEquals(0, resultWriter.getNumRiskRows()); assertEquals(1, resultWriter.getNumRiskFailureRows()); assertEquals(0, resultWriter.getNumRiskFailureReasonRows()); assertEquals(0, resultWriter.getNumRiskComputeFailureRows()); } @Test public void successfulAndFailedResultOnSameTarget() { CalculationJobResultItem successItem = new CalculationJobResultItem( new CalculationJobItem("function1", new EmptyFunctionParameters(), _mockFunction.getTarget().toSpecification(), Collections.<ValueSpecification>emptySet(), Collections.singleton(new ValueRequirement("OUTPUT1", _mockFunction.getTarget().toSpecification())))); CalculationJobResultItem failedItem = new CalculationJobResultItem( new CalculationJobItem("function1", new EmptyFunctionParameters(), _mockFunction.getTarget().toSpecification(), Collections.<ValueSpecification>emptySet(), Collections.singleton(new ValueRequirement("OUTPUT2", _mockFunction.getTarget().toSpecification()))), new RuntimeException("function execution failed")); ArrayList<CalculationJobResultItem> items = new ArrayList<CalculationJobResultItem>(); items.add(successItem); items.add(failedItem); CalculationJobResult result = new CalculationJobResult( _calcJob.getSpecification(), 200, items, "localhost"); BatchResultWriter resultWriter = getSuccessResultWriter(); resultWriter.jobExecuted(result, null); // note - success row not written assertEquals(0, resultWriter.getNumRiskRows()); assertEquals(2, resultWriter.getNumRiskFailureRows()); assertEquals(1, resultWriter.getNumRiskFailureReasonRows()); assertEquals(1, resultWriter.getNumRiskComputeFailureRows()); } @Override public Class<?>[] getHibernateMappingClasses() { return BatchDbManagerImpl.getHibernateMappingClasses(); } private RiskValue getValueFromDb(BatchResultWriter resultWriter) { return resultWriter.getValue( CalculationNodeUtils.CALC_CONF_NAME, _mockFunction.getResultSpec().getRequirementSpecification().getValueName(), _mockFunction.getTarget().toSpecification()); } private void putOutputToCache() { ComputedValue output = _mockFunction.getResult(); putValue(output); } private void putValue(ComputedValue value) { ViewComputationCache cache = getCache(); cache.putValue(value); } private ViewComputationCache getCache() { ViewComputationCache cache = _calcNode.getCache(_calcJob.getSpecification()); return cache; } }
package com.contained.game.handler; import java.awt.Point; import java.util.ArrayList; import java.util.Collections; import com.contained.game.Contained; import com.contained.game.ContainedRegistry; import com.contained.game.Settings; import com.contained.game.data.Data; import com.contained.game.data.DataItemStack; import com.contained.game.data.DataLogger; import com.contained.game.data.Data.OccupationRank; import com.contained.game.entity.ExtendedPlayer; import com.contained.game.item.BlockInteractItem; import com.contained.game.item.DowsingRod; import com.contained.game.item.ItemTerritory; import com.contained.game.item.SurveyClipboard; import com.contained.game.network.ClientPacketHandlerUtil; import com.contained.game.ui.survey.SurveyData; import com.contained.game.user.PlayerMiniGame; import com.contained.game.user.PlayerTeam; import com.contained.game.user.PlayerTeamIndividual; import com.contained.game.user.PlayerTeamInvitation; import com.contained.game.util.MiniGameUtil; import com.contained.game.util.Resources; import com.contained.game.util.Util; import com.contained.game.world.block.AntiTerritoryMachine; import com.contained.game.world.block.TerritoryMachine; import com.contained.game.world.block.TerritoryMachineTE; import codechicken.lib.packet.PacketCustom; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; import cpw.mods.fml.relauncher.ReflectionHelper; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.effect.EntityLightningBolt; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemMonsterPlacer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.DamageSource; import net.minecraft.util.MathHelper; import net.minecraftforge.event.entity.EntityJoinWorldEvent; import net.minecraftforge.event.entity.EntityEvent.EntityConstructing; import net.minecraftforge.event.entity.living.LivingDeathEvent; import net.minecraftforge.event.entity.living.LivingDropsEvent; import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent; import net.minecraftforge.event.entity.player.EntityItemPickupEvent; import net.minecraftforge.event.entity.player.ItemTooltipEvent; import net.minecraftforge.event.entity.player.PlayerInteractEvent; import net.minecraftforge.event.entity.player.PlayerSleepInBedEvent; import net.minecraftforge.event.entity.player.PlayerUseItemEvent; import net.minecraftforge.event.entity.player.PlayerEvent.Clone; import net.minecraftforge.event.world.BlockEvent; import net.minecraftforge.event.world.BlockEvent.HarvestDropsEvent; public class PlayerEvents { @SubscribeEvent //When a player joins the server, send their client the territory & team data. public void onJoin(EntityJoinWorldEvent event) { if (event.entity instanceof EntityPlayer && !event.world.isRemote) { EntityPlayer joined = (EntityPlayer)event.entity; boolean completedSurvey = false; if (PlayerTeamIndividual.get(joined) == null) { // Server has no info about this player, this must be their first // time joining. Initialize their custom data. Contained.teamMemberData.add(new PlayerTeamIndividual(joined.getDisplayName())); Contained.channel.sendToAll(ClientPacketHandlerUtil.packetNewPlayer(joined.getDisplayName()).toPacket()); } else { PlayerTeamIndividual pdata = PlayerTeamIndividual.get(joined); //If player has not completed the survey, give them a reminder. if (pdata.surveyResponses.progress <= SurveyData.getSurveyLength()) Util.displayMessage(joined, "§a§l(Reminder: Please take a moment to fill out §a§lyour §a§lsurvey)"); else completedSurvey = true; //If the player has pending invitations, let them know. if (PlayerTeamInvitation.getInvitations(pdata).size() > 0) Util.displayMessage(joined, "§d§lYou have pending inviations in your guild §d§lmenu!"); // If the player got accepted into a team since last time they // were online, let them know. if (pdata.teamID != null && pdata.joinTime > pdata.lastOnline) { PlayerTeam newTeam = PlayerTeam.get(pdata.teamID, joined.dimension); if (newTeam != null) Util.displayMessage(joined, "§d§lYou are now a member of "+newTeam.getFormatCode()+"§l"+newTeam.displayName+"§d§l!"); pdata.lastOnline = System.currentTimeMillis(); } } //If player does not have a survey in their inventory, give them one. if (!completedSurvey && !joined.inventory.hasItem(SurveyClipboard.instance) && joined.inventory.getFirstEmptyStack() > -1){ joined.inventory.addItemStackToInventory(new ItemStack(SurveyClipboard.instance, 1)); PacketCustom itemPacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.ADD_ITEM); itemPacket.writeItemStack(new ItemStack(SurveyClipboard.instance, 1)); Contained.channel.sendTo(itemPacket.toPacket(), (EntityPlayerMP) joined); } //If dowsing is enabled, give the player a dowsing rod. if (Contained.configs.enableDowsing[Settings.getDimConfig(joined.dimension)] && !joined.inventory.hasItem(DowsingRod.instance) && joined.inventory.getFirstEmptyStack() > -1) { joined.inventory.addItemStackToInventory(new ItemStack(DowsingRod.instance, 1)); PacketCustom itemPacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.ADD_ITEM); itemPacket.writeItemStack(new ItemStack(DowsingRod.instance, 1)); Contained.channel.sendTo(itemPacket.toPacket(), (EntityPlayerMP) joined); } //Tutorial book if (!joined.inventory.hasItem(ContainedRegistry.book) && joined.inventory.getFirstEmptyStack() > -1){ joined.inventory.addItemStackToInventory(new ItemStack(ContainedRegistry.book, 1)); PacketCustom itemPacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.ADD_ITEM); itemPacket.writeItemStack(new ItemStack(ContainedRegistry.book, 1)); Contained.channel.sendTo(itemPacket.toPacket(), (EntityPlayerMP) joined); } //Update PlayerMiniGame When Joining Server if(!ExtendedPlayer.get(joined).isAdmin() && (MiniGameUtil.isPvP(joined.dimension) || MiniGameUtil.isTreasure(joined.dimension))){ PlayerMiniGame miniGame = PlayerMiniGame.get(joined.dimension); if(miniGame != null && ExtendedPlayer.get(joined).gameID == miniGame.getGameID()){ PacketCustom miniGamePacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.MINIGAME_STARTED); miniGamePacket.writeInt(miniGame.getGameMode()); miniGamePacket.writeInt(miniGame.getGameID()); NBTTagCompound miniGameTag = new NBTTagCompound(); miniGame.writeToNBT(miniGameTag); miniGamePacket.writeNBTTagCompound(miniGameTag); miniGamePacket.writeInt(miniGame.getGameDimension()); miniGamePacket.writeInt(Contained.getTeamList(miniGame.getGameDimension()).size()); for(PlayerTeam team : Contained.getTeamList(miniGame.getGameDimension())){ NBTTagCompound teamTag = new NBTTagCompound(); team.writeToNBT(teamTag); miniGamePacket.writeNBTTagCompound(teamTag); } Contained.channel.sendTo(miniGamePacket.toPacket(), (EntityPlayerMP) joined); } else { //If MiniGame Does Not Exist, Send Back To Lobby //Do not reward player and do not update stats int dim = joined.dimension; Util.travelToDimension(Resources.OVERWORLD, joined, true); PacketCustom miniGamePacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.MINIGAME_ENDED); miniGamePacket.writeInt(dim); Contained.channel.sendTo(miniGamePacket.toPacket(), (EntityPlayerMP) joined); } } // Players should get a short period of invincibility upon respawning // to prevent spawn camping joined.addPotionEffect(new PotionEffect(Potion.resistance.id, 20*15, 5)); if (joined instanceof EntityPlayerMP) { Contained.channel.sendTo(ClientPacketHandlerUtil.packetSyncTeams(Contained.getTeamList(joined.dimension)).toPacket(), (EntityPlayerMP) joined); Contained.channel.sendTo(ClientPacketHandlerUtil.packetSyncTerritories(Contained.getTerritoryMap(joined.dimension)).toPacket(), (EntityPlayerMP) joined); Contained.channel.sendTo(ClientPacketHandlerUtil.packetSyncLocalPlayer((EntityPlayer)joined).toPacket(), (EntityPlayerMP)joined); Contained.channel.sendTo(ClientPacketHandlerUtil.packetPlayerList(Contained.teamMemberData).toPacket(), (EntityPlayerMP)joined); Contained.channel.sendTo(ClientPacketHandlerUtil.packetSyncRelevantInvites(joined).toPacket(), (EntityPlayerMP)joined); Contained.channel.sendTo(ClientPacketHandlerUtil.packetSyncTrades(Contained.getTradeList(joined.dimension)).toPacket(), (EntityPlayerMP) joined); ClientPacketHandlerUtil.syncPlayerStats(ExtendedPlayer.get(joined), (EntityPlayerMP) joined); if (MiniGameUtil.isTreasure(joined.dimension)) Contained.channel.sendTo(ClientPacketHandlerUtil.packetAddTreasures(Contained.getActiveTreasures(joined.dimension), true).toPacket(), (EntityPlayerMP)joined); //Class Perks ArrayList<Integer> perks = ExtendedPlayer.get(joined).perks; PacketCustom perkPacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.PERK_INFO); for(int i = 0; i < 5; i++){ if(i < perks.size()) perkPacket.writeInt(perks.get(i)); else perkPacket.writeInt(-1); } perkPacket.writeInt(ExtendedPlayer.get(joined).occupationClass); perkPacket.writeInt(ExtendedPlayer.get(joined).occupationLevel); Contained.channel.sendTo(perkPacket.toPacket(), (EntityPlayerMP) joined); } } } @SubscribeEvent public void onLeave(PlayerEvent.PlayerLoggedOutEvent event) { PlayerTeamIndividual pdata = PlayerTeamIndividual.get(event.player); pdata.lastOnline = System.currentTimeMillis(); } @SubscribeEvent public void onRespawn(Clone event) { if(event.entityPlayer != null) { ExtendedPlayer newClone = ExtendedPlayer.get(event.entityPlayer); ExtendedPlayer oldPlayer = ExtendedPlayer.get(event.original); NBTTagCompound ntc = new NBTTagCompound(); oldPlayer.saveNBTData(ntc); newClone.loadNBTData(ntc); int dim = event.entityPlayer.dimension; if (MiniGameUtil.isPvP(dim)) { ExtendedPlayer properties = ExtendedPlayer.get(event.entityPlayer); PacketCustom syncLifePacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.SYNC_LIVES); syncLifePacket.writeInt(properties.lives); Contained.channel.sendTo(syncLifePacket.toPacket(), (EntityPlayerMP) event.entityPlayer); if(properties.lives == 0){ PacketCustom spectatorPacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.PLAYER_SPECTATOR); Contained.channel.sendTo(spectatorPacket.toPacket(), (EntityPlayerMP) event.entityPlayer); } } //TODO: Bugging Out on Developer Mode, will auto end game for pvp if((MiniGameUtil.isPvP(dim) || MiniGameUtil.isTreasure(dim))){ boolean endGame = false; if(PlayerMiniGame.get(dim) == null) endGame = true; else if(PlayerMiniGame.get(dim).getGameID() != oldPlayer.gameID) endGame = true; if(endGame) { PlayerTeamIndividual pdata = PlayerTeamIndividual.get(event.entityPlayer.getDisplayName()); ExtendedPlayer properties = ExtendedPlayer.get(event.entityPlayer); int playerScore = 0; int winScore = DataLogger.findGameWinScore(properties.gameID, pdata.teamID); String winCondition = DataLogger.findGameWinCondition(properties.gameID); String teamID = DataLogger.findGameWinTeamID(properties.gameID); if(MiniGameUtil.isPvP(dim) && pdata.teamID != null){ playerScore = properties.curKills - properties.curDeaths + properties.curAntiTerritory; DataLogger.insertPVPScore(Util.getServerID(), properties.gameID, event.entityPlayer.getDisplayName(), pdata.teamID, properties.curKills, properties.curDeaths, properties.curAntiTerritory, Util.getDate()); if(!winCondition.equals("TIE")){ if(pdata.teamID.equalsIgnoreCase(teamID)) properties.pvpWon++; else if (!teamID.equals("Debug") && !teamID.equals("Kicked")) properties.pvpLost++; } properties.kills+=properties.curKills; properties.deaths+=properties.curDeaths; properties.antiTerritory+=properties.curAntiTerritory; }else if(MiniGameUtil.isTreasure(dim) && pdata.teamID != null){ playerScore = properties.curTreasuresOpened + properties.curAltersActivated; DataLogger.insertTreasureScore(Util.getServerID(), properties.gameID, event.entityPlayer.getDisplayName(), pdata.teamID, properties.curTreasuresOpened, properties.curAltersActivated, Util.getDate()); if(!winCondition.equals("TIE")){ if(pdata.teamID.equalsIgnoreCase(teamID)) properties.treasureWon++; else if (!teamID.equals("Debug") && !teamID.equals("Kicked")) properties.treasureLost++; } properties.treasuresOpened+=properties.curTreasuresOpened; properties.altersActivated+=properties.curAltersActivated; } //Reward XP Points To Player String teamMiniGame = pdata.teamID; if(teamID != null && winCondition != null){ boolean emptySlot = false; int index = -1; for(int i = 0; i < pdata.inventory.length; i++){ ItemStack item = pdata.inventory[i]; if(item == null){ emptySlot = true; index = i; break; } } if(!emptySlot) PlayerMiniGame.rewardXP(event.entityPlayer, pdata, properties.altersActivated, properties.antiTerritory, properties.kills, playerScore, winScore, winCondition, pdata.teamID.equals(teamID)); } Util.travelToDimension(Resources.OVERWORLD, event.entityPlayer, true); //Reward Item To Player if(teamID != null && teamMiniGame != null && winCondition != null){ if(event.entityPlayer.inventory.getFirstEmptyStack() > -1) PlayerMiniGame.rewardItem(event.entityPlayer, properties.altersActivated, properties.antiTerritory, properties.kills, playerScore, winScore, winCondition, pdata.teamID.equals(teamID)); } if(MiniGameUtil.isPvP(dim)){ PacketCustom syncScore = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.SYNC_PVP_STATS); syncScore.writeInt(properties.pvpWon); syncScore.writeInt(properties.pvpLost); syncScore.writeInt(properties.kills); syncScore.writeInt(properties.deaths); syncScore.writeInt(properties.antiTerritory); Contained.channel.sendTo(syncScore.toPacket(), (EntityPlayerMP) event.entityPlayer); }else if(MiniGameUtil.isTreasure(dim)){ PacketCustom syncScore = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.SYNC_TEASURE_STATS); syncScore.writeInt(properties.treasureWon); syncScore.writeInt(properties.treasureLost); syncScore.writeInt(properties.treasuresOpened); syncScore.writeInt(properties.altersActivated); Contained.channel.sendTo(syncScore.toPacket(), (EntityPlayerMP) event.entityPlayer); } PacketCustom miniGamePacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.MINIGAME_ENDED); miniGamePacket.writeInt(dim); Contained.channel.sendTo(miniGamePacket.toPacket(), (EntityPlayerMP)event.entityPlayer); } } } } @SubscribeEvent public void onEntityLiving(LivingUpdateEvent event) { if (event.entity != null && event.entity instanceof EntityPlayer && !event.entity.worldObj.isRemote) { EntityPlayer player = (EntityPlayer)event.entity; ExtendedPlayer properties = ExtendedPlayer.get(player); // Handle nether portal override boolean wasInPortal = ReflectionHelper.getPrivateValue(Entity.class, player, "inPortal", "field_71087_bX"); if (wasInPortal) { ReflectionHelper.setPrivateValue(Entity.class, player, false, "inPortal", "field_71087_bX"); for(int i=-3; i<=3; i+=1) { for(int j=-3; j<=3; j+=1) { for(int k=-3; k<=3; k+=1) { if (player.worldObj.getBlock((int)player.posX+i, (int)player.posY+k, (int)player.posZ+j).equals(Blocks.portal)) player.worldObj.setBlock((int)player.posX+i, (int)player.posY+k, (int)player.posZ+j, Blocks.air); } } } player.worldObj.createExplosion(player, player.posX, player.posY, player.posZ, 1, false); player.worldObj.spawnEntityInWorld(new EntityLightningBolt(player.worldObj, player.posX, player.posY+1, player.posZ)); EntityLiving mobSpawn = (EntityLiving)EntityList.createEntityByName(Util.choose("PigZombie", "PigZombie", "Blaze", "LavaSlime"), player.worldObj); mobSpawn.setLocationAndAngles(player.posX, player.posY, player.posZ, MathHelper.wrapAngleTo180_float(player.worldObj.rand.nextFloat() * 360.0F), 0f); player.worldObj.spawnEntityInWorld(mobSpawn); if (Math.random() < 0.5) { player.worldObj.spawnEntityInWorld(new EntityItem(player.worldObj, player.posX, player.posY+1, player.posZ, Util.choose(new ItemStack(Items.quartz, 8) ,new ItemStack(Blocks.obsidian, 2) ,new ItemStack(Items.nether_wart, 4) ,new ItemStack(Items.netherbrick, 32) ,new ItemStack(Blocks.netherrack, 16) ,new ItemStack(Blocks.soul_sand, 8)))); } mobSpawn.playLivingSound(); } // Update Admin Rights When Logging Back In Or Changing Dimensions if(properties.isAdmin()){ if(!player.isInvisible() || !player.capabilities.allowFlying || !player.capabilities.disableDamage){ player.setInvisible(true); player.capabilities.allowFlying = true; player.capabilities.disableDamage = true; PacketCustom adminPacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.PLAYER_ADMIN); Contained.channel.sendTo(adminPacket.toPacket(), (EntityPlayerMP)player); } } //Check If Player Is In A Valid MiniGame Dimension if(!properties.isAdmin() && (MiniGameUtil.isPvP(player.dimension) || MiniGameUtil.isTreasure(player.dimension))){ int dim = player.dimension; PlayerMiniGame miniGame = PlayerMiniGame.get(player.dimension); if(miniGame == null || (miniGame != null && miniGame.getGameID() != properties.gameID)){ PlayerTeamIndividual pdata = PlayerTeamIndividual.get(player.getDisplayName()); Util.displayMessage(player, "The MiniGame You Were In Has Ended, We Are Sending You Back To Where You Belong!"); Util.travelToDimension(Resources.OVERWORLD, player, true); PacketCustom miniGamePacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.MINIGAME_ENDED); miniGamePacket.writeInt(dim); Contained.channel.sendTo(miniGamePacket.toPacket(), (EntityPlayerMP) player); //Update Player Stats if(MiniGameUtil.isPvP(dim)){ PacketCustom syncScore = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.SYNC_PVP_STATS); syncScore.writeInt(properties.pvpWon); syncScore.writeInt(properties.pvpLost); syncScore.writeInt(properties.kills); syncScore.writeInt(properties.deaths); Contained.channel.sendTo(syncScore.toPacket(), (EntityPlayerMP) player); }else if(MiniGameUtil.isTreasure(dim)){ PacketCustom syncScore = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.SYNC_TEASURE_STATS); syncScore.writeInt(properties.treasureWon); syncScore.writeInt(properties.treasureLost); syncScore.writeInt(properties.treasuresOpened); Contained.channel.sendTo(syncScore.toPacket(), (EntityPlayerMP) player); } } } //Intermittently sync data logging information with the client //so the visualizations can be updated. if (player != null && Math.random() <= 1.0/20.0) { int[] occupationData = ExtendedPlayer.get(player).getOccupationValues(); if (player instanceof EntityPlayerMP) { PacketCustom occPacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.OCCUPATIONAL_DATA); for(int i=0; i<occupationData.length; i++) occPacket.writeInt(occupationData[i]); Contained.channel.sendTo(occPacket.toPacket(), (EntityPlayerMP)player); PacketCustom usePacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.ITEM_USAGE_DATA); usePacket.writeInt(ExtendedPlayer.get(player).usedOwnItems); usePacket.writeInt(ExtendedPlayer.get(player).usedOthersItems); usePacket.writeInt(ExtendedPlayer.get(player).usedByOthers); Contained.channel.sendTo(usePacket.toPacket(), (EntityPlayerMP)player); PlayerTeamIndividual pdata = PlayerTeamIndividual.get(player); if(pdata.surveyResponses.progress < SurveyData.getSurveyLength() && Resources.MANDATORY_SURVEY){ if(!player.isInvisible() || !player.capabilities.disableDamage){ player.setInvisible(true); player.capabilities.disableDamage = true; } PacketCustom perkPacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.START_SURVEY); Contained.channel.sendTo(perkPacket.toPacket(), (EntityPlayerMP) player); } else if(!ExtendedPlayer.get(player).isAdmin() && (player.isInvisible() || player.capabilities.disableDamage)){ player.setInvisible(false); player.capabilities.disableDamage = false; PacketCustom perkPacket = new PacketCustom(Resources.MOD_ID, ClientPacketHandlerUtil.PLAYER_NORMAL); Contained.channel.sendTo(perkPacket.toPacket(), (EntityPlayerMP) player); } } } //Update items in a player's inventory which //have no owner to be owned by them if (player != null) { ItemStack[] inventory = player.inventory.mainInventory; for(int i=0; i<inventory.length; i++) if (inventory[i] != null) { if (processNewOwnership(player, inventory[i], false)) { event.entity.worldObj.spawnEntityInWorld(new EntityItem(event.entity.worldObj, event.entity.posX, event.entity.posY+1, event.entity.posZ, inventory[i])); inventory[i] = null; } } } } } @SubscribeEvent public void onEntityDeath(LivingDeathEvent event) { Entity source = event.source.getSourceOfDamage(); if (event.entityLiving == null || source == null || event.entityLiving.worldObj.isRemote) return; // Players in teams should drop anti-territory gems when they are killed by other players. if (event.entityLiving instanceof EntityPlayer && source instanceof EntityPlayer) { EntityPlayer killed = (EntityPlayer)event.entityLiving; EntityPlayer killer = (EntityPlayer)source; PlayerTeamIndividual playerData = PlayerTeamIndividual.get(killed); if (playerData.teamID != null) { int amount = 1; if (MiniGameUtil.isPvP(event.entityLiving.dimension)) { int territoryCount = (int)Math.pow(Contained.configs.pvpTerritorySize*2+1, 2); amount = Util.randomRange( (int)Math.ceil(Math.sqrt(territoryCount/2D)), (int)Math.sqrt(territoryCount)); } else { if (playerData.isLeader) //Leaders drop more anti-gems on death. amount = 4; } ItemStack toDrop = new ItemStack(ItemTerritory.removeTerritory, amount); NBTTagCompound itemData = Data.getTagCompound(toDrop); itemData.setString("teamOwner", playerData.teamID); toDrop.setTagCompound(itemData); processNewOwnership(killer, toDrop, true); killed.worldObj.spawnEntityInWorld(new EntityItem(killed.worldObj, killed.posX, killed.posY+1, killed.posZ, toDrop)); } } //Players should drop only a small portion of their inventory on death. if (event.entityLiving instanceof EntityPlayer && source instanceof EntityLivingBase) { EntityPlayer killed = (EntityPlayer)event.entityLiving; ArrayList<Integer> definedSlots = new ArrayList<Integer>(); for(int i=0; i<killed.inventory.mainInventory.length; i++) { if (killed.inventory.mainInventory[i] != null) definedSlots.add(i); } Collections.shuffle(definedSlots); int numStacksToRemove = (int)Math.ceil((float)definedSlots.size()/8F); for (int i=0; i<numStacksToRemove; i++) { ItemStack toDrop = killed.inventory.mainInventory[definedSlots.get(i)]; if (source instanceof EntityPlayer) processNewOwnership((EntityPlayer)source, toDrop, true); killed.worldObj.spawnEntityInWorld(new EntityItem(killed.worldObj, killed.posX, killed.posY+1, killed.posZ, toDrop)); killed.inventory.mainInventory[definedSlots.get(i)] = null; } } } @SubscribeEvent // For players that are in teams, only allow them to sleep in beds that are // within their team's territory. public void onBedSleep(PlayerSleepInBedEvent ev) { if (ev.entityPlayer != null && !ev.entityPlayer.worldObj.isRemote) { PlayerTeamIndividual playerData = PlayerTeamIndividual.get(ev.entityPlayer); if (playerData.teamID != null) { Point probe = new Point(ev.x, ev.z); int dimID = ev.entityPlayer.worldObj.provider.dimensionId; if (!Contained.getTerritoryMap(dimID).containsKey(probe) || !Contained.getTerritoryMap(dimID).get(probe).equals(playerData.teamID)) { ev.result = EntityPlayer.EnumStatus.OTHER_PROBLEM; Util.displayError(ev.entityPlayer, "You can only sleep within your team's territory."); } } } } @SubscribeEvent public void onEntityConstructing(EntityConstructing event) { if (event.entity instanceof EntityPlayer && ExtendedPlayer.get((EntityPlayer) event.entity) == null) ExtendedPlayer.register((EntityPlayer) event.entity); } //Handle all data collection for a player using (consuming) an item. public void processItemUsage(EntityPlayer user, ItemStack item) { if (!user.worldObj.isRemote) { NBTTagCompound itemData = Data.getTagCompound(item); String ownerName = itemData.getString("owner"); EntityPlayer owner = user.worldObj.getPlayerEntityByName(ownerName); //Use own item if (ownerName.equals(user.getDisplayName())) { ExtendedPlayer.get(user).usedOwnItems += 1; } //Use other person's item else { ExtendedPlayer.get(user).usedOthersItems += 1; if (owner != null) //Note: Data logging here may be flawed, as I don't //think it will be able to update this parameter //if the owner of the item is not currently online. ExtendedPlayer.get(owner).usedByOthers += 1; } } } @SubscribeEvent //When an item is used, if it is consumed by the usage, log it. public void onItemUsed(PlayerUseItemEvent.Finish event) { if (event.entityPlayer != null && event.item != null) processItemUsage(event.entityPlayer, event.item); } @SubscribeEvent //Handle firing the functionality of BlockInteractItems when right-clicked on a block. public void onItemUse(PlayerInteractEvent event) { if (!event.world.isRemote) { ItemStack usedItem = event.entityPlayer.getHeldItem(); if (usedItem == null) return; if (usedItem.getItem() instanceof BlockInteractItem && event.action == PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK) { BlockInteractItem intItem = (BlockInteractItem)usedItem.getItem(); intItem.onBlockInteract(event.entityPlayer, event.x, event.y, event.z, usedItem); } } } @SubscribeEvent //Transfer player's team to a territory machine when placed. public void onBlockPlacement(BlockEvent.PlaceEvent ev) { if (ev.player != null && (ev.block instanceof TerritoryMachine.BlockClaimTerritory || ev.block instanceof AntiTerritoryMachine.BlockAntiTerritory)) { TileEntity te = ev.world.getTileEntity(ev.x, ev.y, ev.z); if (te != null && te instanceof TerritoryMachineTE) { TerritoryMachineTE machine = (TerritoryMachineTE)te; if (!ev.world.isRemote && ev.block instanceof TerritoryMachine.BlockClaimTerritory) { PlayerTeamIndividual playerData = PlayerTeamIndividual.get(ev.player); machine.teamID = playerData.teamID; machine.sendInfoPacket(); } if (ev.block instanceof AntiTerritoryMachine.BlockAntiTerritory && ev.itemInHand != null) { NBTTagCompound itemData = Data.getTagCompound(ev.itemInHand); String teamID = itemData.getString("teamOwner"); if (teamID == null || teamID.equals("")) machine.teamID = null; else { machine.teamID = teamID; machine.sendInfoPacket(); } } } } } //Handle all data collection procedures for when a player becomes //the owner of a new item. public boolean processNewOwnership(EntityPlayer newOwner, ItemStack item, boolean forceOwner) { //First make sure this item isn't owned by someone already... NBTTagCompound itemData = Data.getTagCompound(item); String owner = itemData.getString("owner"); if ((owner == null || owner.equals("") || forceOwner) && newOwner != null) { //Check if this item corresponds to an "occupation", and update //player's values accordingly OccupationRank occ = Data.occupationMap.get(new DataItemStack(item)); if (occ != null) { ExtendedPlayer.get(newOwner) .increaseOccupation(occ.occupationID, occ.rank*item.stackSize); } //Set this player as the new owner of the item itemData.setString("owner", newOwner.getDisplayName()); item.setTagCompound(itemData); //If the item is a spawn egg, set its display name to match the owner. if (item.getItem() instanceof ItemMonsterPlacer) item.setStackDisplayName(newOwner.getDisplayName()); return true; } return false; } @SubscribeEvent //When an unowned item is collected, it is owned by the collector. public void onItemCollected(EntityItemPickupEvent event) { if (event.entityPlayer != null) processNewOwnership(event.entityPlayer, event.item.getEntityItem(), false); } @SubscribeEvent //When a block is harvested, the dropped items are owned by the harvester. public void onItemHarvested(HarvestDropsEvent event) { ArrayList<ItemStack> drops = event.drops; for (ItemStack stack : drops) processNewOwnership(event.harvester, stack, false); } @SubscribeEvent //When a creature is killed, the dropped items are owned by the killer. public void onCreatureDropItems(LivingDropsEvent event) { DamageSource ds = event.source; if (ds != null && ds.getEntity() != null && ds.getEntity() instanceof EntityPlayer) { EntityPlayer killer = (EntityPlayer)ds.getEntity(); ArrayList<EntityItem> drops = event.drops; for (EntityItem item : drops) processNewOwnership(killer, item.getEntityItem(), false); } } @SubscribeEvent //Show the owner of an item in the item's mouse-over tooltip. public void itemInformation(ItemTooltipEvent event) { ItemStack stack = event.itemStack; NBTTagCompound itemData = Data.getTagCompound(stack); String owner = itemData.getString("owner"); if (owner == null || owner.equals("")) event.toolTip.add("Not Owned"); else event.toolTip.add("Owner: "+owner); } @SubscribeEvent //Make a player wait a little longer to loot an item if it belongs //to someone else. public void onItemPickup(EntityItemPickupEvent event) { int secondsToWait = 10; ItemStack stack = event.item.getEntityItem(); NBTTagCompound itemData = Data.getTagCompound(stack); String owner = itemData.getString("owner"); if (event.entityPlayer != null && !(owner == null || owner.equals("") || owner.equals(event.entityPlayer.getDisplayName()))) { if (event.item.ticksExisted < 20*secondsToWait) event.setCanceled(true); } } }
package com.easternedgerobotics.rov.io; import com.easternedgerobotics.rov.event.EventPublisher; import com.easternedgerobotics.rov.value.ThrusterSpeedValue; import com.pi4j.io.i2c.I2CDevice; import java.io.IOException; import java.nio.ByteBuffer; public class Thruster { private static final byte WRITE_ADDRESS = 0x00; private final byte[] zeroBuffer = new byte[] {0x00, 0x00}; private I2CDevice device; private ThrusterSpeedValue thrusterValue; private boolean initialized; public Thruster(final EventPublisher event, final ThrusterSpeedValue thruster, final I2CDevice device) { this.device = device; thrusterValue = thruster; initialized = false; event.valuesOfType(ThrusterSpeedValue.class) .filter(value -> thrusterValue.getName().equals(value.getName())) .subscribe(value -> thrusterValue = value); } /** * Write the latest {@code ThrusterSpeedValue} for this thruster to the device. * @throws IOException */ public final void write() throws IOException { final short speed = (short) (thrusterValue.getSpeed() * Short.MAX_VALUE); final byte[] writeBuffer = ByteBuffer.allocate(2).putShort(speed).array(); if (!initialized) { device.write(WRITE_ADDRESS, zeroBuffer, 0, zeroBuffer.length); initialized = true; } device.write(WRITE_ADDRESS, writeBuffer, 0, writeBuffer.length); } /** * Write zero to the thruster. * @throws IOException */ public final void writeZero() throws IOException { device.write(WRITE_ADDRESS, zeroBuffer, 0, zeroBuffer.length); } }
package com.enderio.core.common.util; import java.util.ArrayList; import java.util.List; import java.util.Random; import javax.annotation.Nonnull; import com.enderio.core.EnderCore; import com.enderio.core.common.vecmath.Vector3d; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityList; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.item.EntityFireworkRocket; import net.minecraft.entity.item.EntityItem; import net.minecraft.init.Items; import net.minecraft.item.ItemDye; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.nbt.NBTTagList; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; import net.minecraftforge.common.DimensionManager; public class EntityUtil { private static final Random rand = new Random(); public static void setEntityVelocity(Entity entity, double velX, double velY, double velZ) { entity.motionX = velX; entity.motionY = velY; entity.motionZ = velZ; } public static @Nonnull EntityFireworkRocket getRandomFirework(@Nonnull World world) { return getRandomFirework(world, new BlockPos(0, 0, 0)); } public static @Nonnull EntityFireworkRocket getRandomFirework(@Nonnull World world, @Nonnull BlockPos pos) { ItemStack firework = new ItemStack(Items.FIREWORKS); firework.setTagCompound(new NBTTagCompound()); NBTTagCompound expl = new NBTTagCompound(); expl.setBoolean("Flicker", true); expl.setBoolean("Trail", true); int[] colors = new int[rand.nextInt(8) + 1]; for (int i = 0; i < colors.length; i++) { colors[i] = ItemDye.DYE_COLORS[rand.nextInt(16)]; } expl.setIntArray("Colors", colors); byte type = (byte) (rand.nextInt(3) + 1); type = type == 3 ? 4 : type; expl.setByte("Type", type); NBTTagList explosions = new NBTTagList(); explosions.appendTag(expl); NBTTagCompound fireworkTag = new NBTTagCompound(); fireworkTag.setTag("Explosions", explosions); fireworkTag.setByte("Flight", (byte) 1); firework.setTagInfo("Fireworks", fireworkTag); EntityFireworkRocket e = new EntityFireworkRocket(world, pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, firework); return e; } public static void spawnFirework(@Nonnull BlockPos block, int dimID) { spawnFirework(block, dimID, 0); } public static void spawnFirework(@Nonnull BlockPos pos, int dimID, int range) { World world = DimensionManager.getWorld(dimID); BlockPos spawnPos = pos; // don't bother if there's no randomness at all if (range > 0) { spawnPos = new BlockPos(moveRandomly(spawnPos.getX(), range), spawnPos.getY(), moveRandomly(spawnPos.getZ(), range)); IBlockState bs = world.getBlockState(spawnPos); int tries = -1; while (!world.isAirBlock(new BlockPos(spawnPos)) && !bs.getBlock().isReplaceable(world, spawnPos)) { tries++; if (tries > 100) { return; } } } world.spawnEntity(getRandomFirework(world, spawnPos)); } private static double moveRandomly(double base, double range) { return base + 0.5 + rand.nextDouble() * range - (range / 2); } public static @Nonnull String getDisplayNameForEntity(@Nonnull String mobName) { return EnderCore.lang.localizeExact("entity." + mobName + ".name"); } public static @Nonnull NNList<ResourceLocation> getAllRegisteredMobNames() { NNList<ResourceLocation> result = new NNList<ResourceLocation>(); for (ResourceLocation entityName : EntityList.getEntityNameList()) { final Class<? extends Entity> clazz = EntityList.getClass(NullHelper.notnullF(entityName, "EntityList.getEntityNameList()")); if (clazz != null && EntityLiving.class.isAssignableFrom(clazz)) { result.add(entityName); } } return result; } public static boolean isRegisteredMob(ResourceLocation entityName) { if (entityName != null) { final Class<? extends Entity> clazz = EntityList.getClass(entityName); return clazz != null && EntityLiving.class.isAssignableFrom(clazz); } return false; } private EntityUtil() { } public static Vector3d getEntityPosition(@Nonnull Entity ent) { return new Vector3d(ent.posX, ent.posY, ent.posZ); } public static List<AxisAlignedBB> getCollidingBlockGeometry(@Nonnull World world, @Nonnull Entity entity) { AxisAlignedBB entityBounds = entity.getEntityBoundingBox(); ArrayList<AxisAlignedBB> collidingBoundingBoxes = new ArrayList<AxisAlignedBB>(); int minX = MathHelper.floor(entityBounds.minX); int minY = MathHelper.floor(entityBounds.minY); int minZ = MathHelper.floor(entityBounds.minZ); int maxX = MathHelper.floor(entityBounds.maxX + 1.0D); int maxY = MathHelper.floor(entityBounds.maxY + 1.0D); int maxZ = MathHelper.floor(entityBounds.maxZ + 1.0D); for (int x = minX; x < maxX; x++) { for (int z = minZ; z < maxZ; z++) { for (int y = minY; y < maxY; y++) { BlockPos pos = new BlockPos(x, y, z); world.getBlockState(pos).addCollisionBoxToList(world, pos, entityBounds, collidingBoundingBoxes, entity, false); } } } return collidingBoundingBoxes; } public static void spawnItemInWorldWithRandomMotion(@Nonnull World world, @Nonnull ItemStack item, int x, int y, int z) { if (!item.isEmpty()) { spawnItemInWorldWithRandomMotion(world, item, x + 0.5, y + 0.5, z + 0.5); } } public static void spawnItemInWorldWithRandomMotion(@Nonnull World world, @Nonnull ItemStack item, double x, double y, double z) { if (!item.isEmpty()) { spawnItemInWorldWithRandomMotion(new EntityItem(world, x, y, z, item)); } } public static void spawnItemInWorldWithRandomMotion(@Nonnull EntityItem entity) { entity.setDefaultPickupDelay(); float f = (entity.world.rand.nextFloat() * 0.1f) - 0.05f; float f1 = (entity.world.rand.nextFloat() * 0.1f) - 0.05f; float f2 = (entity.world.rand.nextFloat() * 0.1f) - 0.05f; entity.motionX += f; entity.motionY += f1; entity.motionZ += f2; entity.world.spawnEntity(entity); } }
package com.github.onsdigital.api.taxonomy; import java.io.IOException; import java.net.URI; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.GET; import javax.ws.rs.core.Context; import org.apache.commons.io.IOUtils; import org.eclipse.jetty.http.HttpStatus; import com.github.davidcarboni.ResourceUtils; import com.github.davidcarboni.restolino.framework.Endpoint; import com.github.onsdigital.configuration.Configuration; @Endpoint public class Data { static boolean validated; @GET public void getData(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException { // Validate all Json so that we get a warning if // there's an issue with a file that's been edited. if (!validated) { Validator.validate(); validated = true; } // Ensures ResourceUtils gets the right classloader when running // reloadable in development: ResourceUtils.classLoaderClass = Data.class; // Standardise the path: URI uri = URI.create(request.getRequestURI()); String uriPath = cleanPath(uri); Path taxonomy = FileSystems.getDefault().getPath( Configuration.getTaxonomyPath()); // Look for a data.json file, or // fall back to adding a .json file extension Path data = taxonomy.resolve(uriPath).resolve("data.json"); if (!Files.exists(data)) { data = taxonomy.resolve(uriPath + ".json"); } // Output directly to the response // (rather than deserialise and re-serialise) if (Files.exists(data)) { response.setContentType("application/json"); response.setCharacterEncoding("UTF8"); IOUtils.copy(Files.newInputStream(data), response.getOutputStream()); } else { response.setStatus(HttpStatus.NOT_FOUND_404); } } /** * @param uri * The URI to get a standardised path from. * @return The URI path, lowercasted, without the endpoint name or trailing * slash. */ String cleanPath(URI uri) { // It would be nice to use StringBuilder, // but it doesn't have the manipulation methods we need String result = uri.getPath(); // Remove slashes: if (result.startsWith("/")) { result = result.substring(1); } if (result.endsWith("/")) { result = result.substring(0, result.length() - 1); } // Remove endpoint name: String endpointName = getClass().getSimpleName().toLowerCase() + "/"; if (result.startsWith(endpointName)) { result = result.substring(endpointName.length()); } // Lowercase result = result.toLowerCase(); return result; } }
package com.gitrekt.resort.model.entities; public class Guest { private String firstName; private String lastName; private String emailAddress; private String phoneNumber; private MailingAddress mailingAddress; private boolean isCheckedIn = true; protected Guest(){ } public Guest(String firstName, String lastName, String emailAddress, String phoneNumber, MailingAddress mailingAddress) { this.emailAddress = emailAddress; this.firstName = firstName; this.lastName = lastName; this.phoneNumber = phoneNumber; this.mailingAddress = mailingAddress; } public String getLastName(){ return lastName; } public void setLastName(String lastName){ this.lastName = lastName; } public String getFirstName(){ return firstName; } public void setFirstName(String firstName){ this.firstName = firstName; } public String getEmailAddress(){ return emailAddress; } public void setEmailAddress(String emailingAddress){ this.emailAddress = emailingAddress; } public MailingAddress getMailingAddress(){ return mailingAddress; } public void setMailingAddress(MailingAddress mailingAddress){ this.mailingAddress = mailingAddress; } public String getphoneNumber(){ return phoneNumber; } public void setphoneNUmber(String phoneNumber){ this.phoneNumber = phoneNumber; } public void detChexkedIn(boolean checkedIn){ this.isCheckedIn = checkedIn; } public boolean isCheckedIn(){ return isCheckedIn; } }
package com.hibegin.http.server; import com.hibegin.common.util.BytesUtil; import com.hibegin.common.util.EnvKit; import com.hibegin.common.util.LoggerUtil; import com.hibegin.http.server.api.HttpRequestDeCoder; import com.hibegin.http.server.api.HttpRequestListener; import com.hibegin.http.server.api.HttpResponse; import com.hibegin.http.server.api.ISocketServer; import com.hibegin.http.server.config.ConfigKit; import com.hibegin.http.server.config.RequestConfig; import com.hibegin.http.server.config.ResponseConfig; import com.hibegin.http.server.config.ServerConfig; import com.hibegin.http.server.execption.ContentLengthTooLargeException; import com.hibegin.http.server.execption.UnSupportMethodException; import com.hibegin.http.server.handler.CheckRequestListenerThread; import com.hibegin.http.server.handler.HttpRequestHandlerThread; import com.hibegin.http.server.handler.PlainReadWriteSelectorHandler; import com.hibegin.http.server.handler.ReadWriteSelectorHandler; import com.hibegin.http.server.impl.HttpMethod; import com.hibegin.http.server.impl.HttpRequestDecoderImpl; import com.hibegin.http.server.impl.ServerContext; import com.hibegin.http.server.impl.SimpleHttpResponse; import com.hibegin.http.server.util.PathUtil; import com.hibegin.http.server.util.ServerInfo; import java.io.EOFException; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Level; import java.util.logging.Logger; public class SimpleWebServer implements ISocketServer { private static final Logger LOGGER = LoggerUtil.getLogger(SimpleWebServer.class); private Selector selector; private ServerConfig serverConfig; private RequestConfig requestConfig; private ResponseConfig responseConfig; private ServerContext serverContext = new ServerContext(); private List<HttpRequestHandlerThread> timeoutCheckRequestHandlerList = new CopyOnWriteArrayList<>(); private Thread checkCloseTimeoutRequestThread = new Thread(); private CheckRequestListenerThread checkRequestListenerThread = new CheckRequestListenerThread("Call-Request-Listener-Thread"); public SimpleWebServer() { this(null, null, null); } public SimpleWebServer(ServerConfig serverConfig, RequestConfig requestConfig, ResponseConfig responseConfig) { if (requestConfig == null) { requestConfig = new RequestConfig(); } if (responseConfig == null) { responseConfig = new ResponseConfig(); } this.requestConfig = requestConfig; this.responseConfig = responseConfig; if (serverConfig == null) { serverConfig = new ServerConfig(); serverConfig.setDisableCookie(Boolean.valueOf(ConfigKit.get("server.disableCookie", requestConfig.isDisableCookie()).toString())); } this.serverConfig = serverConfig; this.requestConfig = getDefaultRequestConfig(); this.responseConfig = getDefaultResponseConfig(); if (serverConfig.getTimeOut() == 0 && ConfigKit.contains("server.timeout")) { serverConfig.setTimeOut(Integer.parseInt(ConfigKit.get("server.timeout", 60).toString())); } if (serverConfig.getPort() == 0) { serverConfig.setPort(ConfigKit.getServerPort()); } serverContext.setServerConfig(serverConfig); } public ReadWriteSelectorHandler getReadWriteSelectorHandlerInstance(SocketChannel channel, SelectionKey key) throws IOException { return new PlainReadWriteSelectorHandler(channel, key, false); } @Override public void listener() { if (selector == null) { return; } serverContext.init(); if (enableRequestListener()) { checkRequestListenerThread.start(); } if (checkCloseTimeoutRequestThread == null || checkCloseTimeoutRequestThread.isInterrupted()) { tryCheckConnectTimeoutRequest(); } LOGGER.info(ServerInfo.getName() + " is run versionStr -> " + ServerInfo.getVersion()); LOGGER.log(Level.INFO, serverConfig.getRouter().toString()); try { EnvKit.savePid(PathUtil.getRootPath() + "/sim.pid"); } catch (Throwable e) { LOGGER.log(Level.WARNING, "save pid error", e); } while (true) { try { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iterator = keys.iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); SocketChannel channel = null; if (!key.isValid() || !key.channel().isOpen()) { LOGGER.log(Level.WARNING, "error key " + key); } else if (key.isAcceptable()) { ServerSocketChannel server = (ServerSocketChannel) key.channel(); try { channel = server.accept(); if (channel != null) { channel.configureBlocking(false); channel.register(selector, SelectionKey.OP_READ); } } catch (IOException e) { LOGGER.log(Level.SEVERE, "accept connect error", e); if (channel != null) { key.cancel(); channel.close(); } } } else if (key.isReadable()) { channel = (SocketChannel) key.channel(); if (!handleRequest(key, channel)) continue; } iterator.remove(); } } catch (Throwable e) { LOGGER.log(Level.SEVERE, "", e); } } } private boolean handleRequest(SelectionKey key, SocketChannel channel) { if (channel != null && channel.isOpen()) { HttpRequestDeCoder codec = serverContext.getHttpDeCoderMap().get(channel); SocketAddress socketAddress = channel.socket().getRemoteSocketAddress(); HttpRequestHandlerThread requestHandlerThread = null; try { ReadWriteSelectorHandler handler; if (codec == null) { handler = getReadWriteSelectorHandlerInstance(channel, key); codec = new HttpRequestDecoderImpl(socketAddress, requestConfig, serverContext, handler); serverContext.getHttpDeCoderMap().put(channel, codec); } else { handler = codec.getRequest().getHandler(); } requestHandlerThread = new HttpRequestHandlerThread(codec, responseConfig, serverContext); if (enableConnectTimeout()) { timeoutCheckRequestHandlerList.add(requestHandlerThread); } boolean exception = false; try { ByteBuffer byteBuffer = handler.handleRead(); byte[] bytes = BytesUtil.subBytes(byteBuffer.array(), 0, byteBuffer.array().length - byteBuffer.remaining()); if (!codec.doDecode(bytes)) { return false; } } catch (EOFException e) { //do nothing handleException(key, codec, new HttpRequestHandlerThread(codec, responseConfig, serverContext), 400); exception = true; } catch (UnSupportMethodException e) { LOGGER.log(Level.INFO, "", e); handleException(key, codec, new HttpRequestHandlerThread(codec, responseConfig, serverContext), 400); exception = true; } catch (ContentLengthTooLargeException e) { handleException(key, codec, requestHandlerThread, 413); exception = true; } catch (Exception e) { handleException(key, codec, requestHandlerThread, 500); exception = true; } if (channel.isConnected() && !exception) { if (enableRequestListener()) { HttpRequestHandlerThread oldHttpRequestHandlerThread = checkRequestListenerThread.getChannelHttpRequestHandlerThreadMap().get(channel); if (oldHttpRequestHandlerThread != null) { oldHttpRequestHandlerThread.interrupt(); } checkRequestListenerThread.getChannelHttpRequestHandlerThreadMap().put(channel, requestHandlerThread); } serverConfig.getExecutor().execute(requestHandlerThread); if (codec.getRequest().getMethod() != HttpMethod.CONNECT) { codec = new HttpRequestDecoderImpl(socketAddress, requestConfig, serverContext, handler); serverContext.getHttpDeCoderMap().put(channel, codec); } } } catch (Exception e) { LOGGER.log(Level.SEVERE, "error", e); handleException(key, codec, requestHandlerThread, 500); } } return true; } private void handleException(SelectionKey key, HttpRequestDeCoder codec, HttpRequestHandlerThread httpRequestHandlerThread, int errorCode) { try { if (httpRequestHandlerThread != null && codec != null && codec.getRequest() != null) { if (!httpRequestHandlerThread.getRequest().getHandler().getChannel().socket().isClosed()) { HttpResponse response = new SimpleHttpResponse(codec.getRequest(), getDefaultResponseConfig()); response.renderCode(errorCode); } else { callRequestListener(httpRequestHandlerThread); } } } catch (Exception e) { LOGGER.log(Level.SEVERE, "error", e); } finally { try { key.channel().close(); } catch (IOException e) { LOGGER.log(Level.SEVERE, "error", e); } key.cancel(); } } @Override public void destroy() { } @Override public boolean create() { return create(serverConfig.getPort()); } public boolean create(int port) { try { final ServerSocketChannel serverChannel = ServerSocketChannel.open(); serverChannel.socket().bind(new InetSocketAddress(serverConfig.getHost(), port)); serverChannel.configureBlocking(false); selector = Selector.open(); serverChannel.register(selector, SelectionKey.OP_ACCEPT); LOGGER.info(ServerInfo.getName() + " listening on port -> " + port); return true; } catch (IOException e) { LOGGER.log(Level.SEVERE, "", e); return false; } } private void tryCheckConnectTimeoutRequest() { if (enableConnectTimeout()) { final ServerConfig finalServerConfig = serverConfig; checkCloseTimeoutRequestThread = new Thread() { @Override public void run() { Thread.currentThread().setName("Call-Request-Timeout-Listener"); try { while (!isInterrupted()) { List<HttpRequestHandlerThread> removeHttpRequestList = new ArrayList<>(); for (HttpRequestHandlerThread handler : timeoutCheckRequestHandlerList) { if (handler.getRequest().getHandler().getChannel().socket().isClosed()) { removeHttpRequestList.add(handler); } else { if (System.currentTimeMillis() - handler.getRequest().getCreateTime() > finalServerConfig.getTimeOut() * 1000) { handler.getResponse().renderCode(504); removeHttpRequestList.add(handler); } } } timeoutCheckRequestHandlerList.removeAll(removeHttpRequestList); Thread.sleep(1000); } } catch (InterruptedException e) { LOGGER.log(Level.SEVERE, "", e); } } }; checkRequestListenerThread.start(); } } private boolean enableRequestListener() { return !serverContext.getServerConfig().getHttpRequestListenerList().isEmpty(); } private void callRequestListener(HttpRequestHandlerThread httpRequestHandlerThread) { for (HttpRequestListener requestListener : serverContext.getServerConfig().getHttpRequestListenerList()) { requestListener.destroy(httpRequestHandlerThread.getRequest(), httpRequestHandlerThread.getResponse()); } } private boolean enableConnectTimeout() { return serverConfig.getTimeOut() > 0; } private ResponseConfig getDefaultResponseConfig() { ResponseConfig config = new ResponseConfig(); config.setCharSet("UTF-8"); config.setIsGzip(responseConfig.isGzip()); config.setDisableCookie(serverConfig.isDisableCookie()); return config; } private RequestConfig getDefaultRequestConfig() { RequestConfig config = new RequestConfig(); config.setDisableCookie(serverConfig.isDisableCookie()); config.setRouter(serverConfig.getRouter()); config.setIsSsl(serverConfig.isSsl()); return config; } }
package com.hibegin.http.server; import com.hibegin.common.util.BytesUtil; import com.hibegin.common.util.EnvKit; import com.hibegin.common.util.LoggerUtil; import com.hibegin.http.server.api.HttpRequestDeCoder; import com.hibegin.http.server.api.HttpResponse; import com.hibegin.http.server.api.ISocketServer; import com.hibegin.http.server.config.ConfigKit; import com.hibegin.http.server.config.RequestConfig; import com.hibegin.http.server.config.ResponseConfig; import com.hibegin.http.server.config.ServerConfig; import com.hibegin.http.server.execption.ContentLengthTooLargeException; import com.hibegin.http.server.handler.HttpRequestHandler; import com.hibegin.http.server.handler.PlainReadWriteSelectorHandler; import com.hibegin.http.server.handler.ReadWriteSelectorHandler; import com.hibegin.http.server.impl.HttpMethod; import com.hibegin.http.server.impl.HttpRequestDecoderImpl; import com.hibegin.http.server.impl.ServerContext; import com.hibegin.http.server.impl.SimpleHttpResponse; import com.hibegin.http.server.util.PathUtil; import com.hibegin.http.server.util.ServerInfo; import java.io.EOFException; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; public class SimpleWebServer implements ISocketServer { private static final Logger LOGGER = LoggerUtil.getLogger(SimpleWebServer.class); private Selector selector; private ServerConfig serverConfig; private RequestConfig requestConfig; private ResponseConfig responseConfig; private ServerContext serverContext = new ServerContext(); private List<HttpRequestHandler> httpRequestHandlerList = new ArrayList<>(); public SimpleWebServer() { this(null, null, null); } public SimpleWebServer(ServerConfig serverConfig, RequestConfig requestConfig, ResponseConfig responseConfig) { if (requestConfig == null) { requestConfig = new RequestConfig(); } if (responseConfig == null) { responseConfig = new ResponseConfig(); } this.requestConfig = requestConfig; this.responseConfig = responseConfig; if (serverConfig == null) { serverConfig = new ServerConfig(); serverConfig.setDisableCookie(Boolean.valueOf(ConfigKit.get("server.disableCookie", requestConfig.isDisableCookie()).toString())); } this.serverConfig = serverConfig; this.requestConfig = getDefaultRequestConfig(); this.responseConfig = getDefaultResponseConfig(); if (serverConfig.getTimeOut() == 0 && ConfigKit.contains("server.timeout")) { serverConfig.setTimeOut(Integer.parseInt(ConfigKit.get("server.timeout", 60).toString())); } if (serverConfig.getPort() == 0) { serverConfig.setPort(ConfigKit.getServerPort()); } serverContext.setServerConfig(serverConfig); serverContext.init(); } public ReadWriteSelectorHandler getReadWriteSelectorHandlerInstance(SocketChannel channel, SelectionKey key) throws IOException { return new PlainReadWriteSelectorHandler(channel, key, false); } @Override public void listener() { if (selector == null) { return; } LOGGER.info(ServerInfo.getName() + " is run versionStr -> " + ServerInfo.getVersion()); LOGGER.log(Level.INFO, serverConfig.getRouter().toString()); try { EnvKit.savePid(PathUtil.getRootPath() + "/sim.pid"); } catch (Throwable e) { LOGGER.log(Level.WARNING, "save pid error", e); } while (true) { try { selector.select(); Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iterator = keys.iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); SocketChannel channel = null; if (!key.isValid() || !key.channel().isOpen()) { LOGGER.log(Level.WARNING, "error key" + key); } else if (key.isAcceptable()) { ServerSocketChannel server = (ServerSocketChannel) key.channel(); try { channel = server.accept(); if (channel != null) { channel.configureBlocking(false); channel.register(selector, SelectionKey.OP_READ); } } catch (IOException e) { LOGGER.log(Level.SEVERE, "accept connect error", e); if (channel != null) { key.cancel(); channel.close(); } } } else if (key.isReadable()) { channel = (SocketChannel) key.channel(); if (!handleRequest(key, channel)) continue; } iterator.remove(); } } catch (Throwable e) { LOGGER.log(Level.SEVERE, "", e); } } } private boolean handleRequest(SelectionKey key, SocketChannel channel) { if (channel != null && channel.isOpen()) { HttpRequestDeCoder codec = serverContext.getHttpDeCoderMap().get(channel); ReadWriteSelectorHandler handler = null; SocketAddress socketAddress = channel.socket().getRemoteSocketAddress(); try { if (codec == null) { handler = getReadWriteSelectorHandlerInstance(channel, key); codec = new HttpRequestDecoderImpl(socketAddress, requestConfig, serverContext, handler); serverContext.getHttpDeCoderMap().put(channel, codec); } else { handler = codec.getRequest().getHandler(); } ByteBuffer byteBuffer = handler.handleRead(); byte[] bytes = BytesUtil.subBytes(byteBuffer.array(), 0, byteBuffer.array().length - byteBuffer.remaining()); if (!codec.doDecode(bytes)) { return false; } HttpRequestHandler requestHandler = new HttpRequestHandler(codec, responseConfig, serverContext); serverConfig.getExecutor().execute(requestHandler); if (isOpenConnectTimeout()) { httpRequestHandlerList.add(requestHandler); } if (codec.getRequest().getMethod() != HttpMethod.CONNECT) { codec = new HttpRequestDecoderImpl(socketAddress, requestConfig, serverContext, handler); serverContext.getHttpDeCoderMap().put(channel, codec); } } catch (EOFException e) { //do nothing handleException(key, codec, null, 500); } catch (ContentLengthTooLargeException e) { handleException(key, codec, handler, 413); } catch (Exception e) { LOGGER.log(Level.SEVERE, "error", e); handleException(key, codec, handler, 500); } } return true; } private void handleException(SelectionKey key, HttpRequestDeCoder codec, ReadWriteSelectorHandler handler, int errorCode) { try { if (handler != null && codec != null && codec.getRequest() != null) { HttpResponse response = new SimpleHttpResponse(codec.getRequest(), getDefaultResponseConfig()); response.renderCode(errorCode); } } catch (Exception e) { LOGGER.log(Level.SEVERE, "error", e); } finally { try { key.channel().close(); } catch (IOException e) { LOGGER.log(Level.SEVERE, "error", e); } key.cancel(); } } @Override public void destroy() { } @Override public void create() { try { create(serverConfig.getPort()); } catch (Exception e) { LOGGER.log(Level.SEVERE, "", e); } } public void create(int port) throws IOException { ServerSocketChannel serverChannel = ServerSocketChannel.open(); serverChannel.socket().bind(new InetSocketAddress(serverConfig.getHost(), port)); serverChannel.configureBlocking(false); selector = Selector.open(); serverChannel.register(selector, SelectionKey.OP_ACCEPT); LOGGER.info(ServerInfo.getName() + " listening on port -> " + port); //timeout if (isOpenConnectTimeout()) { final ServerConfig finalServerConfig = serverConfig; Thread checkCloseThread = new Thread() { @Override public void run() { while (true) { List<HttpRequestHandler> removeHttpRequestList = new ArrayList<>(); for (HttpRequestHandler handler : httpRequestHandlerList) { if (handler.getRequest().getHandler().getChannel().socket().isClosed()) { removeHttpRequestList.add(handler); } if (System.currentTimeMillis() - handler.getRequest().getCreateTime() > finalServerConfig.getTimeOut() * 1000) { handler.getResponse().renderCode(504); removeHttpRequestList.add(handler); } } for (HttpRequestHandler handler : removeHttpRequestList) { httpRequestHandlerList.remove(handler); } try { Thread.sleep(100); } catch (InterruptedException e) { LOGGER.log(Level.SEVERE, "", e); } } } }; checkCloseThread.start(); } } private boolean isOpenConnectTimeout() { return serverConfig.getTimeOut() > 0; } private ResponseConfig getDefaultResponseConfig() { ResponseConfig config = new ResponseConfig(); config.setCharSet("UTF-8"); config.setIsGzip(responseConfig.isGzip()); config.setDisableCookie(serverConfig.isDisableCookie()); return config; } private RequestConfig getDefaultRequestConfig() { RequestConfig config = new RequestConfig(); config.setDisableCookie(serverConfig.isDisableCookie()); config.setRouter(serverConfig.getRouter()); config.setIsSsl(serverConfig.isSsl()); return config; } }
package com.liuxinglanyue.session; import java.io.IOException; import java.security.Principal; import org.apache.catalina.Manager; import org.apache.catalina.session.StandardSession; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; public class CustomSession extends StandardSession { private final static Log logger = LogFactory.getLog(CustomSession.class); private static final long serialVersionUID = 1L; protected boolean dirty; protected static boolean manualDirtyTrackingSupportEnabled = false; public CustomSession(Manager manager) { super(manager); resetDirtyTracking(); } public static void setManualDirtyTrackingSupportEnabled(boolean enabled) { manualDirtyTrackingSupportEnabled = enabled; } protected static String manualDirtyTrackingAttributeKey = "__changed__"; public static void setManualDirtyTrackingAttributeKey(String key) { manualDirtyTrackingAttributeKey = key; } public boolean isDirty() { return dirty; } public void resetDirtyTracking() { dirty = false; } @Override public void setAttribute(String key, Object value) { if (manualDirtyTrackingSupportEnabled && manualDirtyTrackingAttributeKey.equals(key)) { dirty = true; return; } Object oldValue = getAttribute(key); super.setAttribute(key, value); if ((value != null || oldValue != null) && (value == null && oldValue != null || oldValue == null && value != null || !value.getClass().isInstance(oldValue) || !value .equals(oldValue))) { if (this.manager instanceof AbstractSessionManager && ((AbstractSessionManager) this.manager).getSaveOnChange()) { try { ((AbstractSessionManager) this.manager).save(this, true); } catch (IOException ex) { logger.error("Error saving session on setAttribute (triggered by saveOnChange=true): " + ex.getMessage()); } } else { dirty = true; } } } @Override public void removeAttribute(String name) { super.removeAttribute(name); if (this.manager instanceof AbstractSessionManager && ((AbstractSessionManager) this.manager).getSaveOnChange()) { try { ((AbstractSessionManager) this.manager).save(this, true); } catch (IOException ex) { logger.error("Error saving session on setAttribute (triggered by saveOnChange=true): " + ex.getMessage()); } } else { dirty = true; } } @Override public void setId(String id) { this.id = id; } @Override public void setPrincipal(Principal principal) { dirty = true; super.setPrincipal(principal); } @Override public void writeObjectData(java.io.ObjectOutputStream out) throws IOException { super.writeObjectData(out); out.writeLong(this.getCreationTime()); } @Override public void readObjectData(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { super.readObjectData(in); this.setCreationTime(in.readLong()); } }
package com.mixpanel.mixpanelapi; import java.util.Date; import java.util.Iterator; import java.util.Map; import java.util.TimeZone; import java.text.DateFormat; import java.text.SimpleDateFormat; import org.json.JSONException; import org.json.JSONObject; /** * This class writes JSONObjects of a form appropriate to send as Mixpanel events and * updates to people analytics profiles via the MixpanelAPI class. * * Instances of this class can be instantiated separately from instances of MixpanelAPI, * and the resulting messages are suitable for enqueuing or sending over a local network. */ public class MessageBuilder { public MessageBuilder(String token) { mToken = token; } public JSONObject event(String distinctId, String eventName, JSONObject properties) { long time = System.currentTimeMillis() / 1000; // Nothing below should EVER throw a JSONException. try { JSONObject dataObj = new JSONObject(); dataObj.put("event", eventName); JSONObject propertiesObj = null; if (properties == null) { propertiesObj = new JSONObject(); } else { propertiesObj = new JSONObject(properties.toString()); } if (! propertiesObj.has("token")) propertiesObj.put("token", mToken); if (! propertiesObj.has("time")) propertiesObj.put("time", time); if (! propertiesObj.has("mp_lib")) propertiesObj.put("mp_lib", "jdk"); if (distinctId != null) propertiesObj.put("distinct_id", distinctId); dataObj.put("properties", propertiesObj); JSONObject envelope = new JSONObject(); envelope.put("envelope_version", 1); envelope.put("message_type", "event"); envelope.put("message", dataObj); return envelope; } catch (JSONException e) { throw new RuntimeException("Can't construct a Mixpanel message", e); } } /** * Sets a People Analytics property on the profile associated with * the given distinctId. When sent, this message will overwrite any * existing values for the given properties. So, to set some properties * on user 12345, one might call: * <pre> * {@code * JSONObject userProperties = new JSONObject(); * userProperties.put("Company", "Uneeda Medical Supply"); * userProperties.put("Easter Eggs", "Hatched"); * JSONObject message = messageBuilder.set("12345", userProperties); * mixpanelApi.sendMessage(message); * } * </pre> * * @param distinctId a string uniquely identifying the people analytics profile to change, * for example, a user id of an app, or the hostname of a server. If no profile * exists for the given id, a new one will be created. * @param properties a collection of properties to set on the associated profile. Each key * in the properties argument will be updated on on the people profile. */ public JSONObject set(String distinctId, JSONObject properties) { return set(distinctId, properties, null); } /** * Sets a People Analytics property on the profile associated with * the given distinctId. When sent, this message will overwrite any * existing values for the given properties. So, to set some properties * on user 12345, one might call: * <pre> * {@code * JSONObject userProperties = new JSONObject(); * userProperties.put("Company", "Uneeda Medical Supply"); * userProperties.put("Easter Eggs", "Hatched"); * JSONObject message = messageBuilder.set("12345", userProperties); * mixpanelApi.sendMessage(message); * } * </pre> * * @param distinctId a string uniquely identifying the people analytics profile to change, * for example, a user id of an app, or the hostname of a server. If no profile * exists for the given id, a new one will be created. * @param properties a collection of properties to set on the associated profile. Each key * in the properties argument will be updated on on the people profile * @param modifiers Modifiers associated with the update message. (for example "$time" or "$ignore_time"). * this can be null- if non-null, the keys and values in the modifiers * object will be associated directly with the update. */ public JSONObject set(String distinctId, JSONObject properties, JSONObject modifiers) { return stdPeopleMessage(distinctId, "$set", properties, modifiers); } /** * Deletes the People Analytics profile associated with * the given distinctId. * * <pre> * {@code * JSONObject message = messageBuilder.delete("12345"); * mixpanelApi.sendMessage(message); * } * </pre> * * @param distinctId a string uniquely identifying the people analytics profile to delete */ public JSONObject delete(String distinctId) { return stdPeopleMessage(distinctId, "$delete", new JSONObject(), null); } /** * For each key and value in the properties argument, adds that amount * to the associated property in the People Analytics profile with the given distinct id. * So, to maintain a login count for user 12345, one might run the following code * at every login: * <pre> * {@code * Map<String, Long> updates = new HashMap<String, Long>(); * updates.put('Logins', 1); * JSONObject message = messageBuilder.set("12345", updates); * mixpanelApi.sendMessage(message); * } * </pre> * @param distinctId a string uniquely identifying the people analytics profile to change, * for example, a user id of an app, or the hostname of a server. If no profile * exists for the given id, a new one will be created. * @param properties a collection of properties to change on the associated profile, * each associated with a numeric value. */ public JSONObject increment(String distinctId, Map<String, Long> properties) { return increment(distinctId, properties, null); } /** * For each key and value in the properties argument, adds that amount * to the associated property in the People Analytics profile with the given distinct id. * So, to maintain a login count for user 12345, one might run the following code * at every login: * <pre> * {@code * Map<String, Long> updates = new HashMap<String, Long>(); * updates.put('Logins', 1); * JSONObject message = messageBuilder.set("12345", updates); * mixpanelApi.sendMessage(message); * } * </pre> * @param distinctId a string uniquely identifying the people analytics profile to change, * for example, a user id of an app, or the hostname of a server. If no profile * exists for the given id, a new one will be created. * @param properties a collection of properties to change on the associated profile, * each associated with a numeric value. * @param modifiers Modifiers associated with the update message. (for example "$time" or "$ignore_time"). * this can be null- if non-null, the keys and values in the modifiers * object will be associated directly with the update. */ public JSONObject increment(String distinctId, Map<String, Long> properties, JSONObject modifiers) { JSONObject jsonProperties = new JSONObject(properties); return stdPeopleMessage(distinctId, "$add", jsonProperties, modifiers); } /** * For each key and value in the properties argument, attempts to append * that value to a list associated with the key in the identified People Analytics profile. */ public JSONObject append(String distinctId, JSONObject properties) { return append(distinctId, properties, null); } /** * For each key and value in the properties argument, attempts to append * that value to a list associated with the key in the identified People Analytics profile. */ public JSONObject append(String distinctId, JSONObject properties, JSONObject modifiers) { return stdPeopleMessage(distinctId, "$append", properties, modifiers); } /** * Tracks revenue associated with the given distinctId. * * @param distinctId an identifier associated with a People Analytics profile * @param amount a double revenue amount. Positive amounts represent income for your business. * @param properties can be null. If provided, a set of properties to associate with * the individual transaction. */ public JSONObject trackCharge(String distinctId, double amount, JSONObject properties) { return trackCharge(distinctId, amount, properties, null); } /** * Tracks revenue associated with the given distinctId. * * @param distinctId an identifier associated with a People Analytics profile * @param amount a double revenue amount. Positive amounts represent income for your business. * @param properties can be null. If provided, a set of properties to associate with * the individual transaction. * @param modifiers can be null. If provided, the keys and values in the object will * be merged as modifiers associated with the update message (for example, "$time" or "$ignore_time") */ public JSONObject trackCharge(String distinctId, double amount, JSONObject properties, JSONObject modifiers) { JSONObject transactionValue = new JSONObject(); JSONObject appendProperties = new JSONObject(); try { transactionValue.put("$amount", amount); DateFormat dateFormat = new SimpleDateFormat(ENGAGE_DATE_FORMAT); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); transactionValue.put("$time", dateFormat.format(new Date())); if (null != properties) { for (Iterator<?> iter = properties.keys(); iter.hasNext();) { String key = (String) iter.next(); transactionValue.put(key, properties.get(key)); } } appendProperties.put("$transactions", transactionValue); return this.append(distinctId, appendProperties, modifiers); } catch (JSONException e) { e.printStackTrace(); throw new RuntimeException("Cannot create trackCharge message", e); } } private JSONObject stdPeopleMessage(String distinctId, String actionType, JSONObject properties, JSONObject modifiers) { // Nothing below should EVER throw a JSONException. try { JSONObject dataObj = new JSONObject(); dataObj.put(actionType, properties); dataObj.put("$token", mToken); dataObj.put("$distinct_id", distinctId); dataObj.put("$time", System.currentTimeMillis()); if (null != modifiers) { for(String key : JSONObject.getNames(modifiers)) { dataObj.put(key, modifiers.get(key)); } } JSONObject envelope = new JSONObject(); envelope.put("envelope_version", 1); envelope.put("message_type", "people"); envelope.put("message", dataObj); return envelope; } catch (JSONException e) { throw new RuntimeException("Can't construct a Mixpanel message", e); } } private final String mToken; private static final String ENGAGE_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss"; }
package com.mycompany.gitfirsttest; /** * * @author ingimar */ public class FailsToBuild { // nu ska det funka }
package com.rosshambrick.standardlib; import android.os.Bundle; import android.support.v4.app.DialogFragment; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.Toast; import butterknife.ButterKnife; import rx.Observable; import rx.Observer; import rx.Subscription; import rx.android.app.AppObservable; import rx.android.lifecycle.LifecycleEvent; import rx.android.lifecycle.LifecycleObservable; import rx.functions.Action0; import rx.subjects.BehaviorSubject; public abstract class RxFragment extends DialogFragment { private BlockingProgressFragment blockingProgressFragment; private Toolbar toolbar; private boolean traceLog; private final BehaviorSubject<LifecycleEvent> lifecycleSubject = BehaviorSubject.create(); private Observable<LifecycleEvent> lifecycle() { return lifecycleSubject.asObservable(); } abstract protected boolean isDebug(); protected void enableTraceLog(boolean enable) { traceLog = enable; } @Override public void onAttach(android.app.Activity activity) { if (traceLog) Log.d("TRACE", "--> RxFragment.onAttach()"); super.onAttach(activity); lifecycleSubject.onNext(LifecycleEvent.ATTACH); } @Override public void onCreate(Bundle savedInstanceState) { if (traceLog) Log.d("TRACE", "--> RxFragment.onCreate()"); super.onCreate(savedInstanceState); lifecycleSubject.onNext(LifecycleEvent.CREATE); } @Override public void onActivityCreated(Bundle savedInstanceState) { if (traceLog) Log.d("TRACE", "--> RxFragment.onActivityCreated()"); super.onActivityCreated(savedInstanceState); toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { if (traceLog) Log.d("TRACE", "--> RxFragment.onViewCreated()"); super.onViewCreated(view, savedInstanceState); ButterKnife.inject(this, view); lifecycleSubject.onNext(LifecycleEvent.CREATE_VIEW); } @Override public void onStart() { if (traceLog) Log.d("TRACE", "--> RxFragment.onStart()"); super.onStart(); lifecycleSubject.onNext(LifecycleEvent.START); } @Override public void onResume() { if (traceLog) Log.d("TRACE", "--> RxFragment.onResume()"); super.onResume(); lifecycleSubject.onNext(LifecycleEvent.RESUME); } @Override public void onPause() { if (traceLog) Log.d("TRACE", "--> RxFragment.onPause()"); lifecycleSubject.onNext(LifecycleEvent.PAUSE); super.onPause(); } @Override public void onStop() { if (traceLog) Log.d("TRACE", "--> RxFragment.onStop()"); lifecycleSubject.onNext(LifecycleEvent.STOP); super.onStop(); } @Override public void onDestroyView() { if (traceLog) Log.d("TRACE", "--> RxFragment.onDestroyView()"); lifecycleSubject.onNext(LifecycleEvent.DESTROY_VIEW); super.onDestroyView(); } @Override public void onDetach() { if (traceLog) Log.d("TRACE", "--> RxFragment.onDetach()"); lifecycleSubject.onNext(LifecycleEvent.DETACH); super.onDetach(); } @Override public void onDestroy() { if (traceLog) Log.d("TRACE", "--> RxFragment.onDetach()"); lifecycleSubject.onNext(LifecycleEvent.DESTROY); super.onDestroy(); } protected void showBlockingProgress() { showBlockingProgress(null); } protected void showBlockingProgress(Subscription subscription) { blockingProgressFragment = BlockingProgressFragment.newInstance(); blockingProgressFragment.show(getFragmentManager(), BlockingProgressFragment.TAG); blockingProgressFragment.setOnCancelListener(subscription); } public void handleError(Throwable e) { handleError(null, e); } protected void handleError(String message, Throwable e) { Log.e(getClass().getSimpleName(), e.getLocalizedMessage(), e); if (isDebug() || message != null) { Toast.makeText(getActivity(), message == null ? e.getLocalizedMessage() : message, Toast.LENGTH_LONG).show(); } } protected void dismissBlockingProgress() { if (blockingProgressFragment != null) { blockingProgressFragment.dismiss(); blockingProgressFragment = null; } } public Toolbar getToolbar() { if (toolbar == null) { throw new RuntimeException("Toolbar has not been set. Make sure not to call getToolbar() until onViewCreated() at the earliest."); } return toolbar; } protected <T> Subscription blockingSubscribe(Observable<T> observable, final Observer<T> observer) { Subscription subscription = bind(observable) .doOnTerminate(new Action0() { @Override public void call() { dismissBlockingProgress(); } }) .subscribe(observer); showBlockingProgress(subscription); return subscription; } protected <T> Subscription subscribe(Observable<T> observable, Observer<T> observer) { Observable<T> boundObservable = bind(observable); return boundObservable.subscribe(observer); } protected <T> Observable<T> bind(Observable<T> observable) { Observable<T> boundObservable = AppObservable.bindFragment(this, observable); return LifecycleObservable.bindFragmentLifecycle(lifecycle(), boundObservable); } protected void toast(int messageId) { Toast.makeText(getActivity(), messageId, Toast.LENGTH_SHORT).show(); } protected void toast(String message) { Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show(); } protected int getColor(int colorRes) { return getResources().getColor(colorRes); } protected int getDimensionPixelOffset(int dpResource) { return getResources().getDimensionPixelOffset(dpResource); } protected void debugToast(int messageResId) { if (isDebug()) { Toast.makeText(getActivity(), messageResId, Toast.LENGTH_SHORT).show(); } } public void onCompleted() { //nothing by default } public void onError(Throwable e) { handleError(e); } }
package com.ryanberg.alfresco.s3; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.regions.Region; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.transfer.TransferManager; import org.alfresco.repo.content.AbstractContentStore; import org.alfresco.repo.content.ContentStore; import org.alfresco.repo.content.ContentStoreCreatedEvent; import org.alfresco.repo.content.UnsupportedContentUrlException; import org.alfresco.repo.content.filestore.FileContentStore; import org.alfresco.service.cmr.repository.ContentReader; import org.alfresco.service.cmr.repository.ContentWriter; import org.alfresco.util.GUID; import org.alfresco.util.Pair; import org.apache.commons.lang3.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import java.io.Serializable; import java.util.Calendar; import java.util.Collections; import java.util.GregorianCalendar; import java.util.Map; public class S3ContentStore extends AbstractContentStore implements ApplicationContextAware, ApplicationListener<ApplicationEvent> { private static final Log logger = LogFactory.getLog(S3ContentStore.class); private ApplicationContext applicationContext; private AmazonS3 s3Client; private TransferManager transferManager; private String accessKey; private String secretKey; private String bucketName; private String regionName; private String rootDirectory; @Override public boolean isWriteSupported() { return true; } @Override public ContentReader getReader(String contentUrl) { String key = makeS3Key(contentUrl); return new S3ContentReader(key, contentUrl, s3Client, bucketName); } public void init() { AWSCredentials credentials = null; if(StringUtils.isNotBlank(this.accessKey) && StringUtils.isNotBlank(this.secretKey)) { logger.debug("Found credentials in properties file"); credentials = new BasicAWSCredentials(this.accessKey, this.secretKey); } else { try { logger.debug("AWS Credentials not specified in properties, will fallback to credentials provider"); credentials = new ProfileCredentialsProvider().getCredentials(); } catch (Exception e) { logger.error("Can not find AWS Credentials"); } } s3Client = new AmazonS3Client(credentials); Region region = Region.getRegion(Regions.fromName(this.regionName)); s3Client.setRegion(region); transferManager = new TransferManager(s3Client); } public void setAccessKey(String accessKey) { this.accessKey = accessKey; } public void setSecretKey(String secretKey) { this.secretKey = secretKey; } public void setBucketName(String bucketName) { this.bucketName = bucketName; } public void setRegionName(String regionName) { this.regionName = regionName; } public void setRootDirectory(String rootDirectory) { String dir = rootDirectory; if (dir.startsWith("/")) { dir = dir.substring(1); } this.rootDirectory = dir; } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override protected ContentWriter getWriterInternal(ContentReader existingContentReader, String newContentUrl) { String contentUrl = newContentUrl; if(StringUtils.isBlank(contentUrl)) { contentUrl = createNewUrl(); } String key = makeS3Key(contentUrl); return new S3ContentWriter(bucketName, key, contentUrl, existingContentReader, s3Client, transferManager); } public static String createNewUrl() { Calendar calendar = new GregorianCalendar(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; // 0-based int day = calendar.get(Calendar.DAY_OF_MONTH); int hour = calendar.get(Calendar.HOUR_OF_DAY); int minute = calendar.get(Calendar.MINUTE); // create the URL StringBuilder sb = new StringBuilder(20); sb.append(FileContentStore.STORE_PROTOCOL) .append(ContentStore.PROTOCOL_DELIMITER) .append(year).append('/') .append(month).append('/') .append(day).append('/') .append(hour).append('/') .append(minute).append('/') .append(GUID.generate()).append(".bin"); String newContentUrl = sb.toString(); // done return newContentUrl; } private String makeS3Key(String contentUrl) { // take just the part after the protocol Pair<String, String> urlParts = super.getContentUrlParts(contentUrl); String protocol = urlParts.getFirst(); String relativePath = urlParts.getSecond(); // Check the protocol if (!protocol.equals(FileContentStore.STORE_PROTOCOL)) { throw new UnsupportedContentUrlException(this, protocol + PROTOCOL_DELIMITER + relativePath); } return rootDirectory + "/" + relativePath; } @Override public boolean delete(String contentUrl) { try { String key = makeS3Key(contentUrl); logger.debug("Deleting object from S3 with url: " + contentUrl + ", key: " + key); s3Client.deleteObject(bucketName, key); return true; } catch (Exception e) { logger.error("Error deleting S3 Object", e); } return false; } /** * Publishes an event to the application context that will notify any interested parties of the existence of this * content store. * * @param context * the application context * @param extendedEventParams */ private void publishEvent(ApplicationContext context, Map<String, Serializable> extendedEventParams) { context.publishEvent(new ContentStoreCreatedEvent(this, extendedEventParams)); } public void onApplicationEvent(ApplicationEvent event) { // Once the context has been refreshed, we tell other interested beans about the existence of this content store // (e.g. for monitoring purposes) if (event instanceof ContextRefreshedEvent && event.getSource() == this.applicationContext) { publishEvent(((ContextRefreshedEvent) event).getApplicationContext(), Collections.<String, Serializable> emptyMap()); } } }
package com.taskadapter.redmineapi.bean; import java.io.Serializable; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Redmine's Project. */ public class Project implements Identifiable, Serializable { private static final long serialVersionUID = 4529305420978716446L; /** * database ID */ private Integer id; /** * String "identifier" (human-readable name without spaces and other extra stuff) */ private String identifier; /** * Can contain any symbols */ private String name; private String description; private String homepage; private Date createdOn; private Date updatedOn; /** * Trackers available for this project */ private List<Tracker> trackers; /** * This is the *database ID*, not a String-based key. */ private Integer parentId; private Boolean projectPublic; private List<CustomField> customFields = new ArrayList<CustomField>(); public String getHomepage() { return homepage; } public void setHomepage(String homepage) { this.homepage = homepage; } /** * @return project's string "key" (not a numeric database id!). Example: "project_ABC" */ public String getIdentifier() { return identifier; } public void setIdentifier(String identifier) { this.identifier = identifier; } @Override /** * @return numeric database ID */ public Integer getId() { return id; } /** * @param id numeric database ID */ public void setId(Integer id) { this.id = id; } /** * @return project name */ public String getName() { return name; } /** * @param name the project name */ public void setName(String name) { this.name = name; } /** * @return list of Trackers allowed in this project (e.g.: Bug, Feature, Support, Task, ...) */ public List<Tracker> getTrackers() { return trackers; } public void setTrackers(List<Tracker> trackers) { this.trackers = trackers; } public Tracker getTrackerByName(String trackerName) { if (this.trackers == null) return null; for (Tracker t : this.trackers) { if (t.getName().equals(trackerName)) return t; } return null; } @Override public String toString() { return name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Date getCreatedOn() { return createdOn; } public void setCreatedOn(Date createdOn) { this.createdOn = createdOn; } public Date getUpdatedOn() { return updatedOn; } public void setUpdatedOn(Date updatedOn) { this.updatedOn = updatedOn; } public Integer getParentId() { return parentId; } public void setParentId(Integer parentId) { this.parentId = parentId; } @Deprecated public Boolean getProjectPublic() { return projectPublic; } public void setProjectPublic(Boolean projectPublic) { this.projectPublic = projectPublic; } public List<CustomField> getCustomFields() { return customFields; } public void setCustomFields(List<CustomField> customFields) { this.customFields = customFields; } public CustomField getCustomFieldById(int customFieldId) { for (CustomField customField : customFields) { if (customFieldId == customField.getId()) { return customField; } } return null; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Project project = (Project) o; if (id != null ? !id.equals(project.id) : project.id != null) return false; return true; } @Override public int hashCode() { return id != null ? id.hashCode() : 0; } }
package com.whitein.threadpool; import com.sun.deploy.net.HttpRequest; import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream; import org.junit.BeforeClass; import org.junit.Test; import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class SimpleHttpServer { //http static ThreadPool<HttpRequestHandler> threadPool = new DefaultThreadPool<HttpRequestHandler>(5); static String basePath; private static ServerSocket serverSocket; static int port = 8080; public static void setPort( int port ){ if( port>0 ){ SimpleHttpServer.port = port; } } public static void setBasePath( String basePath ){ if( basePath!=null && !"".equals(basePath) && new File(basePath).exists() && new File(basePath).isDirectory()){ SimpleHttpServer.basePath = basePath; } } public static void start() throws Exception { serverSocket = new ServerSocket(port); SimpleHttpServer.setBasePath("C:\\Users\\CR\\Desktop"); System.out.println("server start listening..."); Socket socket = null; while( (socket = serverSocket.accept()) != null ){ threadPool.execute(new HttpRequestHandler(socket)); } serverSocket.close(); } static class HttpRequestHandler implements Runnable { private Socket socket; HttpRequestHandler( Socket socket ){ this.socket = socket; } public void run() { //request BufferedReader in = null; //response PrintWriter out = null; InputStream fileIn = null; BufferedReader fileInn = null; try { in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String header = in.readLine(); String path = basePath.concat(header.split(" ")[1].replace("/","\\")); out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream())); if( path.endsWith("jpg") || path.endsWith("ico")){ fileIn = new FileInputStream(path); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int i = 0; while((i = fileIn.read()) != -1){ baos.write(i); } byte[] bytes = baos.toByteArray(); out.println("HTTP/1.1 200 OK"); out.println("Server: Molly"); out.println("Content-Type: image/jpeg"); out.println("Content-Length: " + bytes.length); out.println(""); socket.getOutputStream().write(bytes, 0, bytes.length); }else{ fileInn = new BufferedReader(new FileReader(path)); out.println("HTTP/1.1 200 OK"); out.println("Server: Molly"); out.println("Content-Type: text/html; charset=UTF-8"); out.println(""); String line; while( (line = fileInn.readLine()) != null ){ out.print(line); } } out.flush(); } catch (IOException e) { e.printStackTrace(); out.println("HTTP/1.1 500"); out.println(""); out.flush(); } finally { HttpRequestHandler.close(in, out, fileIn, fileInn); } } private static void close( Closeable... closeables ){ if( closeables != null ){ for( Closeable closeable: closeables ){ if( closeable!=null ){ try { closeable.close(); } catch (IOException e) { e.printStackTrace(); } } } } } } @Test public void testServer() throws Exception { SimpleHttpServer.start(); } }
package com.wrapper.spotify.model_objects; import com.google.gson.Gson; import com.google.gson.JsonNull; import com.google.gson.JsonObject; import com.neovisionaries.i18n.CountryCode; /** * Retrieve information about tracks by building instances from this class. */ public class Track extends AbstractModelObject { private final AlbumSimplified album; private final ArtistSimplified[] artists; private final CountryCode[] availableMarkets; private final int discNumber; private final int durationMs; private final boolean explicit; private final ExternalIds externalIds; private final ExternalUrls externalUrls; private final String href; private final String id; private final boolean isPlayable; private final TrackLink linkedFrom; private final Restrictions restrictions; private final String name; private final int popularity; private final String previewUrl; private final int trackNumber; private final ModelObjectType type; private final String uri; private Track(final Track.Builder builder) { super(builder); this.album = builder.album; this.artists = builder.artists; this.availableMarkets = builder.availableMarkets; this.discNumber = builder.discNumber; this.durationMs = builder.durationMs; this.explicit = builder.explicit; this.externalIds = builder.externalIds; this.externalUrls = builder.externalUrls; this.href = builder.href; this.id = builder.id; this.isPlayable = builder.isPlayable; this.linkedFrom = builder.linkedFrom; this.restrictions = builder.restrictions; this.name = builder.name; this.popularity = builder.popularity; this.previewUrl = builder.previewUrl; this.trackNumber = builder.trackNumber; this.type = builder.type; this.uri = builder.uri; } /** * Get the album of a track. * * @return A simplified album. */ public AlbumSimplified getAlbum() { return album; } /** * Get the artists of a track. * * @return An array of simplified artists. */ public ArtistSimplified[] getArtists() { return artists; } /** * Get the country codes of all countries, in which a track is available. * * @return An array of ISO 3166-1 alpha-2 country codes. */ public CountryCode[] getAvailableMarkets() { return availableMarkets; } /** * Get the disc number of a track in it's album. * * @return A disc number. */ public int getDiscNumber() { return discNumber; } /** * Get the duration of a track in milliseconds. * * @return Duration of track in milliseconds. */ public int getDurationMs() { return durationMs; } /** * Check whether a track is explicit or not. * * @return Returns "true" for explicit, "false" for not explicit. */ public boolean getIsExplicit() { return explicit; } /** * Get the external ids of a track.<br> * Example: isrc -&gt; "International Standard Recording Code". * * @return All external ids of the track. */ public ExternalIds getExternalIds() { return externalIds; } /** * Get the external urls of a track.<br> * Example: Spotify-URL. * * @return The external urls of the track. */ public ExternalUrls getExternalUrls() { return externalUrls; } /** * Get the full Spotify API endpoint url of a track. * * @return A Spotify API endpoint url. */ public String getHref() { return href; } /** * Get the Spotify id of a track. * * @return A Spotify track id. */ public String getId() { return id; } /** * Check whether a track is playable in the market, which may has been specified * somewhere before requesting it. * * @return Return "true" if the track is playable in specified market, "false" if not. */ public boolean getIsPlayable() { return isPlayable; } /** * Get the track link of a track if the given track has been relinked.<br> * This happens mostly when a specific track is not available in a specific market. * * @return The original Spotify url of the track. */ public TrackLink getLinkedFrom() { return linkedFrom; } /** * Get the restrictions of a track.<br> * Example: The reason why a track may not be available. * * @return The restrictions of the track. */ public Restrictions getRestrictions() { return restrictions; } /** * Get the name of a track. * * @return Track name. */ public String getName() { return name; } /** * Get the popularity of a track in a range between 0 and 100. (higher = more popular)<br> * The popularity of a track is based on how often a track has been played recently. * * @return The popularity of the track. */ public int getPopularity() { return popularity; } /** * Get an url to a 30 seconds long track preview in MP3 format.<br> * If there is no track preview available, null will be returned. * * @return A track preview url if available, null if not available. */ public String getPreviewUrl() { return previewUrl; } /** * Get the track number of a track. * * @return A track number. */ public int getTrackNumber() { return trackNumber; } /** * Get the model object type, which should be a "track" in this case. * * @return A model object type. */ public ModelObjectType getType() { return type; } /** * Get a Spotify track uri. * * @return A Spotify track uri. */ public String getUri() { return uri; } @Override public Builder builder() { return new Builder(); } /** * Builder class for building track instances. */ public static final class Builder extends AbstractModelObject.Builder { private AlbumSimplified album; private ArtistSimplified[] artists; private CountryCode[] availableMarkets; private int discNumber; private int durationMs; private boolean explicit; private ExternalIds externalIds; private ExternalUrls externalUrls; private String href; private String id; private boolean isPlayable; private TrackLink linkedFrom; private Restrictions restrictions; private String name; private int popularity; private String previewUrl; private int trackNumber; private ModelObjectType type; private String uri; public Builder setAlbum(AlbumSimplified album) { this.album = album; return this; } public Builder setArtists(ArtistSimplified[] artists) { this.artists = artists; return this; } public Builder setAvailableMarkets(CountryCode[] availableMarkets) { this.availableMarkets = availableMarkets; return this; } public Builder setDiscNumber(int discNumber) { this.discNumber = discNumber; return this; } public Builder setDurationMs(int durationMs) { this.durationMs = durationMs; return this; } public Builder setExplicit(boolean explicit) { this.explicit = explicit; return this; } public Builder setExternalIds(ExternalIds externalIds) { this.externalIds = externalIds; return this; } public Builder setExternalUrls(ExternalUrls externalUrls) { this.externalUrls = externalUrls; return this; } public Builder setHref(String href) { this.href = href; return this; } public Builder setId(String id) { this.id = id; return this; } public Builder setIsPlayable(boolean isPlayable) { this.isPlayable = isPlayable; return this; } public Builder setLinkedFrom(TrackLink linkedFrom) { this.linkedFrom = linkedFrom; return this; } public Builder setRestrictions(Restrictions restrictions) { this.restrictions = restrictions; return this; } public Builder setName(String name) { this.name = name; return this; } public Builder setPopularity(int popularity) { this.popularity = popularity; return this; } public Builder setPreviewUrl(String previewUrl) { this.previewUrl = previewUrl; return this; } public Builder setTrackNumber(int trackNumber) { this.trackNumber = trackNumber; return this; } public Builder setType(ModelObjectType type) { this.type = type; return this; } public Builder setUri(String uri) { this.uri = uri; return this; } @Override public Track build() { return new Track(this); } } public static final class JsonUtil extends AbstractModelObject.JsonUtil<Track> { public Track createModelObject(JsonObject jsonObject) { if (jsonObject == null || jsonObject.isJsonNull()) { return null; } if (jsonObject.has("available_markets")) { return new Track.Builder() .setAlbum(new AlbumSimplified.JsonUtil().createModelObject(jsonObject.getAsJsonObject("album"))) .setArtists(new ArtistSimplified.JsonUtil().createModelObjectArray(jsonObject.getAsJsonArray("artists"))) .setAvailableMarkets(new Gson().fromJson(jsonObject.getAsJsonArray("available_markets"), CountryCode[].class)) .setDiscNumber(jsonObject.get("disc_number").getAsInt()) .setDurationMs(jsonObject.get("duration_ms").getAsInt()) .setExplicit(jsonObject.get("explicit").getAsBoolean()) .setExternalIds(new ExternalIds.JsonUtil().createModelObject(jsonObject.getAsJsonObject("external_ids"))) .setExternalUrls(new ExternalUrls.JsonUtil().createModelObject(jsonObject.getAsJsonObject("external_urls"))) .setHref((jsonObject.get("href") instanceof JsonNull) ? null : jsonObject.get("href").getAsString()) .setId((jsonObject.get("id") instanceof JsonNull) ? null : jsonObject.get("id").getAsString()) .setName(jsonObject.get("name").getAsString()) .setPopularity(jsonObject.get("popularity").getAsInt()) .setPreviewUrl((jsonObject.get("preview_url") instanceof JsonNull) ? null : jsonObject.get("preview_url").getAsString()) .setTrackNumber(jsonObject.get("track_number").getAsInt()) .setType(ModelObjectType.valueOf(jsonObject.get("type").getAsString().toUpperCase())) .setUri(jsonObject.get("uri").getAsString()) .build(); } else if (jsonObject.has("is_playable")) { return new Track.Builder() .setAlbum(new AlbumSimplified.JsonUtil().createModelObject(jsonObject.getAsJsonObject("album"))) .setArtists(new ArtistSimplified.JsonUtil().createModelObjectArray(jsonObject.getAsJsonArray("artists"))) .setDiscNumber(jsonObject.get("disc_number").getAsInt()) .setDurationMs(jsonObject.get("duration_ms").getAsInt()) .setExplicit(jsonObject.get("explicit").getAsBoolean()) .setExternalIds(new ExternalIds.JsonUtil().createModelObject(jsonObject.getAsJsonObject("external_ids"))) .setExternalUrls(new ExternalUrls.JsonUtil().createModelObject(jsonObject.getAsJsonObject("external_urls"))) .setHref(jsonObject.get("href").getAsString()) .setId(jsonObject.get("id").getAsString()) .setIsPlayable(jsonObject.get("is_playable").getAsBoolean()) .setLinkedFrom(new TrackLink.JsonUtil().createModelObject(jsonObject.get("linked_from").getAsJsonObject())) .setRestrictions(new Restrictions.JsonUtil().createModelObject(jsonObject.get("restrictions").getAsJsonObject())) .setName(jsonObject.get("name").getAsString()) .setPopularity(jsonObject.get("popularity").getAsInt()) .setPreviewUrl((jsonObject.get("preview_url") instanceof JsonNull) ? null : jsonObject.get("preview_url").getAsString()) .setTrackNumber(jsonObject.get("track_number").getAsInt()) .setType(ModelObjectType.valueOf(jsonObject.get("type").getAsString().toUpperCase())) .setUri(jsonObject.get("uri").getAsString()) .build(); } else { return null; } } } }
package com.xjeffrose.xio.SSL; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SupportedCipherSuiteFilter; import java.io.IOException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.*; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.SSLException; import javax.net.ssl.TrustManagerFactory; public class SslContextFactory { static private SslContextBuilder configure(TlsConfig config, SslContextBuilder builder) { return builder .applicationProtocolConfig(config.getAlpnConfig()) .ciphers(config.getCiphers(), SupportedCipherSuiteFilter.INSTANCE) .clientAuth(config.getClientAuth()) .enableOcsp(config.isEnableOcsp()) .protocols(config.getProtocols()) .sessionCacheSize(config.getSessionCacheSize()) .sessionTimeout(config.getSessionTimeout()) .sslProvider(config.getSslProvider()) ; } static public SslContext buildServerContext(TlsConfig config) { try { SslContextBuilder builder = SslContextBuilder .forServer(config.getPrivateKey(), config.getCertificateAndTrustChain()); return configure(config, builder) // servers will trust only certs in trust chain .trustManager(config.getTrustChain()) .build(); } catch (SSLException e) { return null; } } static public SslContext buildClientContext(TlsConfig config, TrustManagerFactory trustManager) { try { return configure(config, SslContextBuilder.forClient()) .keyManager(config.getPrivateKey(), config.getCertificateAndTrustChain()) // clients will trust only certs in trust chain .trustManager(trustManager) .build(); } catch (SSLException e) { return null; } } static TrustManagerFactory buildTrustManagerFactory(X509Certificate[] certCollection) { try { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, null); int i = 1; for (X509Certificate cert: certCollection) { String alias = Integer.toString(i); ks.setCertificateEntry(alias, cert); i++; } TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(ks); return trustManagerFactory; } catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | IOException e) { return null; } } static public SslContext buildClientContext(TlsConfig config) { return buildClientContext(config, buildTrustManagerFactory(config.getTrustChain())); } }
package de.cronn.jira.sync.domain; import java.io.Serializable; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnore; public class JiraChangeLog implements Serializable { private static final long serialVersionUID = 1L; private int total; private List<JiraIssueHistoryEntry> history; public JiraChangeLog() { this.history = new ArrayList<>(); } public JiraChangeLog(List<JiraIssueHistoryEntry> history) { this.history = history; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public List<JiraIssueHistoryEntry> getHistory() { return history; } public void setHistory(List<JiraIssueHistoryEntry> history) { this.history = history; } @JsonIgnore public JiraChangeLog addHistoryEntry(JiraIssueHistoryEntry historyEntry) { getHistory().add(historyEntry); return this; } @JsonIgnore public JiraIssueHistoryEntry getLatestStatusTransition() { return history.stream() .filter(historyEntry -> historyEntry.hasItemWithField(WellKnownJiraField.STATUS)) .max(Comparator.comparing(JiraIssueHistoryEntry::getCreated)) .orElse(null); } }
package de.otto.jlineup.report; import de.otto.jlineup.Util; import de.otto.jlineup.file.FileService; import org.thymeleaf.TemplateEngine; import org.thymeleaf.context.Context; import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; import java.io.FileNotFoundException; import java.util.*; public class HTMLReportWriter { private FileService fileService; public HTMLReportWriter(FileService fileService) { this.fileService = fileService; } public void writeReport(Report report) throws FileNotFoundException { fileService.writeHtmlReport(renderReport("report", report.getFlatResultList())); } String renderReport(String template, List<ScreenshotComparisonResult> screenshotComparisonResults) throws FileNotFoundException { ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); templateResolver.setTemplateMode("HTML"); templateResolver.setPrefix("templates/"); templateResolver.setSuffix(".html"); TemplateEngine templateEngine = new TemplateEngine(); templateEngine.setTemplateResolver(templateResolver); final Map<String, Object> variables = prepareVariablesForReportTemplate(screenshotComparisonResults); return templateEngine.process(template, new Context(Locale.US, variables)); } private Map<String, Object> prepareVariablesForReportTemplate(final List<ScreenshotComparisonResult> screenshotComparisonResults) { Map<String, Object> variables = new HashMap<>(); List<ScreenshotComparisonResultContext> screenshotComparisonResultContexts = new LinkedList<>(); String lastContextKey = null; ScreenshotComparisonResultContext currentContext = null; for (ScreenshotComparisonResult screenshotComparisonResult : screenshotComparisonResults) { String context = getContextKey(screenshotComparisonResult); if (!context.equals(lastContextKey)) { lastContextKey = context; currentContext = new ScreenshotComparisonResultContext(screenshotComparisonResult.url, screenshotComparisonResult.width); screenshotComparisonResultContexts.add(currentContext); } currentContext.addResult(screenshotComparisonResult); } variables.put("resultContexts", screenshotComparisonResultContexts); variables.put("jlineup_version", Util.readVersion()); variables.put("jlineup_commit", Util.readCommit()); return variables; } private String getContextKey(final ScreenshotComparisonResult screenshotComparisonResult) { return screenshotComparisonResult.url + "|||" + screenshotComparisonResult.width; } private class ScreenshotComparisonResultContext { private final String url; private final int width; private final List<ScreenshotComparisonResult> results; ScreenshotComparisonResultContext(final String url, final int width) { this.url = url; this.width = width; this.results = new LinkedList<>(); } void addResult(ScreenshotComparisonResult result) { results.add(result); } public String getUrl() { return url; } @UsedInTemplate public int getWidth() { return width; } @UsedInTemplate public List<ScreenshotComparisonResult> getResults() { return results; } @UsedInTemplate public String getShortenedUrl() { String shortenedUrl = url; if (url.length() > 25) { shortenedUrl = "..." + shortenedUrl.substring(shortenedUrl.lastIndexOf("/"), shortenedUrl.length()); } return shortenedUrl; } @UsedInTemplate public boolean isSuccess() { for(ScreenshotComparisonResult result : results) { if(result.difference > 0) return false; } return true; } } }
package eu.openanalytics.services; import java.io.FileInputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.Random; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.IntPredicate; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import org.apache.commons.codec.binary.Hex; import org.apache.log4j.Logger; import org.springframework.context.annotation.Bean; import org.springframework.core.env.Environment; import org.springframework.stereotype.Service; import org.springframework.web.util.WebUtils; import com.spotify.docker.client.DefaultDockerClient; import com.spotify.docker.client.DockerCertificates; import com.spotify.docker.client.DockerClient; import com.spotify.docker.client.DockerClient.LogsParam; import com.spotify.docker.client.DockerClient.RemoveContainerParam; import com.spotify.docker.client.LogStream; import com.spotify.docker.client.exceptions.DockerCertificateException; import com.spotify.docker.client.exceptions.DockerException; import com.spotify.docker.client.messages.ContainerConfig; import com.spotify.docker.client.messages.ContainerCreation; import com.spotify.docker.client.messages.ContainerInfo; import com.spotify.docker.client.messages.HostConfig; import com.spotify.docker.client.messages.HostConfig.Builder; import com.spotify.docker.client.messages.PortBinding; import com.spotify.docker.client.messages.mount.Mount; import com.spotify.docker.client.messages.swarm.ContainerSpec; import com.spotify.docker.client.messages.swarm.DnsConfig; import com.spotify.docker.client.messages.swarm.EndpointSpec; import com.spotify.docker.client.messages.swarm.NetworkAttachmentConfig; import com.spotify.docker.client.messages.swarm.Node; import com.spotify.docker.client.messages.swarm.PortConfig; import com.spotify.docker.client.messages.swarm.ServiceSpec; import com.spotify.docker.client.messages.swarm.Task; import com.spotify.docker.client.messages.swarm.TaskSpec; import eu.openanalytics.ShinyProxyException; import eu.openanalytics.services.AppService.ShinyApp; import eu.openanalytics.services.EventService.EventType; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.Cookie; import io.undertow.servlet.handlers.ServletRequestContext; @Service public class DockerService { private Logger log = Logger.getLogger(DockerService.class); private Random rng = new Random(); private List<Proxy> launchingProxies = Collections.synchronizedList(new ArrayList<>()); private List<Proxy> activeProxies = Collections.synchronizedList(new ArrayList<>()); private List<MappingListener> mappingListeners = Collections.synchronizedList(new ArrayList<>()); private Set<Integer> occupiedPorts = Collections.synchronizedSet(new HashSet<>()); private ExecutorService containerKiller = Executors.newSingleThreadExecutor(); private boolean swarmMode = false; @Inject Environment environment; @Inject AppService appService; @Inject UserService userService; @Inject EventService eventService; @Inject LogService logService; @Inject DockerClient dockerClient; public static class Proxy { public String name; public String protocol; public String host; public int port; public String containerId; public String serviceId; public String userName; public String appName; public Set<String> sessionIds = new HashSet<>(); public long startupTimestamp; public Long lastHeartbeatTimestamp; public String uptime() { long uptimeSec = (System.currentTimeMillis() - startupTimestamp)/1000; return String.format("%d:%02d:%02d", uptimeSec/3600, (uptimeSec%3600)/60, uptimeSec%60); } public Proxy copyInto(Proxy target) { target.name = this.name; target.protocol = this.protocol; target.host = this.host; target.port = this.port; target.containerId = this.containerId; target.serviceId = this.serviceId; target.userName = this.userName; target.appName = this.appName; target.sessionIds = this.sessionIds; target.startupTimestamp = this.startupTimestamp; return target; } } @PostConstruct public void init() { try { swarmMode = (dockerClient.inspectSwarm().id() != null); } catch (DockerException | InterruptedException e) {} log.info(String.format("Swarm mode is %s", (swarmMode ? "enabled" : "disabled"))); Thread heartbeatThread = new Thread(new AppCleaner(), "HeartbeatThread"); heartbeatThread.setDaemon(true); heartbeatThread.start(); } @PreDestroy public void shutdown() { containerKiller.shutdown(); List<Proxy> proxiesToRelease = new ArrayList<>(); synchronized (activeProxies) { proxiesToRelease.addAll(activeProxies); } for (Proxy proxy: proxiesToRelease) releaseProxy(proxy, false); } @Bean public DockerClient getDockerClient() { try { DefaultDockerClient.Builder builder = DefaultDockerClient.fromEnv(); String confCertPath = environment.getProperty("shiny.proxy.docker.cert-path"); if (confCertPath != null) { builder.dockerCertificates(DockerCertificates.builder().dockerCertPath(Paths.get(confCertPath)).build().orNull()); } String confUrl = environment.getProperty("shiny.proxy.docker.url"); if (confUrl != null) { builder.uri(confUrl); } return builder.build(); } catch (DockerCertificateException e) { throw new ShinyProxyException("Failed to initialize docker client", e); } } public List<Proxy> listProxies() { synchronized (activeProxies) { return activeProxies.stream().map(p -> p.copyInto(new Proxy())).collect(Collectors.toList()); } } public String getMapping(HttpServletRequest request, String userName, String appName, boolean startNew) { waitForLaunchingProxy(userName, appName); Proxy proxy = findProxy(userName, appName); if (proxy == null && startNew) { // The user has no proxy yet. proxy = startProxy(userName, appName); } if (proxy == null) { return null; } else { proxy.sessionIds.add(getCurrentSessionId(request)); return proxy.name; } } public boolean sessionOwnsProxy(HttpServerExchange exchange) { String sessionId = getCurrentSessionId(exchange); if (sessionId == null) return false; String proxyName = exchange.getRelativePath(); synchronized (activeProxies) { for (Proxy p: activeProxies) { if (p.sessionIds.contains(sessionId) && proxyName.startsWith("/" + p.name)) { return true; } } } synchronized (launchingProxies) { for (Proxy p: launchingProxies) { if (p.sessionIds.contains(sessionId) && proxyName.startsWith("/" + p.name)) { return true; } } } return false; } public List<Proxy> releaseProxies(String userName) { List<Proxy> proxiesToRelease = new ArrayList<>(); synchronized (activeProxies) { for (Proxy proxy: activeProxies) { if (userName.equals(proxy.userName)) proxiesToRelease.add(proxy); } } for (Proxy proxy: proxiesToRelease) { releaseProxy(proxy, true); } return proxiesToRelease; } public void releaseProxy(String userName, String appName) { Proxy proxy = findProxy(userName, appName); if (proxy != null) { releaseProxy(proxy, true); } } private String getCurrentSessionId(HttpServerExchange exchange) { if (exchange == null && ServletRequestContext.current() != null) { exchange = ServletRequestContext.current().getExchange(); } if (exchange == null) return null; Cookie sessionCookie = exchange.getRequestCookies().get("JSESSIONID"); if (sessionCookie == null) return null; return sessionCookie.getValue(); } private String getCurrentSessionId(HttpServletRequest request) { if (request == null) { return getCurrentSessionId((HttpServerExchange) null); } javax.servlet.http.Cookie sessionCookie = WebUtils.getCookie(request, "JSESSIONID"); if (sessionCookie == null) return null; return sessionCookie.getValue(); } private void releaseProxy(Proxy proxy, boolean async) { activeProxies.remove(proxy); Runnable releaser = () -> { try { if (swarmMode) { dockerClient.removeService(proxy.serviceId); } else { ShinyApp app = appService.getApp(proxy.appName); if (app != null && app.getDockerNetworkConnections() != null) { for (String networkConnection: app.getDockerNetworkConnections()) { dockerClient.disconnectFromNetwork(proxy.containerId, networkConnection); } } dockerClient.removeContainer(proxy.containerId, RemoveContainerParam.forceKill()); } releasePort(proxy.port); log.info(String.format("Proxy released [user: %s] [app: %s] [port: %d]", proxy.userName, proxy.appName, proxy.port)); eventService.post(EventType.AppStop.toString(), proxy.userName, proxy.appName); } catch (Exception e){ log.error("Failed to release proxy " + proxy.name, e); } }; if (async) containerKiller.submit(releaser); else releaser.run(); synchronized (mappingListeners) { for (MappingListener listener: mappingListeners) { listener.mappingRemoved(proxy.name); } } } private Proxy startProxy(String userName, String appName) { ShinyApp app = appService.getApp(appName); if (app == null) { throw new ShinyProxyException("Cannot start container: unknown application: " + appName); } if (findProxy(userName, appName) != null) { throw new ShinyProxyException("Cannot start container: user " + userName + " already has a running proxy"); } boolean internalNetworking = "true".equals(environment.getProperty("shiny.proxy.docker.internal-networking")); boolean generateName = swarmMode || "true".equals(environment.getProperty("shiny.proxy.docker.generate-name", String.valueOf(internalNetworking))); Proxy proxy = new Proxy(); proxy.userName = userName; proxy.appName = appName; if (internalNetworking) { proxy.port = app.getPort(); } else { proxy.port = getFreePort(); } launchingProxies.add(proxy); try { URL hostURL = null; String containerProtocolDefault = "http"; if (!internalNetworking) { hostURL = new URL(environment.getProperty("shiny.proxy.docker.url")); containerProtocolDefault = hostURL.getProtocol(); } proxy.protocol = environment.getProperty("shiny.proxy.docker.container-protocol", containerProtocolDefault); if (generateName) { byte[] nameBytes = new byte[20]; rng.nextBytes(nameBytes); proxy.name = Hex.encodeHexString(nameBytes); } if (swarmMode) { Mount[] mounts = getBindVolumes(app).stream() .map(b -> b.split(":")) .map(fromTo -> Mount.builder().source(fromTo[0]).target(fromTo[1]).type("bind").build()) .toArray(i -> new Mount[i]); ContainerSpec containerSpec = ContainerSpec.builder() .image(app.getDockerImage()) .command(app.getDockerCmd()) .env(buildEnv(userName, app)) .dnsConfig(DnsConfig.builder().nameServers(app.getDockerDns()).build()) .mounts(mounts) .build(); NetworkAttachmentConfig[] networks = Arrays .stream(Optional.ofNullable(app.getDockerNetworkConnections()).orElse(new String[0])) .map(n -> NetworkAttachmentConfig.builder().target(n).build()) .toArray(i -> new NetworkAttachmentConfig[i]); ServiceSpec.Builder serviceSpecBuilder = ServiceSpec.builder() .networks(networks) .name(proxy.name) .taskTemplate(TaskSpec.builder() .containerSpec(containerSpec) .build()); if (!internalNetworking) { serviceSpecBuilder.endpointSpec(EndpointSpec.builder() .ports(PortConfig.builder().publishedPort(proxy.port).targetPort(app.getPort()).build()) .build()); } proxy.serviceId = dockerClient.createService(serviceSpecBuilder.build()).id(); boolean containerFound = retry(i -> { try { Task serviceTask = dockerClient .listTasks(Task.Criteria.builder().serviceName(proxy.name).build()) .stream().findAny().orElseThrow(() -> new IllegalStateException("Swarm service has no tasks")); proxy.containerId = serviceTask.status().containerStatus().containerId(); proxy.host = serviceTask.nodeId(); } catch (Exception e) { throw new RuntimeException("Failed to inspect swarm service tasks"); } return (proxy.containerId != null); }, 10, 2000); if (!containerFound) throw new IllegalStateException("Swarm container did not start in time"); if (internalNetworking) { proxy.host = proxy.name; } else { Node node = dockerClient.listNodes().stream() .filter(n -> n.id().equals(proxy.host)).findAny() .orElseThrow(() -> new IllegalStateException(String.format("Swarm node not found [id: %s]", proxy.host))); proxy.host = node.description().hostname(); } log.info(String.format("Container running in swarm [service: %s] [node: %s]", proxy.name, proxy.host)); } else { Builder hostConfigBuilder = HostConfig.builder(); Optional.ofNullable(memoryToBytes(app.getDockerMemory())).ifPresent(l -> hostConfigBuilder.memory(l)); Optional.ofNullable(app.getDockerNetwork()).ifPresent(n -> hostConfigBuilder.networkMode(app.getDockerNetwork())); List<PortBinding> portBindings; if (internalNetworking) { portBindings = Collections.emptyList(); } else { portBindings = Collections.singletonList(PortBinding.of("0.0.0.0", proxy.port)); } hostConfigBuilder .portBindings(Collections.singletonMap(app.getPort().toString(), portBindings)) .dns(app.getDockerDns()) .binds(getBindVolumes(app)); ContainerConfig containerConfig = ContainerConfig.builder() .hostConfig(hostConfigBuilder.build()) .image(app.getDockerImage()) .exposedPorts(app.getPort().toString()) .cmd(app.getDockerCmd()) .env(buildEnv(userName, app)) .build(); ContainerCreation container = dockerClient.createContainer(containerConfig); if (app.getDockerNetworkConnections() != null) { for (String networkConnection: app.getDockerNetworkConnections()) { dockerClient.connectToNetwork(container.id(), networkConnection); } } if (proxy.name != null) { dockerClient.renameContainer(container.id(), proxy.name); } dockerClient.startContainer(container.id()); ContainerInfo info = dockerClient.inspectContainer(container.id()); if (proxy.name == null) { proxy.name = info.name().substring(1); } if (internalNetworking) { proxy.host = proxy.name; } else { proxy.host = hostURL.getHost(); } proxy.containerId = container.id(); } proxy.startupTimestamp = System.currentTimeMillis(); } catch (Exception e) { releasePort(proxy.port); launchingProxies.remove(proxy); throw new ShinyProxyException("Failed to start container: " + e.getMessage(), e); } if (!testProxy(proxy)) { releaseProxy(proxy, true); launchingProxies.remove(proxy); throw new ShinyProxyException("Container did not respond in time"); } try { URI target = new URI(String.format("%s://%s:%d", proxy.protocol, proxy.host, proxy.port)); synchronized (mappingListeners) { for (MappingListener listener: mappingListeners) { listener.mappingAdded(proxy.name, target); } } } catch (URISyntaxException ignore) {} if (logService.isContainerLoggingEnabled()) { try { LogStream logStream = dockerClient.logs(proxy.containerId, LogsParam.follow(), LogsParam.stdout(), LogsParam.stderr()); logService.attachLogWriter(proxy, logStream); } catch (DockerException e) { log.error("Failed to attach to container log " + proxy.containerId, e); } catch (InterruptedException e) { log.error("Interrupted while attaching to container log " + proxy.containerId, e); } } activeProxies.add(proxy); launchingProxies.remove(proxy); log.info(String.format("Proxy activated [user: %s] [app: %s] [port: %d]", userName, appName, proxy.port)); eventService.post(EventType.AppStart.toString(), userName, appName); return proxy; } private Proxy findProxy(String userName, String appName) { synchronized (activeProxies) { for (Proxy proxy: activeProxies) { if (userName.equals(proxy.userName) && appName.equals(proxy.appName)) return proxy; } } return null; } private void waitForLaunchingProxy(String userName, String appName) { int totalWaitMs = Integer.parseInt(environment.getProperty("shiny.proxy.container-wait-time", "20000")); int waitMs = Math.min(2000, totalWaitMs); int maxTries = totalWaitMs / waitMs; boolean mayProceed = retry(i -> { synchronized (launchingProxies) { for (Proxy proxy: launchingProxies) { if (userName.equals(proxy.userName) && appName.equals(proxy.appName)) { return false; } } } return true; }, maxTries, waitMs); if (!mayProceed) throw new ShinyProxyException("Cannot proceed: waiting for proxy to launch"); } private boolean testProxy(Proxy proxy) { int totalWaitMs = Integer.parseInt(environment.getProperty("shiny.proxy.container-wait-time", "20000")); int waitMs = Math.min(2000, totalWaitMs); int maxTries = totalWaitMs / waitMs; int timeoutMs = Integer.parseInt(environment.getProperty("shiny.proxy.container-wait-timeout", "5000")); return retry(i -> { String urlString = String.format("%s://%s:%d", proxy.protocol, proxy.host, proxy.port); try { URL testURL = new URL(urlString); HttpURLConnection connection = ((HttpURLConnection) testURL.openConnection()); connection.setConnectTimeout(timeoutMs); int responseCode = connection.getResponseCode(); if (responseCode == 200) return true; } catch (Exception e) { if (i > 1) log.warn(String.format("Container unresponsive, trying again (%d/%d): %s", i, maxTries, urlString)); } return false; }, maxTries, waitMs); } private List<String> buildEnv(String userName, ShinyApp app) throws IOException { List<String> env = new ArrayList<>(); env.add(String.format("SHINYPROXY_USERNAME=%s", userName)); String[] groups = userService.getGroups(userService.getCurrentAuth()); env.add(String.format("SHINYPROXY_USERGROUPS=%s", Arrays.stream(groups).collect(Collectors.joining(",")))); String envFile = app.getDockerEnvFile(); if (envFile != null && Files.isRegularFile(Paths.get(envFile))) { Properties envProps = new Properties(); envProps.load(new FileInputStream(envFile)); for (Object key: envProps.keySet()) { env.add(String.format("%s=%s", key, envProps.get(key))); } } for (Map.Entry<String, String> entry : app.getDockerEnv().entrySet()) { env.add(String.format("%s=%s", entry.getKey(), entry.getValue())); } return env; } private List<String> getBindVolumes(ShinyApp app) { List<String> volumes = new ArrayList<>(); if (app.getDockerVolumes() != null) { for (String vol: app.getDockerVolumes()) { volumes.add(vol); } } return volumes; } private int getFreePort() { int startPort = Integer.valueOf(environment.getProperty("shiny.proxy.docker.port-range-start")); int maxPort = Integer.valueOf(environment.getProperty("shiny.proxy.docker.port-range-max", "-1")); int nextPort = startPort; while (occupiedPorts.contains(nextPort)) nextPort++; if (maxPort > 0 && nextPort > maxPort) { throw new ShinyProxyException("Cannot start container: all allocated ports are currently in use." + " Please try again later or contact an administrator."); } occupiedPorts.add(nextPort); return nextPort; } private void releasePort(int port) { occupiedPorts.remove(port); } private boolean retry(IntPredicate job, int tries, int waitTime) { boolean retVal = false; for (int currentTry = 1; currentTry <= tries; currentTry++) { if (job.test(currentTry)) { retVal = true; break; } try { Thread.sleep(waitTime); } catch (InterruptedException ignore) {} } return retVal; } private Long memoryToBytes(String memory) { if (memory == null || memory.isEmpty()) return null; Matcher matcher = Pattern.compile("(\\d+)([bkmg]?)").matcher(memory.toLowerCase()); if (!matcher.matches()) throw new IllegalArgumentException("Invalid memory argument: " + memory); long mem = Long.parseLong(matcher.group(1)); String unit = matcher.group(2); switch (unit) { case "k": mem *= 1024; break; case "m": mem *= 1024*1024; break; case "g": mem *= 1024*1024*1024; break; default: } return mem; } public void addMappingListener(MappingListener listener) { mappingListeners.add(listener); } public void removeMappingListener(MappingListener listener) { mappingListeners.remove(listener); } public static interface MappingListener { public void mappingAdded(String mapping, URI target); public void mappingRemoved(String mapping); } public void heartbeatReceived(String user, String app) { Proxy proxy = findProxy(user, app); if (proxy != null) { proxy.lastHeartbeatTimestamp = System.currentTimeMillis(); } } private class AppCleaner implements Runnable { @Override public void run() { long cleanupInterval = 2 * Long.parseLong(environment.getProperty("shiny.proxy.heartbeat-rate", "10000")); long heartbeatTimeout = Long.parseLong(environment.getProperty("shiny.proxy.heartbeat-timeout", "60000")); while (true) { try { List<Proxy> proxiesToRemove = new ArrayList<>(); long currentTimestamp = System.currentTimeMillis(); synchronized (activeProxies) { for (Proxy proxy: activeProxies) { Long lastHeartbeat = proxy.lastHeartbeatTimestamp; if (lastHeartbeat == null) lastHeartbeat = proxy.startupTimestamp; long proxySilence = currentTimestamp - lastHeartbeat; if (proxySilence > heartbeatTimeout) { log.info(String.format("Releasing inactive proxy [user: %s] [app: %s] [silence: %dms]", proxy.userName, proxy.appName, proxySilence)); proxiesToRemove.add(proxy); } } } for (Proxy proxy: proxiesToRemove) { releaseProxy(proxy, true); } } catch (Throwable t) { log.error("Error in HeartbeatThread", t); } try { Thread.sleep(cleanupInterval); } catch (InterruptedException e) {} } } } }
package fi.csc.chipster.filebroker; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.UUID; import javax.ws.rs.BadRequestException; import javax.ws.rs.DefaultValue; import javax.ws.rs.ForbiddenException; import javax.ws.rs.GET; import javax.ws.rs.InternalServerErrorException; import javax.ws.rs.NotFoundException; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.SecurityContext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import fi.csc.chipster.rest.RestUtils; import fi.csc.chipster.rest.exception.ConflictException; import fi.csc.chipster.sessiondb.RestException; import fi.csc.chipster.sessiondb.SessionDbClient; import fi.csc.chipster.sessiondb.SessionDbClient.SessionEventListener; import fi.csc.chipster.sessiondb.model.Dataset; import fi.csc.chipster.sessiondb.model.SessionEvent; import fi.csc.chipster.sessiondb.model.SessionEvent.EventType; import fi.csc.chipster.sessiondb.model.SessionEvent.ResourceType; import fi.csc.microarray.util.IOUtils; @Path("sessions") public class FileResource implements SessionEventListener { private static Logger logger = LogManager.getLogger(); private static final String SESSION_ID = "sessionId"; private static final String DATASET_ID = "fileId"; private File storage; private SessionDbClient sessionDbClient; public FileResource(File storage, SessionDbClient sessionDbClient) { this.storage = storage; this.sessionDbClient = sessionDbClient; } @GET @Path("{" + SESSION_ID + "}/datasets/{" + DATASET_ID + "}") @Produces(MediaType.APPLICATION_OCTET_STREAM) public Response get( @PathParam(SESSION_ID) UUID sessionId, @PathParam(DATASET_ID) UUID datasetId, @DefaultValue("true") @QueryParam("download") boolean download, @DefaultValue("false") @QueryParam("type") boolean type, @Context SecurityContext sc) { try { // check authorization Dataset dataset = sessionDbClient.getDataset(sc.getUserPrincipal().getName(), sessionId, datasetId, false); if (dataset == null) { throw new ForbiddenException("dataset not found"); } if (dataset.getFile() == null || dataset.getFile().getFileId() == null) { throw new NotFoundException("file id is null"); } UUID fileId = dataset.getFile().getFileId(); // get the file File f = getStorageFile(fileId); if (!f.exists()) { throw new NotFoundException("no such file"); } ResponseBuilder response = Response.ok(f); if (download) { // hint filename for dataset export response.header("Content-Disposition", "attachment; filename=\"" + dataset.getName() + "\""); } if (type) { response.type(getType(dataset)); } return response.build(); } catch (RestException e) { throw new InternalServerErrorException("failed to get the dataset", e); } } private MediaType getType(Dataset dataset) { MediaType type = null; // we should store the recognized type so that client could rely on it if (dataset.getName().toLowerCase().endsWith(".html")) { // required for visualizing html files in an iFrame type = MediaType.TEXT_HTML_TYPE; } return type; } private File getStorageFile(UUID fileId) { // having a fileId as UUID makes sure that it doesn't point to other dirs return new File(storage, fileId.toString()); } @PUT @Path("{" + SESSION_ID + "}/datasets/{" + DATASET_ID + "}") //@Consumes(MediaType.APPLICATION_OCTET_STREAM) public Response putFile( @PathParam(SESSION_ID) UUID sessionId, @PathParam(DATASET_ID) UUID datasetId, InputStream inputStream, @QueryParam("flowChunkNumber") Long chunkNumber, @QueryParam("flowChunkSize") Long chunkSize, @Context SecurityContext sc) { UUID fileId = null; Dataset dataset = null; try { logger.debug("chunkNumber " + chunkNumber + " uploading"); // check authorization dataset = getDataset(sessionId, datasetId, sc); if (dataset == null) { throw new ForbiddenException("dataset not found"); } if (chunkNumber == null || chunkNumber == 1) { if (dataset.getFile() != null) { throw new ConflictException("file not null"); } // create a new file fileId = RestUtils.createUUID(); File f = getStorageFile(fileId); if (f.exists()) { throw new ConflictException("file exists"); } try { IOUtils.copy(inputStream, f); fi.csc.chipster.sessiondb.model.File file = new fi.csc.chipster.sessiondb.model.File(); file.setFileId(fileId); dataset.setFile(file); sessionDbClient.updateDataset(sessionId, dataset); } catch (EOFException e) { // upload interrupted f.delete(); throw new BadRequestException("EOF"); } } else { if (dataset.getFile() == null) { throw new ConflictException("file is null"); } // append to the old file fileId = dataset.getFile().getFileId(); File f = getStorageFile(fileId); if (f.exists()) { if (chunkNumber == null || chunkSize == null) { throw new ConflictException("missing query parameters"); } else { if (isChunkReady(f, chunkNumber, chunkSize)) { // we have this junk already inputStream.close(); return Response.ok().build(); } } } /* * When the upload is paused, the chunk will end prematurely * with EOF. If we append this stream directly to the right * file, it will be difficult to continue later. Write the * chunk first to a temp file and append to the right file only * when the whole chunk is completed. */ File chunkFile = new File(f.getParent(), f.getName() + ".chunk" + chunkNumber); try { // copy first to a temp file FileOutputStream chunkOutStream = new FileOutputStream(chunkFile, false); IOUtils.copy(inputStream, chunkOutStream); // append chunk to the right file FileInputStream chunkInStream = new FileInputStream(chunkFile); FileOutputStream outStream = new FileOutputStream(f, true); IOUtils.copy(chunkInStream, outStream); chunkFile.delete(); logger.debug("file size after copy: " + f.length()); // // alternative implementation which buffers the chunk in memory // // the last chunk may be double the size of the chunkSize // ByteArrayOutputStream chunkOutStream = new ByteArrayOutputStream(100*1024*1024); // IOUtils.copy(inputStream, chunkOutStream); // // append chunk to the right file // FileOutputStream outStream = new FileOutputStream(f, true); // chunkOutStream.writeTo(outStream); // chunkOutStream.close(); // outStream.close(); } catch (EOFException e) { // upload interrupted chunkFile.delete(); throw new BadRequestException("EOF"); } } return Response.ok().build(); } catch (IOException | RestException | InterruptedException e) { throw new InternalServerErrorException("upload failed", e); } } private boolean isChunkReady(File f, Long chunkNumber, Long chunkSize) { long expectedSize = chunkNumber * chunkSize; logger.debug("is chunk " + chunkNumber + " ready? File size: " + f.length() + " expected " + expectedSize); return f.exists() && f.length() >= expectedSize; } private Dataset getDataset(UUID sessionId, UUID datasetId, SecurityContext sc) throws InterruptedException, RestException { return sessionDbClient.getDataset(sc.getUserPrincipal().getName(), sessionId, datasetId, true); } @Override public void onEvent(SessionEvent e) { logger.debug("received a file event: " + e.getResourceType() + " " + e.getType()); if (ResourceType.FILE == e.getResourceType()) { if (EventType.DELETE == e.getType()) { if (e.getResourceId() != null) { getStorageFile(e.getResourceId()).delete(); } else { logger.warn("received a file deletion event with null id"); } } } } }
package fi.csc.chipster.rest.hibernate; import java.io.File; import java.io.IOException; import java.math.BigInteger; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Timer; import java.util.TimerTask; import java.util.TreeMap; import org.apache.commons.io.FileUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.services.s3.model.S3ObjectSummary; import com.amazonaws.services.s3.transfer.Download; import com.amazonaws.services.s3.transfer.TransferManager; import com.amazonaws.services.s3.transfer.Upload; import fi.csc.chipster.rest.Config; import fi.csc.chipster.rest.ProcessUtils; import fi.csc.chipster.rest.hibernate.HibernateUtil.DatabaseConnectionRefused; import fi.csc.chipster.rest.hibernate.HibernateUtil.HibernateRunnable; public class DbBackup { public class RestoreException extends RuntimeException { public RestoreException(Exception cause) { super(cause); } public RestoreException(String msg) { super(msg); } } private static final String CONF_DB_BACKUP_DAILY_COUNT_FILE = "db-backup-daily-count-file"; private static final String CONF_DB_BACKUP_MONTHLY_COUNT_S3 = "db-backup-monthly-count-s3"; private static final String CONF_DB_BACKUP_DAILY_COUNT_S3 = "db-backup-daily-count-s3"; private final static Logger logger = LogManager.getLogger(); private static final String BACKUP_NAME_POSTFIX = ".sql.lz4"; private static final String BACKUP_NAME_POSTFIX_UNCOMPRESSED = ".sql"; private static final String BACKUP_OBJECT_NAME_PART = "-db-backup_"; private static final String CONF_DB_BACKUP_TIME = "db-backup-time"; private static final String CONF_DB_BACKUP_INTERVAL = "db-backup-interval"; private static final String CONF_DB_RESTORE_KEY = "db-restore-key"; private static final String CONF_DB_BACKUP_BUCKET = "db-backup-bucket"; private static final String COND_DB_BACKUP_S3_SIGNER_OVERRIDE = "db-backup-s3-signer-override"; private static final String CONF_DB_BACKUP_S3_SECRET_KEY = "db-backup-s3-secret-key"; private static final String CONF_DB_BACKUP_S3_ACCESS_KEY = "db-backup-s3-access-key"; private static final String CONF_DB_BACKUP_S3_REGION = "db-backup-s3-region"; private static final String CONF_DB_BACKUP_S3_ENDPOINT = "db-backup-s3-endpoint"; private Config config; private String role; private Timer backupTimer; private String url; private String user; private String password; private final String backupPrefix; private final String backupPostfix; private final String backupPostfixUncompressed; private int dailyCountS3; private int monthlyCountS3; private int dailyCountFile; private SessionFactory sessionFactory; public DbBackup(Config config, String role, String url, String user, String password) { this.config = config; this.role = role; this.url = url; this.user = user; this.password = password; backupPrefix = role + BACKUP_OBJECT_NAME_PART; backupPostfix = BACKUP_NAME_POSTFIX; backupPostfixUncompressed = BACKUP_NAME_POSTFIX_UNCOMPRESSED; dailyCountS3 = Math.max(3, Integer.parseInt(config.getString(CONF_DB_BACKUP_DAILY_COUNT_S3, role))); monthlyCountS3 = Integer.parseInt(config.getString(CONF_DB_BACKUP_MONTHLY_COUNT_S3, role)); dailyCountFile = Integer.parseInt(config.getString(CONF_DB_BACKUP_DAILY_COUNT_FILE, role)); Configuration hibernateConf = HibernateUtil.getHibernateConf(new ArrayList<Class<?>>(), url, "none", user, password, config, role); try { // fail fast if there is no Postgres HibernateUtil.testConnection(url, user, password); sessionFactory = HibernateUtil.buildSessionFactory(hibernateConf); } catch (DatabaseConnectionRefused e) { logger.error(role + " db backups disabled: " + e.getMessage()); } } public void checkRestore() { String restoreKey = getRestoryKey(config, role); if (!restoreKey.isEmpty()) { restore(restoreKey); // don't start backups when restoring to make it safer to restore from the backups of some other installation throw new RestoreException(role + " db restore completed. Remove the db-restore-key-" + role + " from the configuration, restart the Backup service and start all other services"); } } public static String getRestoryKey(Config config, String role) { return config.getString(CONF_DB_RESTORE_KEY, role); } public void scheduleBackups() { int backupInterval = Integer.parseInt(config.getString(CONF_DB_BACKUP_INTERVAL, role)); String backupTimeString = config.getString(CONF_DB_BACKUP_TIME, role); startBackupTimer(backupInterval, backupTimeString, sessionFactory); } private void startBackupTimer(int backupInterval, String backupTimeString, SessionFactory sessionFactory) { int startHour = Integer.parseInt(backupTimeString.split(":")[0]); int startMinute = Integer.parseInt(backupTimeString.split(":")[1]); Calendar firstBackupTime = Calendar.getInstance(); if (firstBackupTime.get(Calendar.HOUR_OF_DAY) > startHour || (firstBackupTime.get(Calendar.HOUR_OF_DAY) == startHour && firstBackupTime.get(Calendar.MINUTE) >= startMinute)) { firstBackupTime.add(Calendar.DATE, 1); } firstBackupTime.set(Calendar.HOUR_OF_DAY, startHour); firstBackupTime.set(Calendar.MINUTE, startMinute); firstBackupTime.set(Calendar.SECOND, 0); firstBackupTime.set(Calendar.MILLISECOND, 0); logger.info("next " + role + " db backup is scheduled at " + firstBackupTime.getTime().toString()); logger.info("save " + role + " db backups to bucket: " + getBackupBucket()); backupTimer = new Timer(); backupTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { try { dbCleanUp(); } catch (InterruptedException | IOException e) { logger.error(role + " db clean up failed", e); } try { backup(); } catch (IOException | AmazonClientException | InterruptedException e) { logger.error(role + " db backup failed", e); } } }, firstBackupTime.getTime(), backupInterval * 60 * 60 * 1000); // }, new Date(), backupInterval * 60 * 60 * 1000); } private void restore(String key) throws RestoreException { if (!getTableStats().isEmpty()) { throw new RestoreException("Restore is allowed only to an empty DB. Please stop all services using the DB, delete the DB files and restart the DB process."); } File restoreFile = new File("db-backups", role + "-db-restore.sql.lz4"); File restoreFileExtracted = new File("db-backups", role + "-db-restore.sql"); try { logger.info("download " + role + " db backup to " + restoreFile); TransferManager transferManager = getTransferManager(config, role); Download download = transferManager.download(getBackupBucket(), key, restoreFile); download.waitForCompletion(); logger.info("extract " + role + " db backup"); ProcessUtils.run(restoreFile, restoreFileExtracted, "lz4", "-d"); logger.info("restore " + role + " db backup from " + restoreFileExtracted); runPostgres(restoreFileExtracted, null, false, "psql"); logger.info("backup restored"); printTableStats(); } catch (AmazonClientException | InterruptedException | IOException e) { logger.error(role + "db restore failed", e); throw new RestoreException(e); } finally { restoreFile.delete(); restoreFileExtracted.delete(); } } private void dbCleanUp() throws IOException, InterruptedException { // can't use runPostgres() because unfortunately vacuumlo has little bit different parameters final Map<String, String> env = new HashMap<>(); env.put("PGPASSWORD", this.password); String dbUrl = url.replace("jdbc:", ""); logger.info(role + " db vacuumlo"); ProcessUtils.run(null, null, env, true, new String[] { "vacuumlo", "-U", this.user, dbUrl}); } private void backup() throws IOException, AmazonServiceException, AmazonClientException, InterruptedException { String bucket = getBackupBucket(); if (bucket.isEmpty()) { logger.warn("no backup configuration for " + role + " db"); return; } printTableStats(); Instant now = Instant.now(); File backupFileUncompressed = new File("db-backups", backupPrefix + now + backupPostfixUncompressed); File backupFile = new File("db-backups", backupPrefix + now + backupPostfix); logger.info("save " + role + " db backup to " + backupFileUncompressed.getAbsolutePath()); // Stream the script to a local file runPostgres(null, backupFileUncompressed, false, "pg_dump"); logger.info("compress " + role + " db backup (" + FileUtils.byteCountToDisplaySize(backupFileUncompressed.length()) + ")"); ProcessUtils.run(backupFileUncompressed, backupFile, "lz4"); backupFileUncompressed.delete(); logger.info("upload " + role + " db backup (" + FileUtils.byteCountToDisplaySize(backupFile.length()) + ")"); TransferManager transferManager = getTransferManager(config, role); Upload upload = transferManager.upload(bucket, backupFile.getName(), backupFile); upload.waitForCompletion(); removeOldFileBackups(backupFile.getParentFile(), backupPrefix, backupPostfix); removeOldS3Backups(transferManager, bucket, backupPrefix, backupPostfix); } private void runPostgres(File stdinFile, File stdoutFile, boolean showStdout, String... command) throws IOException, InterruptedException { runPostgres(stdinFile, stdoutFile, this.url, this.user, this.password, showStdout, command); } public static void runPostgres(File stdinFile, File stdoutFile, String url, String user, String password, boolean showStdout, String... command) throws IOException, InterruptedException { List<String> cmd = new ArrayList<String>(Arrays.asList(command)); cmd.add("--dbname=" + url.replace("jdbc:", "")); cmd.add("--username=" + user); final Map<String, String> env = new HashMap<>(); env.put("PGPASSWORD", password); ProcessUtils.run(stdinFile, stdoutFile, env, showStdout, cmd.toArray(new String[0])); } private Map<String, Long> getTableStats() { return HibernateUtil.runInTransaction(new HibernateRunnable<Map<String, Long>>() { @Override public Map<String, Long> run(Session hibernateSession) { @SuppressWarnings("unchecked") List<String> tables = hibernateSession.createNativeQuery("SELECT tablename FROM pg_catalog.pg_tables where schemaname='public'").getResultList(); Map<String, Long> tableRows = new LinkedHashMap<>(); for (String table : tables) { BigInteger rows = (BigInteger) hibernateSession.createNativeQuery("SELECT count(*) FROM \"" + table + "\"").getSingleResult(); tableRows.put(table, rows.longValue()); } return tableRows; } }, this.sessionFactory); } public void printTableStats() { String logLine = "table row counts: "; for (Entry<String, Long> entry : getTableStats().entrySet()) { logLine += entry.getKey() + " " + entry.getValue() + ", "; } logger.info(logLine); } public static TransferManager getTransferManager(Config config, String role) { String endpoint = config.getString(CONF_DB_BACKUP_S3_ENDPOINT, role); String region = config.getString(CONF_DB_BACKUP_S3_REGION, role); String access = config.getString(CONF_DB_BACKUP_S3_ACCESS_KEY, role); String secret = config.getString(CONF_DB_BACKUP_S3_SECRET_KEY, role); String signerOverride = config.getString(COND_DB_BACKUP_S3_SIGNER_OVERRIDE, role); if (endpoint == null || region == null || access == null || secret == null) { logger.warn("backups are not configured"); } return S3Util.getTransferManager(endpoint, region, access, secret, signerOverride); } private String getBackupBucket() { return config.getString(CONF_DB_BACKUP_BUCKET, role); } /** * Remove old backups * * Keep x daily backups and y monthly backups. This is relatively safe even if the * server time was incorrect or the backups were created more often. Files * created during the clean-up are kept. * * @param transferManager * @param bucket * @param backupPrefix * @param backupPostfix */ private void removeOldS3Backups(TransferManager transferManager, String bucket, String backupPrefix, String backupPostfix) { logger.info("list " + role + " db s3 backups"); List<S3ObjectSummary> summaries = S3Util.getObjects(transferManager, bucket); // all backups TreeMap<Instant, S3ObjectSummary> filesToDelete = BackupRotation2.parse(summaries, backupPrefix, backupPostfix, o -> o.getKey()); logger.info(summaries.size() + " s3 backups found, total size " + FileUtils.byteCountToDisplaySize(BackupRotation2.getTotalSizeS3(filesToDelete.values()))); TreeMap<Instant, S3ObjectSummary> daily = BackupRotation2.getFirstOfEachDay(filesToDelete); TreeMap<Instant, S3ObjectSummary> monthly = BackupRotation2.getFirstOfEachMonth(filesToDelete); // keep these TreeMap<Instant, S3ObjectSummary> latestDaily = BackupRotation2.getLast(daily, dailyCountS3); TreeMap<Instant, S3ObjectSummary> latestMonthly = BackupRotation2.getLast(monthly, monthlyCountS3); logger.info(latestDaily.size() + " daily s3 backups kept, total size " + FileUtils.byteCountToDisplaySize(BackupRotation2.getTotalSizeS3(latestDaily.values()))); logger.info(latestMonthly.size() + " monthly s3 backups kept, total size " + FileUtils.byteCountToDisplaySize(BackupRotation2.getTotalSizeS3(latestMonthly.values()))); // remove the backups to keep from the list of all backups to get those that we want to remove filesToDelete = BackupRotation2.removeAll(filesToDelete, latestDaily.keySet()); filesToDelete = BackupRotation2.removeAll(filesToDelete, latestMonthly.keySet()); for (S3ObjectSummary obj : filesToDelete.values()) { logger.info("delete s3 backup " + obj.getKey()); transferManager.getAmazonS3Client().deleteObject(bucket, obj.getKey()); } logger.info(filesToDelete.size() + " s3 backups deleted, total size " + FileUtils.byteCountToDisplaySize(BackupRotation2.getTotalSizeS3(filesToDelete.values()))); } private void removeOldFileBackups(File dir, String backupPrefix, String backupPostfix) { logger.info("list " + role + " db backup files"); List<File> allFiles = Arrays.asList(dir.listFiles()); // all backups TreeMap<Instant, File> filesToDelete = BackupRotation2.parse(allFiles, backupPrefix, backupPostfix, f -> f.getName()); logger.info(allFiles.size() + " backup files found, total size " + FileUtils.byteCountToDisplaySize(BackupRotation2.getTotalSizeFiles(filesToDelete.values()))); TreeMap<Instant, File> daily = BackupRotation2.getFirstOfEachDay(filesToDelete); // keep these TreeMap<Instant, File> latestDaily = BackupRotation2.getLast(daily, dailyCountFile); logger.info(latestDaily.size() + " daily backup files kept, total size " + FileUtils.byteCountToDisplaySize(BackupRotation2.getTotalSizeFiles(latestDaily.values()))); // remove the backups to keep from the list of all backups to get those that we want to remove filesToDelete = BackupRotation2.removeAll(filesToDelete, latestDaily.keySet()); for (File obj : filesToDelete.values()) { logger.info("delete backup file " + obj.getName()); obj.delete(); } logger.info(filesToDelete.size() + " backup files deleted, total size " + FileUtils.byteCountToDisplaySize(BackupRotation2.getTotalSizeFiles(filesToDelete.values()))); } }
package fi.csc.microarray.client; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.URL; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import org.jdesktop.swingx.JXHyperlink; public class QuickLinkPanel extends JPanel implements ActionListener { private SwingClientApplication application; private JXHyperlink sessionLink; private JXHyperlink importLink; private JXHyperlink emptyLink; private JXHyperlink exampleLink; private JXHyperlink importFolderLink; private JXHyperlink importURLLink; private static final String LINK_WORD = "***"; public QuickLinkPanel() { super(new GridBagLayout()); application = (SwingClientApplication) Session.getSession().getApplication(); this.setBackground(Color.white); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.NORTHWEST; // c.insets.set(5, 10, 5, 10); // c.gridwidth = 2; // JLabel title = new JLabel("Getting started"); // title.setFont(title.getFont().deriveFont( // (float) (title.getFont().getSize()*1.2))); // title.setFont(title.getFont().deriveFont(Font.BOLD)); // this.add(title, c); // c.gridwidth = 1; c.insets.set(0, 10, 0, 0); addLink("To start working with Chipster, you need to load in data first: \n \n \n *** to get familiar with Chipster.", getExampleLink(), VisualConstants.EXAMPLE_SESSION_ICON, c); addLink("*** to continue working on previous sessions.", getSessionLink(), VisualConstants.OPEN_SESSION_LINK_ICON, c); List<JXHyperlink> importLinks = new LinkedList<JXHyperlink>(); importLinks.add(getImportLink()); importLinks.add(getImportFolderLink()); importLinks.add(getImportURLLink()); addLink("Import new data to Chipster: \n *** \n *** \n ***", importLinks, VisualConstants.IMPORT_LINK_ICON, c); // Panels to take rest of space JPanel bottomPanel = new JPanel(); JPanel rightPanel = new JPanel(); bottomPanel.setBackground(Color.white); rightPanel.setBackground(Color.white); c.weightx = 0.0; c.weighty = 1.0; c.fill = GridBagConstraints.VERTICAL; c.gridx = 0; c.gridy++; this.add(bottomPanel, c); c.weightx = 1.0; c.weighty = 0.0; c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 3; c.gridy = 0; this.add(rightPanel, c); this.setMinimumSize(new Dimension(0, 0)); this.setPreferredSize(new Dimension(VisualConstants.LEFT_PANEL_WIDTH, VisualConstants.TREE_PANEL_HEIGHT)); } private void addLink(String description, JXHyperlink link, ImageIcon icon, GridBagConstraints c) { List<JXHyperlink> list = new LinkedList<JXHyperlink>(); list.add(link); addLink(description, list, icon, c); } private void addLink(String description, List<JXHyperlink> links, ImageIcon icon, GridBagConstraints c) { String[] words = description.split(" "); int rowChars = 0; final int MAX_ROW_CHARS = 40; Iterator<JXHyperlink> linkIterator = links.iterator(); int rowCount = 0; c.gridx = 1; c.insets.top = 10; JPanel row = null; for (int i = 0; i < words.length; i++) { if (row == null || rowChars + words[i].length() > MAX_ROW_CHARS || words[i].equals("\n")) { FlowLayout flow = new FlowLayout(FlowLayout.LEADING); flow.setVgap(0); flow.setHgap(0); row = new JPanel(flow); row.setBackground(Color.white); c.gridy++; this.add(row, c); c.insets.top = 0; // After first row rowChars = 0; rowCount++; } if (words[i].equals(LINK_WORD)) { JXHyperlink link = linkIterator.next(); rowChars += link.getText().length() + 1; row.add(link); // row.add(new JLabel(link.getText())); } else if (!words[i].equals("\n")) { JLabel text = new JLabel(" " + words[i]); row.add(text); rowChars += words[i].length() + 1; } } c.gridy -= (rowCount - 1); c.gridheight = rowCount; c.gridx = 0; c.insets.top = 10; this.add(new JLabel(icon), c); c.gridy += (rowCount - 1); c.gridheight = 1; } private JXHyperlink getExampleLink() { if (exampleLink == null) { exampleLink = new JXHyperlink(); exampleLink.setText("Open example session"); exampleLink.addActionListener(this); } return exampleLink; } private JXHyperlink getImportLink() { if (importLink == null) { importLink = new JXHyperlink(); importLink.setText("Import files"); importLink.addActionListener(this); } return importLink; } private JXHyperlink getImportFolderLink() { if (importFolderLink == null) { importFolderLink = new JXHyperlink(); importFolderLink.setText("Import folder"); importFolderLink.addActionListener(this); } return importFolderLink; } private JXHyperlink getImportURLLink() { if (importURLLink == null) { importURLLink = new JXHyperlink(); importURLLink.setText("Import from URL"); importURLLink.addActionListener(this); } return importURLLink; } private JXHyperlink getSessionLink() { if (sessionLink == null) { sessionLink = new JXHyperlink(); sessionLink.setText("Open session"); sessionLink.addActionListener(this); } return sessionLink; } public void actionPerformed(ActionEvent e) { if (e.getSource() == sessionLink) { application.loadSession(); } else if (e.getSource() == importLink) { try { application.openFileImport(); } catch (Exception ex) { application.reportException(ex); } } else if (e.getSource() == importURLLink) { try { application.openURLImport(); } catch (Exception ex) { application.reportException(ex); } } else if (e.getSource() == importFolderLink) { application.openDirectoryImportDialog(); } else if (e.getSource() == emptyLink) { } else if (e.getSource() == exampleLink) { try { URL url = new URL("https://extras.csc.fi/biosciences/Chipster/sessionIlluminaHuman6v1teratospermia.cs"); application.loadSessionFrom(url); } catch (Exception ex) { application.reportException(ex); } } } }
package de.stonebone.cars.server; import java.io.IOException; import java.io.File; import java.io.PrintWriter; import java.nio.file.Files; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletException; import javax.servlet.annotation.WebListener; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import de.stonebone.cars.util.Configuration; import de.stonebone.cars.util.Inbox; @WebServlet(urlPatterns = "/state") @WebListener public class CarsServlet extends HttpServlet implements ServletContextListener { private static final long serialVersionUID = 1L; private int counter = 0; private Thread worker; StringBuilder builder = new StringBuilder(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/event-stream"); response.setCharacterEncoding("UTF-8"); response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1. response.setHeader("Pragma", "no-cache"); // HTTP 1.0. response.setDateHeader("Expires", 0); // Proxies. builder.setLength(0); builder.append("data:"); builder.append(counter); Configuration[] cons = Inbox.cons; if (cons != null) for (int id = 0; id < cons.length; id++) { builder.append(",").append(id); builder.append(",").append(cons[id].steering); builder.append(",").append(cons[id].throttle); } builder.append("\n\n"); PrintWriter writer = response.getWriter(); writer.write(builder.toString()); writer.flush(); } @Override public void contextDestroyed(ServletContextEvent event) { System.out.println(event.toString()); Inbox.running = false; try { Thread.sleep(333); } catch (InterruptedException e) { } } @Override public void contextInitialized(ServletContextEvent event) { System.out.println(event.toString()); String path = event.getServletContext().getRealPath("/"); worker = new Thread(() -> { Inbox.running = true; try { Inbox.main(new String[0]); } catch (Exception e) { event.getServletContext().log(e.toString()); try { Files.write(new File(path, "exception.txt").toPath(), e.toString().getBytes()); } catch (Exception e1) { // ignore } } } ); worker.setDaemon(true); worker.start(); } }
package api.web.gw2.mapping.core; import api.web.gw2.mapping.v2.account.Account; import api.web.gw2.mapping.v2.account.AccountAccessType; import api.web.gw2.mapping.v2.account.bank.BankSlot; import api.web.gw2.mapping.v2.account.finishers.FinisherUnlock; import api.web.gw2.mapping.v2.account.home.cats.Cat; import api.web.gw2.mapping.v2.account.inventory.SharedInventory; import api.web.gw2.mapping.v2.account.wallet.CurrencyAmount; import api.web.gw2.mapping.v2.achievements.Achievement; import api.web.gw2.mapping.v2.achievements.daily.DailyAchievement; import api.web.gw2.mapping.v2.achievements.daily.DailyAchievementLevelRange; import api.web.gw2.mapping.v2.backstory.answers.BackstoryAnswer; import api.web.gw2.mapping.v2.backstory.questions.BackstoryQuestion; import api.web.gw2.mapping.v2.characters.Character; import api.web.gw2.mapping.v2.characters.id.crafting.CharacterCrafting; import api.web.gw2.mapping.v2.characters.CharacterProfession; import api.web.gw2.mapping.v2.characters.id.core.CharacterCore; import api.web.gw2.mapping.v2.characters.id.inventory.CharacterInventoryBinding; import api.web.gw2.mapping.v2.continents.Continent; import api.web.gw2.mapping.v2.currencies.Currency; import api.web.gw2.mapping.v2.finishers.Finisher; import api.web.gw2.mapping.v2.guild.id.Guild; import api.web.gw2.mapping.v2.guild.id.log.LogEvent; import api.web.gw2.mapping.v2.guild.id.stash.Stash; import api.web.gw2.mapping.v2.guild.id.teams.Team; import api.web.gw2.mapping.v2.guild.id.treasury.Treasury; import api.web.gw2.mapping.v2.guild.upgrades.Upgrade; import api.web.gw2.mapping.v2.items.Item; import api.web.gw2.mapping.v2.items.ItemDetails; import api.web.gw2.mapping.v2.items.ItemType; import api.web.gw2.mapping.v2.itemstats.Itemstats; import api.web.gw2.mapping.v2.legends.Legend; import api.web.gw2.mapping.v2.maps.Map; import api.web.gw2.mapping.v2.materials.MaterialStorage; import api.web.gw2.mapping.v2.minis.Mini; import api.web.gw2.mapping.v2.pets.Pet; import api.web.gw2.mapping.v2.professions.Profession; import api.web.gw2.mapping.v2.pvp.amulets.Amulet; import api.web.gw2.mapping.v2.pvp.games.Game; import api.web.gw2.mapping.v2.pvp.seasons.Season; import api.web.gw2.mapping.v2.pvp.seasons.leaderboards.LeaderboardEntry; import api.web.gw2.mapping.v2.pvp.standings.Standing; import api.web.gw2.mapping.v2.pvp.stats.Stat; import api.web.gw2.mapping.v2.recipes.Recipe; import api.web.gw2.mapping.v2.recipes.RecipeCraftingDiscipline; import api.web.gw2.mapping.v2.skins.JsonpSkinArmorDetails; import api.web.gw2.mapping.v2.skins.Skin; import api.web.gw2.mapping.v2.skins.SkinFlag; import api.web.gw2.mapping.v2.skins.SkinType; import api.web.gw2.mapping.v2.specializations.Specialization; import api.web.gw2.mapping.v2.stories.Story; import api.web.gw2.mapping.v2.stories.seasons.StorySeason; import api.web.gw2.mapping.v2.titles.Title; import api.web.gw2.mapping.v2.traits.Trait; import api.web.gw2.mapping.v2.traits.TraitFact; import api.web.gw2.mapping.v2.worlds.World; import api.web.gw2.mapping.v2.worlds.WorldPopulation; import api.web.gw2.mapping.v2.wvw.matches.Match; import api.web.gw2.mapping.v2.wvw.objectives.Objective; import api.web.gw2.mapping.v2.wvw.ranks.Rank; import java.io.IOException; import java.net.URL; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Iterator; import java.util.Optional; import java.util.OptionalInt; import java.util.Set; import java.util.stream.IntStream; import org.junit.After; import org.junit.AfterClass; import static org.junit.Assert.*; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import api.web.gw2.mapping.v2.characters.id.equipment.CharacterEquipment; import api.web.gw2.mapping.v2.characters.id.inventory.CharacterInventoryBag; import api.web.gw2.mapping.v2.characters.id.sab.CharacterSabResponse; import api.web.gw2.mapping.v2.dungeons.Dungeon; import api.web.gw2.mapping.v2.gliders.Glider; import api.web.gw2.mapping.v2.pvp.ranks.PvpRank; import api.web.gw2.mapping.v2.races.Race; public final class JsonpContext_SAX_LocalTest { public JsonpContext_SAX_LocalTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } final JsonpContext instance = JsonpContext.SAX; @Before public void setUp() { } @After public void tearDown() { } @Test public void testLoadObject_World_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(World local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/worlds/"; // NOI18N. final String filename = "world1.json"; // NOI18N. final URL url = getClass().getResource(basecode + filename); assertNotNull(url); final World value = instance.loadObject(World.class, url); assertNotNull(value); assertEquals(1001, value.getId()); assertEquals("Anvil Rock", value.getName()); // NOI18N. assertEquals(WorldPopulation.MEDIUM, value.getPopulation()); } @Test public void testLoadObject_Account_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Account local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/account/"; // NOI18N. final String filename = "account1.json"; // NOI18N. final URL url = getClass().getResource(basecode + filename); assertNotNull(url); final Account value = instance.loadObject(Account.class, url); assertNotNull(value); assertEquals("b8169418-1c11-405f-91bb-e2b29d602b8a", value.getId()); // NOI18N. assertEquals("ExampleAccount.1234", value.getName()); // NOI18N. assertEquals(1007, value.getWorld()); assertEquals(Collections.unmodifiableSet(new LinkedHashSet(Arrays.asList("75FD83CF-0C45-4834-BC4C-097F93A487AF"))), value.getGuilds()); // NOI18N. assertEquals(AccountAccessType.GUILD_WARS_2, value.getAccess()); assertEquals(64, value.getFractalLevel()); } @Test public void testLoadObject_CurrencyAmount_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(CurrencyAmount local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/account/wallet/"; // NOI18N. final String filename = "currency_amount1.json"; // NOI18N. final URL url = getClass().getResource(basecode + filename); assertNotNull(url); final CurrencyAmount value = instance.loadObject(CurrencyAmount.class, url); assertNotNull(value); assertEquals(1, value.getId()); assertEquals(100001, value.getValue()); } @Test public void testLoadObject_Mini_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Mini local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/minis/"; // NOI18N. final String filename = "mini1.json"; // NOI18N. final URL url = getClass().getResource(basecode + filename); assertNotNull(url); final Mini value = instance.loadObject(Mini.class, url); assertNotNull(value); assertEquals(1, value.getId()); assertEquals("Mini-Rytlock", value.getName()); // NOI18N. assertEquals(Optional.empty(), value.getUnlock()); assertEquals(URLReference.of("https://render.guildwars2.com/file/795ED1B945A29EC3E3066797DF57FFB25ABAA631/340551.png"), value.getIcon()); // NOI18N. assertEquals(1, value.getOrder()); assertEquals(21047, value.getItemId()); } @Test public void testLoadObject_Specialization_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Specialization local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/specializations/"; // NOI18N. final String filename = "specialization1.json"; // NOI18N. final URL url = getClass().getResource(basecode + filename); assertNotNull(url); final Specialization value = instance.loadObject(Specialization.class, url); assertNotNull(value); assertEquals(1, value.getId()); assertEquals("Dueling", value.getName()); // NOI18N. assertEquals(CharacterProfession.MESMER, value.getProfession()); assertEquals(false, value.isElite()); } @Test public void testLoadObject_Trait_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Trait local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/traits/"; // NOI18N. final String[] filenames = { "trait1.json", // NOI18N. "trait2.json" // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Trait value = instance.loadObject(Trait.class, url); assertNotNull(value); assertEquals(214, value.getId()); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Character_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Character local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/characters/"; // NOI18N. final String[] filenames = { "character1.json", // NOI18N. "character2.json" // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Character value = instance.loadObject(Character.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_CharacterCore_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(CharacterCore local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/characters/id/core/"; // NOI18N. final String[] filenames = { "charactercore1.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final CharacterCore value = instance.loadObject(CharacterCore.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_CharacterCrafting_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(CharacterCrafting local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/characters/id/crafting/"; // NOI18N. final String filename = "charactercrafting1.json"; // NOI18N. final URL url = getClass().getResource(basecode + filename); assertNotNull(url); final CharacterCrafting value = instance.loadObject(CharacterCrafting.class, url); assertNotNull(value); assertEquals(RecipeCraftingDiscipline.ARTIFICER, value.getDiscipline()); assertEquals(500, value.getRating()); assertEquals(true, value.isActive()); } @Test public void testLoadObject_CharacterSab_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(CharacterSab local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/characters/id/sab/"; // NOI18N. final String[] filenames = {"sab1.json"}; // NOI18N. final int[] expZoneNumbers = {18}; final int[] expUnlockNumbers = {17}; final int[] expSongNumbers = {3}; assertEquals(filenames.length, expZoneNumbers.length); assertEquals(filenames.length, expUnlockNumbers.length); assertEquals(filenames.length, expSongNumbers.length); IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final CharacterSabResponse value = instance.loadObject(CharacterSabResponse.class, url); assertNotNull(value); final int expZoneNumber = expZoneNumbers[index]; assertEquals(expZoneNumber, value.getZones().size()); final int expUnlockNumber = expUnlockNumbers[index]; assertEquals(expUnlockNumber, value.getUnlocks().size()); final int expSongNumber = expSongNumbers[index]; assertEquals(expSongNumber, value.getSongs().size()); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Equipment_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Equipment local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/characters/id/equipment/"; // NOI18N. final String[] filenames = { "equipment1.json", // NOI18N. "equipment2.json", // NOI18N. "equipment3.json", // NOI18N. "equipment4.json" // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final CharacterEquipment value = instance.loadObject(CharacterEquipment.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_InventoryBag_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(InventoryBag local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/characters/id/inventory/"; // NOI18N. final String[] filenames = { "inventorybag1.json", // NOI18N. "inventorybag2.json" // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final CharacterInventoryBag value = instance.loadObject(CharacterInventoryBag.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_MaterialStorage_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(MaterialStorage local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/materials/"; // NOI18N. final String filename = "materialstorage1.json"; // NOI18N. final URL url = getClass().getResource(basecode + filename); assertNotNull(url); final MaterialStorage value = instance.loadObject(MaterialStorage.class, url); assertNotNull(value); assertEquals(38, value.getId()); assertEquals("Festive Materials", value.getName()); // NOI18N. assertEquals(Collections.unmodifiableSet(new LinkedHashSet(Arrays.asList(36060, 36061, 36059, 36041, 38130, 38131, 38132, 38133, 38134, 38135, 43319, 47909, 48807, 48805, 48806))), value.getItems()); } @Test public void testLoadObject_Achievement_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Achievement local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/achievements/"; // NOI18N. final String[] files = { "achievement1.json", // NOI18N. "achievement2.json", // NOI18N. "achievement3.json" // NOI18N. }; final int[] expIds = { 1840, 910, 2258 }; assertEquals(files.length, expIds.length); IntStream.range(0, files.length).forEach(index -> { final String file = files[index]; final URL url = getClass().getResource(basecode + file); assertNotNull(url); try { final Achievement value = instance.loadObject(Achievement.class, url); assertNotNull(value); final int expId = expIds[index]; assertEquals(expId, value.getId()); } catch (IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_DailyAchievement_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(DailyAchievement local)"); // NOI18N. final String baseCode = "/api/web/gw2/mapping/v2/achievements/daily/";// NOI18N. final String[] files = { "achievement1.json", // NOI18N. "achievement2.json" // NOI18N. }; final int[] expIds = { 1984, 1931 }; final DailyAchievementLevelRange[] expLevels = { DailyAchievementLevelRange.ALL_LEVELS, new DailyAchievementLevelRange() { @Override public boolean equals(Object obj) { return equals((DailyAchievementLevelRange) obj); } @Override public int getMin() { return 11; } @Override public int getMax() { return 80; } }}; assertEquals(files.length, expIds.length); assertEquals(files.length, expLevels.length); IntStream.range(0, files.length).forEach(index -> { final String file = files[index]; final URL url = getClass().getResource(baseCode + file); assertNotNull(url); try { final DailyAchievement value = instance.loadObject(DailyAchievement.class, url); assertNotNull(value); final int expId = expIds[index]; assertEquals(expId, value.getId()); final DailyAchievementLevelRange expLevel = expLevels[index]; assertEquals(expLevel, value.getLevel()); } catch (IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_AccountAchievement_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(AccountAchievement local)"); // NOI18N. final String baseCode = "/api/web/gw2/mapping/v2/account/achievements/";// NOI18N. final String[] files = { "achievement1.json", // NOI18N. "achievement2.json", // NOI18N. "achievement3.json" // NOI18N. }; final int[] expIds = { 1, 202, 1653 }; final OptionalInt[] expCurrents = { OptionalInt.of(1), OptionalInt.empty(), OptionalInt.of(4) }; final OptionalInt[] expMaxs = { OptionalInt.of(1000), OptionalInt.empty(), OptionalInt.of(30) }; final boolean[] expDones = { false, true, false }; final Set[] expBits = { Collections.EMPTY_SET, Collections.EMPTY_SET, Collections.unmodifiableSet(new LinkedHashSet(Arrays.asList(2, 3, 4, 5))) }; assertEquals(files.length, expIds.length); assertEquals(files.length, expCurrents.length); assertEquals(files.length, expMaxs.length); assertEquals(files.length, expDones.length); assertEquals(files.length, expBits.length); IntStream.range(0, files.length).forEach(index -> { final String file = files[index]; final URL url = getClass().getResource(baseCode + file); assertNotNull(url); try { final api.web.gw2.mapping.v2.account.achievements.Achievement value = instance.loadObject(api.web.gw2.mapping.v2.account.achievements.Achievement.class, url); assertNotNull(value); final int expId = expIds[index]; assertEquals(expId, value.getId()); final OptionalInt expCurrent = expCurrents[index]; assertEquals(expCurrent, value.getCurrent()); final OptionalInt expMax = expMaxs[index]; assertEquals(expMax, value.getMax()); final boolean expDone = expDones[index]; assertEquals(expDone, value.isDone()); final Set<Integer> expBit = expBits[index]; assertEquals(expBit, value.getBits()); } catch (IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadPage_Integer_Local() throws IOException { System.out.println("loadPage(integer local)"); // NOI18N. final int expPageTotal = 1; final int expPageSize = 10; final int expResultCount = expPageSize; final int expResultTotal = expPageSize; final URL url = getClass().getResource("test_page1.json"); // NOI18N. assertNotNull(url); final PageResult<Integer> value = instance.loadPage(Integer.class, url); assertNotNull(value); assertEquals(expPageTotal, value.getPageTotal()); assertEquals(expPageSize, value.getPageSize()); assertEquals(expResultCount, value.getResultCount()); assertEquals(expResultTotal, value.getResultTotal()); final Iterator<Integer> iterator = value.iterator(); IntStream.range(0, expPageSize).forEach(index -> { final int expResult = index; final int result = iterator.next(); assertEquals(expResult, result); }); } @Test public void testLoadPage_BankSlot_Local() throws IOException { System.out.println("loadPage(BankSlot local)"); // NOI18N. final boolean[] expIsNulls = { false, true, true, false, true, false }; final String baseCode = "/api/web/gw2/mapping/v2/account/bank/"; // NOI18N. String filename = "bankresponse.json"; // NOI18N. final URL url = getClass().getResource(baseCode + filename); assertNotNull(url); final PageResult<BankSlot> value = instance.loadPage(BankSlot.class, url); // value.stream().forEach(System.out::println); assertNotNull(value); final int expPageSize = expIsNulls.length; assertEquals(expPageSize, value.getResultCount()); final Iterator<BankSlot> iterator = value.iterator(); IntStream.range(0, expPageSize).forEach(index -> { final BankSlot result = iterator.next(); final boolean expIsNull = expIsNulls[index]; final boolean isNull = result == null; assertEquals(expIsNull, isNull); }); } @Test public void testLoadRuntimeObject_TraitFact_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(TraitFact local)"); // NOI18N. final String baseCode = "/api/web/gw2/mapping/v2/traits/";// NOI18N. final String[] files = { "fact-attributeadjust.json", // NOI18N. "fact-buff.json", // NOI18N. "fact-buffconversion.json", // NOI18N. "fact-combofield.json", // NOI18N. "fact-combofinisher.json", // NOI18N. "fact-damage.json", // NOI18N. "fact-distance.json", // NOI18N. "fact-nodata.json", // NOI18N. "fact-number.json", // NOI18N. "fact-percent.json", // NOI18N. "fact-prefixedbuff.json", // NOI18N. "fact-radius.json", // NOI18N. "fact-range.json", // NOI18N. "fact-recharge.json", // NOI18N. "fact-time.json", // NOI18N. "fact-unblockable.json", // NOI18N. }; IntStream.range(0, files.length).forEach(index -> { System.out.println(files[index]); final String file = files[index]; final URL url = getClass().getResource(baseCode + file); assertNotNull(url); try { final TraitFact value = instance.loadRuntimeObject("type", "api.web.gw2.mapping.v2.traits.Trait%sFact", url); assertNotNull(value); } catch (IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Skin_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Skin local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/skins/"; // NOI18N. final String[] filenames = { "skin1.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Skin value = instance.loadObject(Skin.class, url); assertNotNull(value); assertEquals(10, value.getId()); assertEquals("Seer Pants", value.getName()); assertEquals(SkinType.ARMOR, value.getType()); assertEquals(URLReference.of("https://render.guildwars2.com/file/1920ACA302E656B60C38605521760351F147809D/61088.png"), value.getIcon()); assertEquals(Collections.unmodifiableSet(new LinkedHashSet(Arrays.asList(SkinFlag.SHOW_IN_WARDROBE))), value.getFlags()); assertTrue(value.getDetails().isPresent()); assertEquals(JsonpSkinArmorDetails.class, value.getDetails().get().getClass()); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Objective_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Objective local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/wvw/objectives/"; // NOI18N. final String[] filenames = { "objective1.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Objective value = instance.loadObject(Objective.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Match_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Objective local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/wvw/matches/"; // NOI18N. final String[] filenames = { "match1.json", // NOI18N. }; final String[] expIds = { "1-3" // NOI18N. }; assertEquals(filenames.length, expIds.length); IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Match value = instance.loadObject(Match.class, url); assertNotNull(value); final String expId = expIds[index]; assertEquals(expId, value.getId()); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Recipe_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Recipe local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/recipes/"; // NOI18N. final String[] filenames = { "recipe1.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Recipe value = instance.loadObject(Recipe.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadRuntimeObject_ItemDetails_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(ItemDetails local)"); // NOI18N. final String classPattern = "api.web.gw2.mapping.v2.items.Item%sDetails"; final String baseCode = "/api/web/gw2/mapping/v2/items/";// NOI18N. // @todo Need more test files. final String[] files = { "details-armor.json", // NOI18N. "details-back.json", // NOI18N. "details-bag.json", // NOI18N. "details-consumable.json", // NOI18N. "details-container.json", // NOI18N. "details-gathering.json", // NOI18N. "details-gizmo.json", // NOI18N. //"details-minipet.json", // NOI18N. "details-tool.json", // NOI18N. "details-trinket.json", // NOI18N. "details-upgradecomponent.json", // NOI18N. "details-weapon.json", // NOI18N. }; // As the type is determined in the parent object we cannot use loadRuntimeObject() for this test. final ItemType[] expItemTypes = { ItemType.ARMOR, ItemType.BACK, ItemType.BAG, ItemType.CONSUMABLE, ItemType.CONTAINER, ItemType.GATHERING, ItemType.GIZMO, //ItemType.MINI_PET, ItemType.TOOL, ItemType.TRINKET, ItemType.UPGRADE_COMPONENT, ItemType.WEAPON }; assertEquals(files.length, expItemTypes.length); IntStream.range(0, files.length).forEach(index -> { System.out.println(files[index]); final String file = files[index]; final URL url = getClass().getResource(baseCode + file); assertNotNull(url); final ItemType expItemType = expItemTypes[index]; final String token = JsonpUtils.INSTANCE.javaEnumToJavaClassName(expItemType); final String className = String.format(classPattern, token); try { final Class<? extends ItemDetails> detailsClass = (Class<? extends ItemDetails>) Class.forName(className); final ItemDetails value = instance.loadObject(detailsClass, url); assertNotNull(value); assertEquals(expItemType, value.getItemType()); } catch (Exception ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Currency_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Currency local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/currencies/"; // NOI18N. final String[] filenames = { "currency1.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Currency value = instance.loadObject(Currency.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Continent_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Continent local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/continents/"; // NOI18N. final String[] filenames = { "continent1.json", // NOI18N. "continent2.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Continent value = instance.loadObject(Continent.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Map_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Map local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/maps/"; // NOI18N. final String[] filenames = { "map1.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Map value = instance.loadObject(Map.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Item_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Item local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/items/"; // NOI18N. final String[] filenames = { "item01.json", // NOI18N. "item02.json", // NOI18N. "item03.json", // NOI18N. "item04.json", // NOI18N. "item05.json", // NOI18N. "item06.json", // NOI18N. "item07.json", // NOI18N. "item08.json", // NOI18N. "item09.json", // NOI18N. "item10.json", // NOI18N. "item11.json", // NOI18N. "item12.json", // NOI18N. "item13.json", // NOI18N. "item14.json", // NOI18N. "item15.json", // NOI18N. "item16.json", // NOI18N. "item17.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Item value = instance.loadObject(Item.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Game_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Game local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/pvp/games/"; // NOI18N. final String[] filenames = { "game01.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Game value = instance.loadObject(Game.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Stat_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Stat local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/pvp/stats/"; // NOI18N. final String[] filenames = { "stat01.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Stat value = instance.loadObject(Stat.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Season_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Season local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/pvp/seasons/"; // NOI18N. final String[] filenames = { "season01.json", // NOI18N. "season02.json", // NOI18N. "season05.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Season value = instance.loadObject(Season.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_LeaderboardEntry_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(LeaderboardEntry local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/pvp/seasons/leaderboards/"; // NOI18N. final String[] filenames = { "leaderboard01.json", // NOI18N. "leaderboard02.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final LeaderboardEntry value = instance.loadObject(LeaderboardEntry.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Standing_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Standing local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/pvp/standings/"; // NOI18N. final String[] filenames = { "standing01.json", // NOI18N. "standing02.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Standing value = instance.loadObject(Standing.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_LogEvent_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(LogEvent local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/guild/id/log/"; // NOI18N. final String[] filenames = { "eventlog01.json", // NOI18N. "eventlog02.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final LogEvent value = instance.loadObject(LogEvent.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Stash_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Stash local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/guild/id/stash/"; // NOI18N. final String[] filenames = { "stash01.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Stash value = instance.loadObject(Stash.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Treasury_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Treasury local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/guild/id/treasury/"; // NOI18N. final String[] filenames = { "treasury01.json", // NOI18N. "treasury02.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Treasury value = instance.loadObject(Treasury.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Team_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Team local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/guild/id/teams/"; // NOI18N. final String[] filenames = { "team01.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Team value = instance.loadObject(Team.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_SharedInventory_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(SharedInventory local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/account/inventory/"; // NOI18N. final String[] filenames = { "inventories.json", // NOI18N. }; final int[] expectedIds = {44602, 20321}; final int[] expectedCounts = {1, 1}; assertEquals(expectedIds.length, expectedCounts.length); IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Collection<SharedInventory> value = instance.loadObjectArray(SharedInventory.class, url); assertEquals(expectedIds.length, value.size()); final Iterator<SharedInventory> it = value.iterator(); IntStream.range(0, expectedIds.length) .forEach(i -> { final SharedInventory sharedInventory = it.next(); assertEquals(expectedIds[i], sharedInventory.getId()); assertEquals(expectedCounts[i], sharedInventory.getCount()); assertEquals(CharacterInventoryBinding.ACCOUNT, sharedInventory.getBinding()); }); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Upgrade_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Upgrade local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/guild/upgrades/"; // NOI18N. final String[] filenames = { "upgrade01.json", // NOI18N. "upgrade02.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Upgrade value = instance.loadObject(Upgrade.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Profession_Local() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Profession local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/professions/"; // NOI18N. final String[] filenames = { "profession01.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Profession value = instance.loadObject(Profession.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_TitlesLocal() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Titles local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/titles/"; // NOI18N. final String[] filenames = { "titles.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Collection<Title> value = instance.loadObjectArray(Title.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_LegendsLocal() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Legends local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/legends/"; // NOI18N. final String[] filenames = { "legends.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Collection<Legend> value = instance.loadObjectArray(Legend.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_AmuletsLocal() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Amulets local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/pvp/amulets/"; // NOI18N. final String[] filenames = { "amulets.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Collection<Amulet> value = instance.loadObjectArray(Amulet.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_ItemstatsLocal() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Itemstats local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/itemstats/"; // NOI18N. final String[] filenames = { "itemstats.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Collection<Itemstats> value = instance.loadObjectArray(Itemstats.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Finisher() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Finisher local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/finishers/"; // NOI18N. final String[] filenames = { "finisher01.json", // NOI18N. "finisher02.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Finisher value = instance.loadObject(Finisher.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_FinisherUnlock() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(FinisherUnlock local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/account/finishers/"; // NOI18N. final String[] filenames = { "finisherunlocks.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Collection<FinisherUnlock> value = instance.loadObjectArray(FinisherUnlock.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_BackstoryAnswer() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(BackstoryAnswer local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/backstory/answers/"; // NOI18N. final String[] filenames = { "answer1.json", // NOI18N. "answer2.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final BackstoryAnswer value = instance.loadObject(BackstoryAnswer.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_BackstoryQuestion() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(BackstoryQuestion local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/backstory/questions/"; // NOI18N. final String[] filenames = { "question1.json", // NOI18N. "question2.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final BackstoryQuestion value = instance.loadObject(BackstoryQuestion.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Pet() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Pet local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/pets/"; // NOI18N. final String[] filenames = { "pet1.json", // NOI18N. "pet2.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Pet value = instance.loadObject(Pet.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Story() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Story local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/stories/"; // NOI18N. final String[] filenames = { "story1.json", // NOI18N. "story2.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Story value = instance.loadObject(Story.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_StorySeason() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(StorySeason local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/stories/seasons/"; // NOI18N. final String[] filenames = { "season1.json", // NOI18N. "season2.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final StorySeason value = instance.loadObject(StorySeason.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Rank() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Rank local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/wvw/ranks/"; // NOI18N. final String[] filenames = { "rank01.json", // NOI18N. "rank02.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Rank value = instance.loadObject(Rank.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Guild() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Guild local)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/guild/id/"; // NOI18N. final String[] filenames = { "guild01.json", // NOI18N. "guild02.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Guild value = instance.loadObject(Guild.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Cat() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Cat)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/account/home/cats/"; // NOI18N. final String[] filenames = { "cat01.json", // NOI18N. "cat27.json", // NOI18N. }; IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Cat value = instance.loadObject(Cat.class, url); assertNotNull(value); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Dungeon() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Dungeon)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/dungeons/"; // NOI18N. final String[] filenames = { "dungeon01.json", // NOI18N. }; final String[] expIds = {"caudecus_manor"}; // NOI18N. assertEquals(filenames.length, expIds.length); IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Dungeon value = instance.loadObject(Dungeon.class, url); assertNotNull(value); final String expId = expIds[index]; assertEquals(expId, value.getId()); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Glider() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Glider)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/gliders/"; // NOI18N. final String[] filenames = { "glider01.json", // NOI18N. }; final int[] expIds = {1}; assertEquals(filenames.length, expIds.length); IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Glider value = instance.loadObject(Glider.class, url); assertNotNull(value); final int expId = expIds[index]; assertEquals(expId, value.getId()); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_PvpRank() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(PvpRank)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/pvp/ranks/"; // NOI18N. final String[] filenames = { "rank01.json", // NOI18N. "rank02.json", // NOI18N. }; final int[] expIds = { 2, 4,}; assertEquals(filenames.length, expIds.length); IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final PvpRank value = instance.loadObject(PvpRank.class, url); assertNotNull(value); final int expId = expIds[index]; assertEquals(expId, value.getId()); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } @Test public void testLoadObject_Race() throws IOException, InstantiationException, IllegalAccessException, NoSuchFieldException { System.out.println("loadObject(Race)"); // NOI18N. final String basecode = "/api/web/gw2/mapping/v2/races/"; // NOI18N. final String[] filenames = { "race01.json", // NOI18N. }; final String[] expIds = { "Asura",}; assertEquals(filenames.length, expIds.length); IntStream.range(0, filenames.length) .forEach(index -> { final String filename = filenames[index]; final URL url = getClass().getResource(basecode + filename); assertNotNull(url); try { final Race value = instance.loadObject(Race.class, url); assertNotNull(value); final String expId = expIds[index]; assertEquals(expId, value.getId()); } catch (NullPointerException | IOException ex) { fail(ex.getMessage()); } }); } }
package fr.liglab.lcm.internals; import gnu.trove.list.array.TIntArrayList; /** * Itemsets and patterns are represented by classic integer arrays * Aside static utility methods, instanciate it to create arrays without knowing their length beforehand */ public class ItemsetsFactory { // default constructor FTW protected TIntArrayList buffer = new TIntArrayList(); protected int capacity = 50; /** * If you're going big and have an estimation of future array's size... */ public void ensureCapacity(final int c) { buffer.ensureCapacity(c); } public void add(final int i) { buffer.add(i); } /** * Resets the builder by the way * @return an array containing latest items added. */ public int[] get() { if (capacity < buffer.size()) { capacity = buffer.size(); } int[] res = buffer.toArray(); buffer.clear(capacity); return res; } public boolean isEmpty() { return buffer.isEmpty(); } /** * @return a new array concatenating each of its arguments */ public static int[] extend(final int[] pattern, final int extension, final int[] closure) { int[] extended = new int[pattern.length + closure.length + 1]; System.arraycopy(pattern, 0, extended, 0, pattern.length); extended[pattern.length] = extension; System.arraycopy(closure, 0, extended, pattern.length+1, closure.length); return extended; } }
package org.bouncycastle.tls.crypto.impl; import java.io.IOException; import java.security.SecureRandom; import org.bouncycastle.tls.AlertDescription; import org.bouncycastle.tls.ProtocolVersion; import org.bouncycastle.tls.SecurityParameters; import org.bouncycastle.tls.TlsFatalAlert; import org.bouncycastle.tls.TlsUtils; import org.bouncycastle.tls.crypto.TlsCipher; import org.bouncycastle.tls.crypto.TlsCrypto; import org.bouncycastle.tls.crypto.TlsCryptoParameters; import org.bouncycastle.tls.crypto.TlsHMAC; /** * A generic TLS 1.0-1.2 block cipher. This can be used for AES or 3DES for example. */ public class TlsBlockCipher implements TlsCipher { protected final TlsCrypto crypto; protected final TlsCryptoParameters cryptoParams; protected final byte[] randomData; protected final boolean encryptThenMAC; protected final boolean useExplicitIV; protected final boolean acceptExtraPadding; protected final boolean useExtraPadding; protected final TlsBlockCipherImpl decryptCipher, encryptCipher; protected final TlsSuiteMac readMac, writeMac; public TlsBlockCipher(TlsCrypto crypto, TlsCryptoParameters cryptoParams, TlsBlockCipherImpl encryptCipher, TlsBlockCipherImpl decryptCipher, TlsHMAC clientMac, TlsHMAC serverMac, int cipherKeySize) throws IOException { this.cryptoParams = cryptoParams; this.crypto = crypto; this.randomData = cryptoParams.getNonceGenerator().generateNonce(256); SecurityParameters securityParameters = cryptoParams.getSecurityParametersHandshake(); ProtocolVersion negotiatedVersion = securityParameters.getNegotiatedVersion(); this.encryptThenMAC = securityParameters.isEncryptThenMAC(); this.useExplicitIV = TlsImplUtils.isTLSv11(negotiatedVersion); this.acceptExtraPadding = !negotiatedVersion.isSSL(); /* * Don't use variable-length padding with truncated MACs. * * See "Tag Size Does Matter: Attacks and Proofs for the TLS Record Protocol", Paterson, * Ristenpart, Shrimpton. * * TODO[DTLS] Consider supporting in DTLS (without exceeding send limit though) */ this.useExtraPadding = securityParameters.isExtendedPadding() && ProtocolVersion.TLSv10.isEqualOrEarlierVersionOf(negotiatedVersion) && (encryptThenMAC || !securityParameters.isTruncatedHMac()); this.encryptCipher = encryptCipher; this.decryptCipher = decryptCipher; TlsBlockCipherImpl clientCipher, serverCipher; if (cryptoParams.isServer()) { clientCipher = decryptCipher; serverCipher = encryptCipher; } else { clientCipher = encryptCipher; serverCipher = decryptCipher; } int key_block_size = (2 * cipherKeySize) + clientMac.getMacLength() + serverMac.getMacLength(); // From TLS 1.1 onwards, block ciphers don't need IVs from the key_block if (!useExplicitIV) { key_block_size += clientCipher.getBlockSize() + serverCipher.getBlockSize(); } byte[] key_block = TlsImplUtils.calculateKeyBlock(cryptoParams, key_block_size); int offset = 0; clientMac.setKey(key_block, offset, clientMac.getMacLength()); offset += clientMac.getMacLength(); serverMac.setKey(key_block, offset, serverMac.getMacLength()); offset += serverMac.getMacLength(); clientCipher.setKey(key_block, offset, cipherKeySize); offset += cipherKeySize; serverCipher.setKey(key_block, offset, cipherKeySize); offset += cipherKeySize; if (!useExplicitIV) { clientCipher.init(key_block, offset, clientCipher.getBlockSize()); offset += clientCipher.getBlockSize(); serverCipher.init(key_block, offset, serverCipher.getBlockSize()); offset += serverCipher.getBlockSize(); } if (offset != key_block_size) { throw new TlsFatalAlert(AlertDescription.internal_error); } if (cryptoParams.isServer()) { this.writeMac = new TlsSuiteHMac(cryptoParams, serverMac); this.readMac = new TlsSuiteHMac(cryptoParams, clientMac); } else { this.writeMac = new TlsSuiteHMac(cryptoParams, clientMac); this.readMac = new TlsSuiteHMac(cryptoParams, serverMac); } } public int getCiphertextLimit(int plaintextLimit) { int blockSize = encryptCipher.getBlockSize(); int macSize = writeMac.getSize(); int ciphertextLimit = plaintextLimit; // An explicit IV consumes 1 block if (useExplicitIV) { ciphertextLimit += blockSize; } // Leave room for the MAC and (block-aligning) padding ciphertextLimit += useExtraPadding ? 256 : blockSize; if (encryptThenMAC) { ciphertextLimit -= (ciphertextLimit % blockSize); ciphertextLimit += macSize; } else { ciphertextLimit += macSize; ciphertextLimit -= (ciphertextLimit % blockSize); } return ciphertextLimit; } public int getPlaintextLimit(int ciphertextLimit) { int blockSize = encryptCipher.getBlockSize(); int macSize = writeMac.getSize(); int plaintextLimit = ciphertextLimit; // Leave room for the MAC, and require block-alignment if (encryptThenMAC) { plaintextLimit -= macSize; plaintextLimit -= plaintextLimit % blockSize; } else { plaintextLimit -= plaintextLimit % blockSize; plaintextLimit -= macSize; } // Minimum 1 byte of padding --plaintextLimit; // An explicit IV consumes 1 block if (useExplicitIV) { plaintextLimit -= blockSize; } return plaintextLimit; } public byte[] encodePlaintext(long seqNo, short type, int headerAllocation, byte[] plaintext, int offset, int len) throws IOException { int blockSize = encryptCipher.getBlockSize(); int macSize = writeMac.getSize(); int enc_input_length = len; if (!encryptThenMAC) { enc_input_length += macSize; } int padding_length = blockSize - (enc_input_length % blockSize); if (useExtraPadding) { // Add a random number of extra blocks worth of padding int maxExtraPadBlocks = (256 - padding_length) / blockSize; int actualExtraPadBlocks = chooseExtraPadBlocks(crypto.getSecureRandom(), maxExtraPadBlocks); padding_length += actualExtraPadBlocks * blockSize; } int totalSize = len + macSize + padding_length; if (useExplicitIV) { totalSize += blockSize; } byte[] outBuf = new byte[headerAllocation + totalSize]; int outOff = headerAllocation; if (useExplicitIV) { byte[] explicitIV = cryptoParams.getNonceGenerator().generateNonce(blockSize); encryptCipher.init(explicitIV, 0, blockSize); System.arraycopy(explicitIV, 0, outBuf, outOff, blockSize); outOff += blockSize; } int blocks_start = outOff; System.arraycopy(plaintext, offset, outBuf, outOff, len); outOff += len; if (!encryptThenMAC) { byte[] mac = writeMac.calculateMac(seqNo, type, plaintext, offset, len); System.arraycopy(mac, 0, outBuf, outOff, mac.length); outOff += mac.length; } byte padByte = (byte)(padding_length - 1); for (int i = 0; i < padding_length; ++i) { outBuf[outOff++] = padByte; } encryptCipher.doFinal(outBuf, blocks_start, outOff - blocks_start, outBuf, blocks_start); if (encryptThenMAC) { byte[] mac = writeMac.calculateMac(seqNo, type, outBuf, headerAllocation, outOff - headerAllocation); System.arraycopy(mac, 0, outBuf, outOff, mac.length); outOff += mac.length; } if (outOff != outBuf.length) { throw new TlsFatalAlert(AlertDescription.internal_error); } return outBuf; } public byte[] decodeCiphertext(long seqNo, short type, byte[] ciphertext, int offset, int len) throws IOException { int blockSize = decryptCipher.getBlockSize(); int macSize = readMac.getSize(); int minLen = blockSize; if (encryptThenMAC) { minLen += macSize; } else { minLen = Math.max(minLen, macSize + 1); } if (useExplicitIV) { minLen += blockSize; } if (len < minLen) { throw new TlsFatalAlert(AlertDescription.decode_error); } int blocks_length = len; if (encryptThenMAC) { blocks_length -= macSize; } if (blocks_length % blockSize != 0) { throw new TlsFatalAlert(AlertDescription.decryption_failed); } if (encryptThenMAC) { byte[] expectedMac = readMac.calculateMac(seqNo, type, ciphertext, offset, len - macSize); boolean badMac = !constantTimeAreEqual(macSize, expectedMac, 0, ciphertext, offset + len - macSize); if (badMac) { /* * RFC 7366 3. The MAC SHALL be evaluated before any further processing such as * decryption is performed, and if the MAC verification fails, then processing SHALL * terminate immediately. For TLS, a fatal bad_record_mac MUST be generated [2]. For * DTLS, the record MUST be discarded, and a fatal bad_record_mac MAY be generated * [4]. This immediate response to a bad MAC eliminates any timing channels that may * be available through the use of manipulated packet data. */ throw new TlsFatalAlert(AlertDescription.bad_record_mac); } } if (useExplicitIV) { decryptCipher.init(ciphertext, offset, blockSize); offset += blockSize; blocks_length -= blockSize; } decryptCipher.doFinal(ciphertext, offset, blocks_length, ciphertext, offset); // If there's anything wrong with the padding, this will return zero int totalPad = checkPaddingConstantTime(ciphertext, offset, blocks_length, blockSize, encryptThenMAC ? 0 : macSize); boolean badMac = (totalPad == 0); int dec_output_length = blocks_length - totalPad; if (!encryptThenMAC) { dec_output_length -= macSize; byte[] expectedMac = readMac.calculateMacConstantTime(seqNo, type, ciphertext, offset, dec_output_length, blocks_length - macSize, randomData); badMac |= !constantTimeAreEqual(macSize, expectedMac, 0, ciphertext, offset + dec_output_length); } if (badMac) { throw new TlsFatalAlert(AlertDescription.bad_record_mac); } return TlsUtils.copyOfRangeExact(ciphertext, offset, offset + dec_output_length); } protected int checkPaddingConstantTime(byte[] buf, int off, int len, int blockSize, int macSize) { int end = off + len; byte lastByte = buf[end - 1]; int padlen = lastByte & 0xff; int totalPad = padlen + 1; int dummyIndex = 0; byte padDiff = 0; int totalPadLimit = Math.min(acceptExtraPadding ? 256 : blockSize, len - macSize); if (totalPad > totalPadLimit) { totalPad = 0; } else { int padPos = end - totalPad; do { padDiff |= (buf[padPos++] ^ lastByte); } while (padPos < end); dummyIndex = totalPad; if (padDiff != 0) { totalPad = 0; } } // Run some extra dummy checks so the number of checks is always constant { byte[] dummyPad = randomData; while (dummyIndex < 256) { padDiff |= (dummyPad[dummyIndex++] ^ lastByte); } // Ensure the above loop is not eliminated dummyPad[0] ^= padDiff; } return totalPad; } protected int chooseExtraPadBlocks(SecureRandom r, int max) { // return r.nextInt(max + 1); int x = r.nextInt(); int n = lowestBitSet(x); return Math.min(n, max); } protected boolean constantTimeAreEqual(int len, byte[] a, int aOff, byte[] b, int bOff) { int d = 0; for (int i = 0; i < len; ++i) { d |= (a[aOff + i] ^ b[bOff + i]); } return 0 == d; } protected int lowestBitSet(int x) { if (x == 0) { return 32; } int n = 0; while ((x & 1) == 0) { ++n; x >>= 1; } return n; } }
package fr.netixx.AutoTopo.statistics; import au.com.bytecode.opencsv.CSVWriter; import fr.netixx.AutoTopo.agents.IScope; import fr.netixx.AutoTopo.agents.Scope; import java.io.BufferedWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.OpenOption; import java.nio.file.Path; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; public class TimeScope extends AbstractStatistic { private static boolean enabled = true; private static final String[] headers = new String[]{"scope", "create", "delete", "avg","std", "min", "max"}; private SortedMap<IScope, ConnectionsRecorder> connectionMap = new TreeMap<>(); private RecordFilter<IScope> filter = null; public TimeScope(String name) { super(name, headers); } public TimeScope(String name, RecordFilter<IScope> filter) { super(name, headers); this.filter = filter; } public void record(Double time, IScope el) { if (enabled) { if (filter != null && filter.filter(el)) return; if (!connectionMap.containsKey(el)) { connectionMap.put(el, new ConnectionsRecorder(1, time)); } else { connectionMap.get(el).recordConnectionNumber(1, time); } } // el.getConnectionManager().getConnectedChildren().size(); } @Override public void toCsv(Path csv) { OpenOption[] opts = new OpenOption[]{ // StandardOpenOption .WRITE, StandardOpenOption.CREATE }; try (BufferedWriter writer = Files.newBufferedWriter(csv, Charset.forName("UTF-8"), opts)) { CSVWriter csvW = new CSVWriter(writer, ';'); csvW.writeNext(this.getHeader()); for (Map.Entry<IScope, ConnectionsRecorder> entry : connectionMap.entrySet()) { csvW.writeNext(new String[]{"" + entry.getKey().getId(), "" + entry.getValue().createTime, "" + entry.getValue().destroyTime, "" + entry.getValue().getAvg(), "" + entry.getValue().getStd(), "" + entry.getValue().getMin(), "" + entry.getValue().getMax()}); } csvW.close(); } catch (IOException e) { e.printStackTrace(); } } private class ConnectionsRecorder { double createTime; double destroyTime; double currentTime; int curConn; int n = 0; int max = 0; int min = 0; double m = 0; double s = 0; ConnectionsRecorder(int nConnections, double time) { this.createTime = time; currentTime = time; curConn = 0; n = 1; max = nConnections; min = nConnections; recordConnectionNumber(nConnections, time); } void recordConnectionNumber(int nConnections, double time) { destroyTime = time; if (time > currentTime) { //start new max = Math.max(curConn, max); min = Math.min(curConn, min); double tmpM = m; m += (curConn - tmpM) / n; s += (curConn - tmpM) * (curConn - m); n++; curConn = nConnections; currentTime = time; } else { curConn += nConnections; } } double getAvg() { return m; } double getVariance() { return s / (n - 1); } double getStd() { return Math.sqrt(getVariance()); } int getMax() { return max; } int getMin() { return min; } } }
package ge.edu.freeuni.sdp.xo.rooms.service; import static org.junit.Assert.*; import ge.edu.freeuni.sdp.xo.rooms.service.PingService; import javax.ws.rs.core.Application; import javax.ws.rs.core.Response; import org.junit.Test; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.test.JerseyTest; public class TestPingService extends JerseyTest{ @Override protected Application configure() { return new ResourceConfig(PingService.class); } @Test public void testGet() { Response actual = target("webapi/ping").request().get(); assertEquals(Response.Status.OK.getStatusCode(),actual.getStatus()); } }
package gg.uhc.uhc.modules.portals; import com.google.common.base.Joiner; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import gg.uhc.uhc.modules.DisableableModule; import gg.uhc.uhc.modules.ModuleRegistry; import gg.uhc.uhc.modules.team.FunctionalUtil; import org.bukkit.*; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityPortalEvent; import org.bukkit.event.player.PlayerPortalEvent; import java.util.Set; public class NetherModule extends DisableableModule implements Listener { protected static final String ICON_NAME = "Nether"; public NetherModule() { this.iconName = ICON_NAME; this.icon.setType(Material.NETHER_STALK); this.icon.setWeight(ModuleRegistry.CATEGORY_WORLD); } @Override public void rerender() { super.rerender(); if (isEnabled()) { icon.setLore("Travelling to the nether is enabled"); } else { icon.setLore("Travelling to the nether is disabled"); } } @Override public void onDisable() { Set<OfflinePlayer> players = Sets.newHashSet(); Set<String> worlds = Sets.newHashSet(); for (World world : Bukkit.getWorlds()) { if (world.getEnvironment() == World.Environment.NETHER) { worlds.add(world.getName()); players.addAll(world.getPlayers()); } } if (players.size() == 0) return; Joiner joiner = Joiner.on(", "); String playerNames = joiner.join(Iterables.transform(players, FunctionalUtil.PLAYER_NAME_FETCHER)); String worldNames = joiner.join(worlds); String message = ChatColor.DARK_GRAY + "The player/s [" + playerNames + "] are within the nether world/s: [" + worldNames + "]."; Bukkit.getConsoleSender().sendMessage(message); for (Player player : Bukkit.getOnlinePlayers()) { if (player.hasPermission("uhc.broadcast.netherdisable")) { player.sendMessage(message); } } } @EventHandler(ignoreCancelled = true) public void on(EntityPortalEvent event) { if (isEnabled()) return; if (event.getTo().getWorld().getEnvironment() == World.Environment.NETHER) event.setCancelled(true); } @EventHandler(ignoreCancelled = true) public void on(PlayerPortalEvent event) { if (isEnabled()) return; if (event.getTo().getWorld().getEnvironment() == World.Environment.NETHER) { event.setCancelled(true); event.getPlayer().sendMessage(ChatColor.RED + "The nether is disabled"); } } @Override protected boolean isEnabledByDefault() { return true; } }
package hudson.plugins.dry.parser; import hudson.plugins.analysis.util.model.AbstractAnnotation; import hudson.plugins.analysis.util.model.FileAnnotation; import hudson.plugins.analysis.util.model.Priority; import hudson.plugins.dry.Messages; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.lang.StringUtils; import de.java2html.converter.JavaSource2HTMLConverter; import de.java2html.javasource.JavaSource; import de.java2html.javasource.JavaSourceParser; import de.java2html.options.JavaSourceConversionOptions; import de.java2html.util.IllegalConfigurationException; import edu.umd.cs.findbugs.annotations.SuppressWarnings; /** * A serializable Java Bean class representing a duplicate code warning. * <p> * Note: this class has a natural ordering that is inconsistent with equals. * </p> * * @author Ulli Hafner */ public class DuplicateCode extends AbstractAnnotation { /** Unique identifier of this class. */ private static final long serialVersionUID = -6231614169627992548L; /** Origin of the annotation. */ public static final String ORIGIN = "dry"; /** The links to the other code duplications. */ @SuppressWarnings("Se") private final Set<DuplicateCode> links = new HashSet<DuplicateCode>(); /** The duplicate source code fragment. */ private String sourceCode; /** * Creates a new instance of {@link DuplicateCode}. * * @param priority * the priority of the warning * @param firstLine * the starting line of the duplication * @param numberOfLines * total number of duplicate lines * @param fileName * name of the file that contains the duplication */ public DuplicateCode(final Priority priority, final int firstLine, final int numberOfLines, final String fileName) { super(priority, Messages.DRY_Warning_Message(numberOfLines), firstLine, firstLine + numberOfLines - 1, StringUtils.EMPTY, Messages.DRY_Warning_Type()); setOrigin(ORIGIN); setFileName(fileName); } /** {@inheritDoc} */ @Override public String getType() { return Messages.DRY_Warning_Type(); } /** {@inheritDoc} */ @Override public String getMessage() { return Messages.DRY_Warning_Message(size()); } /** * Returns the total number of duplicate lines. * * @return the number of duplicate lines */ public int getNumberOfLines() { return getLineRanges().iterator().next().getEnd() - getPrimaryLineNumber() + 1; } /** * Returns the total number of duplicate lines. * * @return the number of duplicate lines */ public int size() { return getNumberOfLines(); } /** * Returns the total number of duplicate lines. * * @return the number of duplicate lines */ public int length() { return getNumberOfLines(); } /** {@inheritDoc} */ public String getToolTip() { StringBuilder message = new StringBuilder(); message.append("<p>"); message.append(Messages.DRY_Duplications_Header()); message.append("<ul>"); for (DuplicateCode duplication : links) { message.append("<li>"); message.append(String.format("<a href=\"link.%s.%s/#%s\">%s (%s)</a>", getKey(), duplication.getKey(), duplication.getPrimaryLineNumber(), duplication.getShortFileName(), duplication.getPrimaryLineNumber())); message.append("</li>"); } message.append("</ul>"); message.append("</p>"); return message.toString(); } /** * Creates links to the specified collection of other code blocks. * * @param codeBlocks the code blocks to links to */ public void linkTo(final List<DuplicateCode> codeBlocks) { links.addAll(codeBlocks); links.remove(this); } /** * Returns the links to the duplicated code in other files. * * @return the links */ public Collection<DuplicateCode> getLinks() { return Collections.unmodifiableCollection(links); } /** * Returns the duplicate source code fragment. * * @return the duplicate source code fragment */ public String getSourceCode() { return sourceCode; } /** * Returns the duplicate source code fragment as formatted HTML string. * * @return the duplicate source code fragment */ public String getFormattedSourceCode() { try { JavaSource source = new JavaSourceParser().parse(new StringReader(sourceCode)); JavaSource2HTMLConverter converter = new JavaSource2HTMLConverter(); StringWriter writer = new StringWriter(); JavaSourceConversionOptions options = JavaSourceConversionOptions.getDefault(); options.setShowLineNumbers(false); options.setAddLineAnchors(false); converter.convert(source, options, writer); return writer.toString(); } catch (IllegalConfigurationException exception) { return sourceCode; } catch (IOException exception) { return sourceCode; } } /** * Sets the duplicate source code fragment to the specified value. * * @param sourceCode the duplicate code fragment */ public void setSourceCode(final String sourceCode) { this.sourceCode = sourceCode; } /** {@inheritDoc} */ @Override public int hashCode() { int prime = 31; int result = super.hashCode(); result = prime * result + ((sourceCode == null) ? 0 : sourceCode.hashCode()); return result; } /** {@inheritDoc} */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } DuplicateCode other = (DuplicateCode)obj; if (sourceCode == null) { if (other.sourceCode != null) { return false; } } else if (!sourceCode.equals(other.sourceCode)) { return false; } return true; } /** * Returns the link with the specified hash code. * * @param linkHashCode * the hash code of the linked annotation * @return the link with the specified hash code */ public FileAnnotation getLink(final long linkHashCode) { for (FileAnnotation link : links) { if (link.getKey() == linkHashCode) { return link; } } throw new NoSuchElementException("Linked annotation not found: key=" + linkHashCode); } }
package i5.las2peer.httpConnector; import i5.httpServer.HttpServer; import i5.httpServer.HttpsServer; import i5.httpServer.RequestHandler; import i5.las2peer.api.Connector; import i5.las2peer.api.ConnectorException; import i5.las2peer.logging.NodeObserver.Event; import i5.las2peer.p2p.AgentNotKnownException; import i5.las2peer.p2p.Node; import i5.las2peer.security.Agent; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.text.DateFormat; import java.util.Date; /** * Starter class for registering the HTTP connector at the LAS2peer server. * * @author Holger Jan&szlig;en */ public class HttpConnector extends Connector { /* configuration parameters */ private int DEFAULT_HTTP_CONNECTOR_PORT = 8080; protected int httpConnectorPort = DEFAULT_HTTP_CONNECTOR_PORT; private int DEFAULT_HTTPS_CONNECTOR_PORT = 8090; protected int httpsConnectorPort = DEFAULT_HTTPS_CONNECTOR_PORT; private boolean DEFAULT_START_HTTP_CONNECTOR = true; protected boolean startHttpConnector = DEFAULT_START_HTTP_CONNECTOR; private boolean DEFAULT_START_HTTPS_CONNECTOR = false; protected boolean startHttpsConnector = DEFAULT_START_HTTPS_CONNECTOR; private String DEFAULT_SSL_KEYSTORE = "keys/ssl"; protected String sslKeystore = DEFAULT_SSL_KEYSTORE; private String DEFAULT_SSL_KEY_PASSWD = "123456"; protected String sslKeyPasswd = DEFAULT_SSL_KEY_PASSWD; private boolean DEFAULT_ENABLE_FILE_ACCESS = false; protected boolean enableFileAccess = DEFAULT_ENABLE_FILE_ACCESS; private String DEFAULT_FILE_DIRECTORY = "./htdocs"; protected String fileDirectory = DEFAULT_FILE_DIRECTORY; private long DEFAULT_MAX_SESSION_TIMEOUT = 30*60*60 * 1000; // 30 minutes protected long maxSessionTimeoutMS = DEFAULT_MAX_SESSION_TIMEOUT; private long DEFAULT_MIN_SESSION_TIMEOUT = 30 * 1000; // 30 seconds protected long minSessionTimeoutMS = DEFAULT_MIN_SESSION_TIMEOUT; private long DEFAULT_DEFAULT_SESSION_TIMEOUT = 10*60*60 * 1000; // 10 minutes protected long defaultSessionTimeout = DEFAULT_DEFAULT_SESSION_TIMEOUT; private long DEFAULT_DEFAULT_PERSISTENT_OUTDATE_S = 60 * 60 * 24 * 1000; // 1 day protected long defaultPersistentTimeoutMS = DEFAULT_DEFAULT_PERSISTENT_OUTDATE_S; private long DEFAULT_MIN_PERSISTENT_OUTDATE_S = 60 * 60 * 1000; // 1 hour protected long minPersistentTimeoutMS = DEFAULT_MIN_PERSISTENT_OUTDATE_S; private long DEFAULT_MAX_PERSISTENT_OUTDATE_S = 60 * 60 * 1000; // 1 hour protected long maxPersistentTimeoutMS = DEFAULT_MAX_PERSISTENT_OUTDATE_S; private boolean DEFAULT_PRINT_SEC_EXCEPTIONS = false; protected boolean printSecExceptions = DEFAULT_PRINT_SEC_EXCEPTIONS; private int DEFAULT_SOCKET_TIMEOUT = 60*1000; // 1 minute protected int socketTimeout = DEFAULT_SOCKET_TIMEOUT; private String DEFAULT_CROSS_ORIGIN_RESOURCE_DOMAIN = ""; protected String crossOriginResourceDomain = DEFAULT_CROSS_ORIGIN_RESOURCE_DOMAIN; private int DEFAULT_CROSS_ORIGIN_RESOURCE_MAX_AGE = 60; protected int crossOriginResourceMaxAge = DEFAULT_CROSS_ORIGIN_RESOURCE_MAX_AGE; private boolean DEFAULT_ENABLE_CROSS_ORIGIN_RESOURCE_SHARING = false; protected boolean enableCrossOriginResourceSharing = DEFAULT_ENABLE_CROSS_ORIGIN_RESOURCE_SHARING; private boolean DEFAULT_PREFER_LOCAL_SERVICES = true; protected boolean preferLocalServices = DEFAULT_PREFER_LOCAL_SERVICES; private HttpServer http; private HttpsServer https; private Node myNode = null; private String DEFAULT_LOGFILE = "log/httpConnector.log"; private PrintStream logStream = null; private DateFormat dateFormat = DateFormat.getDateTimeInstance(); /** * create a new HTTP connector instance. * @throws FileNotFoundException */ public HttpConnector () throws FileNotFoundException { setFieldValues(); if ( enableFileAccess ) System.out.println ( "HttpConnector: Warning - File Access is enabled!"); } /** * set the log file for this connector * * @param filename * @throws FileNotFoundException */ public void setLogFile ( String filename) throws FileNotFoundException { // auto create log directory if it doesn't exist new File(filename.substring(0, filename.lastIndexOf(File.separator))).mkdirs(); setLogStream ( new PrintStream ( new FileOutputStream ( filename, true ))); } /** * set the port for the HTTP connector to listen to * * @param port */ public void setPort ( int port ) { if ( port < 80 ) throw new IllegalArgumentException ( "illegal port number: " + port ); if ( myNode != null ) throw new IllegalStateException ( "change of port only before startup!"); httpConnectorPort = port; } /** * set the port for the HTTP connector to listen to for the secure line * * @param port */ public void setHttpsPort ( int port ) { if ( port < 80 ) throw new IllegalArgumentException ( "illegal port number: " + port ); if ( myNode != null ) throw new IllegalStateException ( "change of port only before startup!"); httpsConnectorPort = port; } /** * set the socket timeout for the underlying http server * (only at configuration not during runtim) * @param timeoutInMs */ public void setSocketTimeout ( int timeoutInMs ) { socketTimeout = timeoutInMs; } /** * set a stream to log all messages to * * @param stream */ public void setLogStream ( PrintStream stream ) { logStream = stream; } @Override public void start ( Node node ) throws ConnectorException { if ( ! startHttpConnector && ! startHttpsConnector ) throw new ConnectorException ( "either the http connector of the https connector have to be started!" ); if ( logStream == null) try { setLogFile ( DEFAULT_LOGFILE ); } catch (FileNotFoundException e) { throw new ConnectorException ( "cannot initialize standard log file at " + DEFAULT_LOGFILE, e); } myNode = node; System.setProperty( "http-connector.printSecExceptions", ""+printSecExceptions ); // enable file access ? if ( enableFileAccess && fileDirectory != null ) { System.setProperty( "las.http.fileAccess" , "true" ); System.setProperty ( "las.http.fileAccessDir", fileDirectory ); } if ( startHttpConnector ) { // start the HTTP listener if (enableCrossOriginResourceSharing) { http = new HttpServer (HttpConnectorRequestHandler.class.getName(), httpConnectorPort, crossOriginResourceDomain, crossOriginResourceMaxAge); } else http = new HttpServer (HttpConnectorRequestHandler.class.getName(), httpConnectorPort); http.setSocketTimeout( socketTimeout ); http.start(); // wait for the server to start RequestHandler handler; do { try { Thread.sleep( 500 ); } catch (InterruptedException e) { throw new ConnectorException ( "Startup has been interrupted!", e); } handler = http.getHandler(); } while ( handler == null ); ((HttpConnectorRequestHandler) handler).setConnector( this ); logMessage("Http-Connector running on port " + httpConnectorPort); } if ( startHttpsConnector ) { if (enableCrossOriginResourceSharing) https = new HttpsServer ( sslKeystore, sslKeyPasswd, RequestHandler.class.getName(), httpsConnectorPort, crossOriginResourceDomain, crossOriginResourceMaxAge); else https = new HttpsServer ( sslKeystore, sslKeyPasswd, HttpConnectorRequestHandler.class.getName(), httpsConnectorPort ); https.setSocketTimeout( socketTimeout ); https.start(); logMessage("Https-Connector running on port " + httpConnectorPort); } } @Override public void stop () throws ConnectorException { // stop the listener if ( http != null ) http.stopServer(); if ( https != null ) https.stopServer(); try { if ( http != null ) { http.join (); logMessage("Http-Connector has been stopped"); } if ( https != null ) { https.join (); logMessage("Https-Connector has been stopped"); } } catch (InterruptedException e) { logError("Joining has been interrupted!"); } this.myNode = null; } /** * send an interrupt to all sub servers * (mainly for hard test shutdown) */ public void interrupt() { if ( http != null ) http.interrupt(); if ( https != null) https.interrupt(); System.out.println ( "interrupted!"); } /** * get the node, this connector is running at / for * * @return the Las2Peer node of this connector */ public Node getL2pNode () { return myNode; } /** * get a timeout value for a suggested timeout (e.g. given by the remote user) * based on the set minimal an maximal timeout values * * e.g. a getSessionTimeout(0) always gives the minimal session timeout value * * @param suggested * @return the session time out */ long getSessionTimeout ( long suggested ) { if ( suggested < minSessionTimeoutMS ) suggested = minSessionTimeoutMS; if ( suggested > maxSessionTimeoutMS ) suggested = maxSessionTimeoutMS; return suggested; } /** * get the default timeout for remote sessions * @return the default session timeout */ long getDefaultSessionTimeout () { return defaultSessionTimeout; } /** * * @param suggested * @return the persistent session timeout */ long getPersistentSessionTimeout ( long suggested ) { if ( suggested < minPersistentTimeoutMS) suggested = minPersistentTimeoutMS; if ( suggested > maxPersistentTimeoutMS) suggested = maxPersistentTimeoutMS; return suggested; } /** * get the default timeout for persistent sessions * * @return the default timeout */ long getDefaultPersistentTimeout () { return defaultPersistentTimeoutMS; } /** * Logs a message. * * @param message */ void logMessage (String message) { logStream.println( dateFormat.format ( new Date() ) + "\t" + message); myNode.observerNotice(Event.HTTP_CONNECTOR_MESSAGE, myNode.getNodeId(), message); } /** * Logs a session creation. * * @param message */ void logSessionOpen (String message) { logStream.println( dateFormat.format ( new Date() ) + "\t" + message); myNode.observerNotice(Event.HTTP_CONNECTOR_SESSION_START, myNode.getNodeId(), message); } /** * Logs a session closing. * * @param message */ void logSessionClose (String message) { logStream.println( dateFormat.format ( new Date() ) + "\t" + message); myNode.observerNotice(Event.HTTP_CONNECTOR_SESSION_END, myNode.getNodeId(), message); } /** * Logs a request. * * @param message */ void logRequest (String request) { logStream.println( dateFormat.format ( new Date() ) + "\t Request:" + request); int lastServiceClassNamePosition = request.lastIndexOf("/"); if(lastServiceClassNamePosition > 0){ String serviceClass = request.substring(1, lastServiceClassNamePosition); Agent service = null; try { service = myNode.getServiceAgent(serviceClass); } catch (AgentNotKnownException e) { // Should be known.. e.printStackTrace(); } myNode.observerNotice(Event.HTTP_CONNECTOR_REQUEST, myNode.getNodeId(), service, request); } //Not a service call else{ myNode.observerNotice(Event.HTTP_CONNECTOR_REQUEST, myNode.getNodeId(), request); } } /** * Logs an error. * * @param error */ void logError (String error) { logStream.println( dateFormat.format ( new Date() ) + "\t Error: " + error); myNode.observerNotice(Event.HTTP_CONNECTOR_ERROR, myNode.getNodeId(), error); } /** * * @return true, if local running versions of services are preferred before broadcasting */ boolean preferLocalServices () { return preferLocalServices; } }
package soot.jimple.internal; import soot.*; public abstract class AbstractFloatBinopExpr extends AbstractBinopExpr { public Type getType() { Value op1 = op1Box.getValue(); Value op2 = op1Box.getValue(); Type op1t = op1.getType(); Type op2t = op2.getType(); if((op1t.equals(IntType.v()) || op1t.equals(ByteType.v()) || op1t.equals(ShortType.v()) || op1t.equals(CharType.v()) || op1t.equals(BooleanType.v())) && (op2t.equals(IntType.v()) || op2t.equals(ByteType.v()) || op2t.equals(ShortType.v()) || op2t.equals(CharType.v()) || op2t.equals(BooleanType.v()))) return IntType.v(); else if(op1t.equals(LongType.v()) || op2t.equals(LongType.v())) return LongType.v(); else if(op1t.equals(DoubleType.v()) || op2t.equals(DoubleType.v())) return DoubleType.v(); else if(op1t.equals(FloatType.v()) || op2t.equals(FloatType.v())) return FloatType.v(); else return UnknownType.v(); } }
package org.sagebionetworks.bridge.models.accounts; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.Set; import org.junit.Test; import org.sagebionetworks.bridge.Roles; import org.sagebionetworks.bridge.json.BridgeObjectMapper; import com.google.common.collect.Sets; public class UserTest { @Test public void testHealthCodeEncryption() throws IOException { User user = new User(); user.setEmail("userEmail"); user.setId("userId"); user.setHealthCode("123abc"); String userSer = BridgeObjectMapper.get().writeValueAsString(user); assertNotNull(userSer); assertFalse("Health code should have been encrypted in the serialized string.", userSer.toLowerCase().contains("123abc")); User userDe = BridgeObjectMapper.get().readValue(userSer, User.class); assertNotNull(userDe); assertEquals("123abc", userDe.getHealthCode()); } @Test public void userIsInRole() { User user = new User(); user.setRoles(Sets.newHashSet(Roles.ADMIN, Roles.DEVELOPER)); assertTrue(user.isInRole(Roles.DEVELOPER)); assertFalse(user.isInRole((Roles)null)); } @Test public void userIsInRoleSet() { User user = new User(); user.setRoles(Sets.newHashSet(Roles.ADMIN, Roles.DEVELOPER)); assertTrue(user.isInRole(Roles.ADMINISTRATIVE_ROLES)); assertFalse(user.isInRole((Set<Roles>)null)); user = new User(); assertFalse(user.isInRole(Roles.ADMINISTRATIVE_ROLES)); } }
package info.iconmaster.typhon.util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; import info.iconmaster.typhon.antlr.TyphonParser.ExprContext; import info.iconmaster.typhon.compiler.Instruction; import info.iconmaster.typhon.compiler.Instruction.OpCode; import info.iconmaster.typhon.compiler.Label; import info.iconmaster.typhon.compiler.Scope; import info.iconmaster.typhon.compiler.TyphonCompiler; import info.iconmaster.typhon.compiler.Variable; import info.iconmaster.typhon.errors.WriteOnlyError; import info.iconmaster.typhon.model.Field; import info.iconmaster.typhon.model.Function; import info.iconmaster.typhon.model.MemberAccess; import info.iconmaster.typhon.model.Parameter; import info.iconmaster.typhon.model.TemplateArgument; import info.iconmaster.typhon.model.libs.CorePackage; import info.iconmaster.typhon.types.TemplateType; import info.iconmaster.typhon.types.Type; import info.iconmaster.typhon.types.TypeRef; import info.iconmaster.typhon.util.LookupUtils.FuncArgMap; import info.iconmaster.typhon.util.LookupUtils.LookupElement.AccessType; import info.iconmaster.typhon.util.LookupUtils.LookupPath.Subject; /** * This class contains functions suitable for doing lookup for expressions in dot-linked form. * @author iconmaster * */ public class LookupUtils { private LookupUtils() {} /** * A single element in a chain of names to look up. * Contains data such as the source and raw template. * * @author iconmaster * */ public static class LookupElement { /** * The name that will be looked up. */ String name; /** * The template arguments that was supplied with this name, if any. */ List<TemplateArgument> template = new ArrayList<>(); /** * The source this portion of lookup came from. */ SourceInfo source; /** * What connector joins this element to the last one. May be null. */ AccessType prefix; /** * The type of connector that was placed between two elements. * * @author iconmaster * */ public static enum AccessType { /** * Normal access notation, '.'. Standard access of a field, subpackage, etc. */ DOT, /** * Call-chaining notation, '..'. Like '.', but will return the value it accessed instead of what it returns itself. */ NULLABLE_DOT, /** * Nullable notation, '.?'. Like '.', but returns null instead if what it is accessing is null. */ DOUBLE_DOT; /** * Creates an AccessType from a String that represents it. * * @param s * @return */ public static AccessType get(String s) { switch (s) { case ".": return DOT; case "?.": return NULLABLE_DOT; case "..": return DOUBLE_DOT; default: throw new IllegalArgumentException("Unknown access type: "+s); } } } public LookupElement(String name, SourceInfo source, AccessType prefix) { this.name = name; this.source = source; this.prefix = prefix; } public LookupElement(String name, SourceInfo source, AccessType prefix, List<TemplateArgument> template) { this.name = name; this.template.addAll(template); this.source = source; this.prefix = prefix; } public LookupElement(String name, SourceInfo source, AccessType prefix, TemplateArgument... template) { this.name = name; this.template.addAll(Arrays.asList(template)); this.source = source; this.prefix = prefix; } @Override public String toString() { StringBuilder sb = new StringBuilder("LookupElement("); sb.append(name); if (!template.isEmpty()) { sb.append('<'); for (TemplateArgument arg : template) { sb.append(arg); sb.append(','); } sb.deleteCharAt(sb.length()-1); sb.append('>'); } sb.append(':'); sb.append(prefix); sb.append(')'); return sb.toString(); } } /** * This represents a possible path returned by findPaths(). * It consists of a list of members that were found based on the names provided. * * @author iconmaster * */ public static class LookupPath { /** * A Subject of a path is a MemberAccess that requires special action when it is encountered. This includes variables, fields, etc. * * @author iconmaster * */ public static class Subject { /** * Where it is in the path's member list. */ public int loc; /** * What the previous subject was. If this is a field, this is the callee, for example. */ public Subject previous; /** * The member this subject represents. */ public MemberAccess member; /** * What access operation binds together <tt>previous</tt> and <tt>this</tt>. */ public AccessType infix; /** * Where this member originated. */ public SourceInfo source; /** * The type this subject returns upon execution. */ public TypeRef type; /** * The path this subject is from. */ public LookupPath path; /** * The type map this subject returns, suitable for the methods in {@link MemberAccess} or {@link TemplateUtils}. */ public Map<TemplateType, TypeRef> typeMap = new HashMap<>(); public Subject(LookupPath path, int loc, MemberAccess member) { this.path = path; this.loc = loc; this.member = member; } @Override public String toString() { return "Subject("+member+")"; } } /** * The raw input given to this path. */ public List<LookupElement> names; /** * The list of consecutive accesses that the names given represent. */ public List<MemberAccess> members = new ArrayList<>(); /** * The list of subjects that were accessed in this path. */ public List<Subject> subjects = new ArrayList<>(); /** * The type map at each step of this access path. */ public List<Map<TemplateType, TypeRef>> typeMaps = new ArrayList<>(); public LookupPath(List<LookupElement> names) { this.names = new ArrayList<>(); this.names.add(null); this.names.addAll(names); } /** * Copies another LookupPath. * * @param other */ public LookupPath(LookupPath other) { this.names = other.names; this.members = new ArrayList<>(other.members); this.subjects = new ArrayList<>(other.subjects); this.typeMaps = new ArrayList<>(other.typeMaps); } /** * Adds a new member to this list. Automatically updates the subject and type map lists. * * @param member * @return <tt>this</tt>. */ public LookupPath add(MemberAccess member) { Map<TemplateType, TypeRef> typeMap = returnedTypeMap(); LookupElement name = names.get(members.size()); if (member instanceof Type) { TypeRef ref = new TypeRef(name == null ? null : name.source, (Type)member); if (name != null) ref.getTemplateArgs().addAll(name.template); member = TemplateUtils.replaceTemplates(ref, typeMap); } Map<TemplateType, TypeRef> newMap = member.getTemplateMap(typeMap); this.members.add(member); if (member instanceof Field || member instanceof Variable || member instanceof Function) { Subject sub = new Subject(this, members.size()-1, member); if (name != null) sub.source = name.source; if (!subjects.isEmpty()) { sub.previous = returnedSubject(); sub.infix = names.get(subjects.get(subjects.size()-1).loc+1).prefix; } TypeRef type = null; if (member instanceof Variable) { type = TemplateUtils.replaceTemplates(((Variable) member).type, typeMap); } if (member instanceof Field) { Field f = (Field) member; type = TemplateUtils.replaceTemplates(f.getType(), typeMap); } sub.type = type; if (type != null) { Map<TemplateType, TypeRef> subTypeMap = type.getTemplateMap(typeMap); sub.typeMap = newMap = subTypeMap == null ? (newMap == null ? typeMap : newMap) : subTypeMap; } else { sub.typeMap = newMap == null ? typeMap : newMap; } subjects.add(sub); } if (newMap != null) { typeMap = newMap; } typeMaps.add(typeMap); return this; } /** * Adds new members to this list. Automatically updates the subject and type map lists. * * @param members * @return <tt>this</tt>. */ public LookupPath addAll(Collection<MemberAccess> members) { for (MemberAccess member : members) { add(member); } return this; } /** * @return true if this path does not violate any access rules. */ public boolean isValidPath() { if (subjects.isEmpty() || subjects.get(subjects.size()-1).loc != names.size()-1) return false; for (Subject sub : subjects) { TypeRef type = sub.previous == null ? null : sub.previous.type; Map<TemplateType, TypeRef> typeMap = sub.previous == null ? new HashMap<>() : sub.previous.typeMap; if (sub.member instanceof Field) { Field f = (Field) sub.member; Type fieldOf = f.getFieldOf(); if (fieldOf == null && type != null) { return false; } if (fieldOf != null && (type == null || !type.canCastTo(TemplateUtils.replaceTemplates(new TypeRef(null, fieldOf), typeMap)))) { return false; } } else if (sub.member instanceof Function) { Function f = (Function) sub.member; Type fieldOf = f.getFieldOf(); if (fieldOf == null && type != null) { return false; } if (fieldOf != null && (type == null || !type.canCastTo(TemplateUtils.replaceTemplates(new TypeRef(null, fieldOf), typeMap)))) { return false; } } } return true; } public List<LookupPath> branch(List<MemberAccess> newMembers) { return newMembers.stream().map((member)->new LookupPath(this).add(member)).collect(Collectors.toList()); } /** * @return the member that this entire lookup will return (but not necessarily the last one in the list). */ public MemberAccess returnedMember() { if (members.isEmpty()) return null; int i = members.size()-1; MemberAccess e = members.get(i); Subject sub = subjects.isEmpty() ? null : subjects.get(subjects.size()-1); while (sub != null && sub.loc == i && sub.infix == AccessType.DOUBLE_DOT) { sub = sub.previous; i = sub.loc; e = members.get(i); } return e; } /** * @return the subject that this entire lookup will return (but not necessarily the last one in the list). */ public Subject returnedSubject() { if (subjects.isEmpty()) return null; Subject e = subjects.get(subjects.size()-1); while (e.infix == AccessType.DOUBLE_DOT) { e = e.previous; } return e; } /** * @return the type map that this entire lookup will return (but not necessarily the last one in the list). */ public Map<TemplateType, TypeRef> returnedTypeMap() { if (typeMaps.isEmpty()) return new HashMap<>(); int i = typeMaps.size()-1; Map<TemplateType, TypeRef> e = typeMaps.get(i); Subject sub = subjects.isEmpty() ? null : subjects.get(subjects.size()-1); while (sub != null && sub.loc == i && sub.infix == AccessType.DOUBLE_DOT) { sub = sub.previous; i = sub.loc; e = typeMaps.get(i); } return e; } /** * Takes the final subject off the list and gives it to you. * @return */ public Subject popSubject() { Subject sub = subjects.remove(subjects.size()-1); // TODO: remove non-subject members return sub; } @Override public String toString() { return "path"+members; } /** * Returns the member you should do lookup based on. * @return */ public MemberAccess getLookup() { Subject sub = returnedSubject(); MemberAccess member = returnedMember(); if (sub == null || sub.type == null || sub.member != member) { return member; } else { return sub.type; } } /** * @return the last member (but not necessarily the one that this lookup returns). */ public MemberAccess lastMember() { return members.isEmpty() ? null : members.get(members.size()-1); } /** * @return the last subject (but not necessarily the one that this lookup returns). */ public Subject lastSubject() { return subjects.isEmpty() ? null : subjects.get(subjects.size()-1); } /** * @return the last type map (but not necessarily the one that this lookup returns). */ public Map<TemplateType, TypeRef> lastTypeMap() { return typeMaps.isEmpty() ? null : typeMaps.get(typeMaps.size()-1); } } /** * Look up all possible paths of a list of names. * * @param base The scope. * @param names The list of successive names. * @return All the possible paths of members. */ public static List<LookupPath> findPaths(Scope scope, MemberAccess base, List<LookupElement> names) { List<LookupPath> result = new ArrayList<>(); // populate the list of possible paths (based on name alone) while (base != null) { List<LookupPath> options = new ArrayList<>(); options.add(new LookupPath(names).add(base)); for (LookupElement name : names) { if (options.isEmpty()) break; options = options.stream() .map((path)->path.branch(path.getLookup().getMembers(name.name, path.returnedTypeMap()))) .reduce(new ArrayList<>(), (a,b)->{a.addAll(b); return a;}); } result.addAll(options); base = base.getMemberParent(); } // remove incorrect accesses to instance fields result.removeIf((path)->!path.isValidPath()); // return the result return result; } /** * Given a path, this function will add the code needed to return the contents of this path to the code block provided. * * @param scope The current scope. * @param path The access path. * @return The variable that contains the results of the lookup. */ public static Variable getSubjectOfPath(Scope scope, LookupPath path) { Variable var = scope.getCodeBlock().instance; Label label = null; for (Subject sub : path.subjects) { LookupElement name = path.names.get(sub.loc); SourceInfo source = name == null ? null : name.source; Variable lastVar = var; if (sub.infix == AccessType.NULLABLE_DOT) { if (var == null) { // TODO: error? return null; } if (label == null) { label = scope.addTempLabel(); } Variable tempVar = scope.addTempVar(new TypeRef(scope.getCodeBlock().tni.corePackage.TYPE_BOOL), name.source); scope.getCodeBlock().ops.add(new Instruction(scope.getCodeBlock().tni, source, OpCode.ISNULL, new Object[] {tempVar, var})); scope.getCodeBlock().ops.add(new Instruction(scope.getCodeBlock().tni, source, OpCode.JUMPTRUE, new Object[] {tempVar, label})); } if (sub.member instanceof Variable) { var = (Variable) sub.member; } if (sub.member instanceof Field) { Field f = (Field) sub.member; Type fieldOf = f.getFieldOf(); Variable newVar = scope.addTempVar(TemplateUtils.replaceTemplates(f.type, sub.previous == null ? sub.typeMap : sub.previous.typeMap), source); if (f.getGetter() == null) { // error; field is write-only scope.getCodeBlock().tni.errors.add(new WriteOnlyError(source, f)); return newVar; } if (fieldOf == null) { // static scope.getCodeBlock().ops.add(new Instruction(scope.getCodeBlock().tni, source, OpCode.CALLSTATIC, new Object[] {Arrays.asList(newVar), f.getGetter(), new ArrayList<>()})); } else { // instance scope.getCodeBlock().ops.add(new Instruction(scope.getCodeBlock().tni, source, OpCode.CALL, new Object[] {Arrays.asList(newVar), var, f.getGetter().getVirtualBase(fieldOf), new ArrayList<>()})); } var = newVar; } if (sub.infix == AccessType.DOUBLE_DOT) { if (var == null) { // TODO: error? return null; } var = lastVar; } } if (label != null) { scope.getCodeBlock().ops.add(new Instruction(scope.getCodeBlock().tni, null, OpCode.LABEL, new Object[] {label})); } return var; } /** * An argument passed into a function. Used for function lookup. * * @author iconmaster * */ public static class LookupArgument { /** * The variable containing the argument's value. */ public Variable var; /** * The label of the argumnet. May be null. */ public String label; public LookupArgument(Variable var) { super(); this.var = var; } public LookupArgument(Variable var, String label) { super(); this.var = var; this.label = label; } } public static class FuncArgMap { public Map<Parameter, Variable> args = new HashMap<>(); public Map<Parameter, List<Variable>> varargs = new HashMap<>(); public Map<Parameter, Map<String, Variable>> varflags = new HashMap<>(); } /** * Creates a map of parameters to arguments for a function. * * @param f * @param args The arguments supplied, in the order they were supplied. * @return */ public static FuncArgMap getFuncArgMap(Function f, List<LookupArgument> args) { FuncArgMap result = new FuncArgMap(); // find the vararg or varflag param if they exist Parameter varargParam = null, varflagParam = null; for (Parameter param : f.getParams()) { if (param.hasAnnot(f.tni.corePackage.ANNOT_VARARG)) { varargParam = param; result.varargs.put(param, new ArrayList<>()); } else if (param.hasAnnot(f.tni.corePackage.ANNOT_VARFLAG)) { varflagParam = param; result.varflags.put(param, new HashMap<>()); } } // populate map for (LookupArgument arg : args) { if (arg.label == null) { // positional argument; find the first unallocated parameter boolean found = false; for (Parameter param : f.getParams()) { if (result.varargs.containsKey(param) || result.varflags.containsKey(param)) continue; if (!result.args.containsKey(param)) { result.args.put(param, arg.var); found = true; break; } } if (!found) { if (varargParam != null) { // put it in the vararg result.varargs.get(varargParam).add(arg.var); } else { // error; too many arguments return null; } } } else { // keyword argument; find the corresponding parameter boolean found = false; for (Parameter param : f.getParams()) { if (param.getName().equals(arg.label)) { if (result.args.containsKey(param)) { // error; duplicate argument return null; } result.args.put(param, arg.var); found = true; break; } } if (!found) { if (varflagParam != null) { if (!result.varflags.get(varflagParam).containsKey(arg.label)) { // add it to the varflags result.varflags.get(varflagParam).put(arg.label, arg.var); } else { // error; duplicate argument return null; } } else { // error; no argument with that key return null; } } } } // check to make sure no required parameters are left out for (Parameter param : f.getParams()) { if (result.varargs.containsKey(param) || result.varflags.containsKey(param)) continue; if (!param.isOptional() && !result.args.containsKey(param)) { // error; parameter required return null; } } // return the arg map return result; } public static boolean areFuncArgsCompatibleWith(Scope scope, Function f, List<LookupArgument> args, Map<TemplateType, TypeRef> typeMap, Map<Variable, ExprContext> argMap) { CorePackage core = f.tni.corePackage; if (argMap == null) argMap = new HashMap<>(); // check if the argumnet's number/labels all match up to the signature FuncArgMap map = LookupUtils.getFuncArgMap(f, args); if (map == null) { return false; } // calculate the function's template map // TODO: add vararg stuff to these lists List<TypeRef> params = f.getParams().stream().filter(p->map.args.containsKey(p)).map(p->p.getType()).collect(Collectors.toList()); List<TypeRef> args2 = f.getParams().stream().filter(p->map.args.containsKey(p)).map(p->map.args.get(p).type).collect(Collectors.toList()); Map<TemplateType, TypeRef> funcTempMap = TemplateUtils.inferTemplatesFromArguments(core.tni, params, args2, f.getFuncTemplateMap()); // check if the types match up to the signature for (Entry<Parameter, Variable> entry : map.args.entrySet()) { TypeRef a = argMap.containsKey(entry.getValue()) ? TyphonCompiler.getExprType(scope, argMap.get(entry.getValue()), Arrays.asList(entry.getKey().getType())).get(0) : entry.getValue().type; TypeRef b = entry.getKey().getType(); a = TemplateUtils.replaceTemplates(TemplateUtils.replaceTemplates(a, funcTempMap), typeMap); b = TemplateUtils.replaceTemplates(TemplateUtils.replaceTemplates(b, funcTempMap), typeMap); if (!a.canCastTo(b)) { return false; } } for (Entry<Parameter, List<Variable>> entry : map.varargs.entrySet()) { Parameter p = entry.getKey(); TypeRef elemType = TemplateUtils.matchAllTemplateArgs(p.getType()).get(core.TYPE_LIST.getTemplates().get(0)); elemType = TemplateUtils.replaceTemplates(TemplateUtils.replaceTemplates(elemType, funcTempMap), typeMap); for (Variable var : entry.getValue()) { TypeRef vtype = argMap.containsKey(var) ? TyphonCompiler.getExprType(scope, argMap.get(var), Arrays.asList(entry.getKey().getType())).get(0) : var.type; vtype = TemplateUtils.replaceTemplates(TemplateUtils.replaceTemplates(vtype, funcTempMap), typeMap); if (!vtype.canCastTo(elemType)) { return false; } } } for (Entry<Parameter, Map<String, Variable>> entry : map.varflags.entrySet()) { Parameter p = entry.getKey(); TypeRef elemType = TemplateUtils.matchAllTemplateArgs(p.getType()).get(core.TYPE_MAP.getTemplates().get(1)); elemType = TemplateUtils.replaceTemplates(TemplateUtils.replaceTemplates(elemType, funcTempMap), typeMap); for (Variable var : entry.getValue().values()) { TypeRef vtype = argMap.containsKey(var) ? TyphonCompiler.getExprType(scope, argMap.get(var), Arrays.asList(entry.getKey().getType())).get(0) : var.type; vtype = TemplateUtils.replaceTemplates(TemplateUtils.replaceTemplates(vtype, funcTempMap), typeMap); if (!vtype.canCastTo(elemType)) { return false; } } } return true; } }
package jsettlers.main.android.bg; import jsettlers.common.CommonConstants; import jsettlers.common.landscape.ELandscapeType; import jsettlers.common.map.EDebugColorModes; import jsettlers.common.map.IGraphicsBackgroundListener; import jsettlers.common.map.IGraphicsGrid; import jsettlers.common.map.partition.IPartitionSettings; import jsettlers.common.mapobject.EMapObjectType; import jsettlers.common.mapobject.IMapObject; import jsettlers.common.movable.IMovable; import jsettlers.common.position.ShortPoint2D; public class BgMap implements IGraphicsGrid { public static final ShortPoint2D startCenter = new ShortPoint2D(30, 0); private static final int TREE_BORDER = 20; private static final int MOVABLE_BORDER = 60; private static final double MOVABLE_PROBABILITY = .001; private static final double TREE_PROBABILITY = 0.1; private final BgFish fish = new BgFish(EMapObjectType.FISH_DECORATION);; private final BgFish tree = new BgFish(EMapObjectType.TREE_ADULT); private final double[] randoms = new double[17]; public BgMap() { for (int i = 0; i < randoms.length; i++) { randoms[i] = Math.random(); } } private double getRand(int x, int y) { double rand1 = randoms[x % randoms.length]; double rand2 = randoms[(y * 7) % randoms.length]; return (rand1 * 3 + rand2) % 1; } @Override public short getWidth() { return Short.MAX_VALUE; } @Override public short getHeight() { return 30; } @Override public IMovable getMovableAt(int x, int y) { if (x > MOVABLE_BORDER && getLandscapeTypeAt(x, y) == ELandscapeType.GRASS && getRand(x, y) > 1 - MOVABLE_PROBABILITY) { return new BgMovable(new ShortPoint2D(x, y)); } else { return null; } } @Override public IMapObject getMapObjectsAt(int x, int y) { if (x > TREE_BORDER && ((x + y) & 3) == 0 && ((x - y) & 3) == 0 && getLandscapeTypeAt(x, y) == ELandscapeType.GRASS && getRand(x, y) < TREE_PROBABILITY) { return tree; } else { return null; } } @Override public byte getHeightAt(int x, int y) { return 0; } @Override public ELandscapeType getLandscapeTypeAt(int x, int y) { return ELandscapeType.GRASS; } @Override public int getDebugColorAt(int x, int y, EDebugColorModes debugColorMode) { return 0; } @Override public boolean isBorder(int x, int y) { return false; } @Override public byte getPlayerIdAt(int x, int y) { return 0; } @Override public byte getVisibleStatus(int x, int y) { return CommonConstants.FOG_OF_WAR_VISIBLE; } @Override public boolean isFogOfWarVisible(int x, int y) { return true; } @Override public void setBackgroundListener( IGraphicsBackgroundListener backgroundListener) { } @Override public int nextDrawableX(int x, int y, int maxX) { return x + 1; } @Override public IPartitionSettings getPartitionSettings(int x, int y) { return null; } }
package innovimax.mixthem.interfaces; import innovimax.mixthem.io.ReadType; import java.io.IOException; /** * This interface provides for reading characters from an character-input. * @author Innovimax * @version 1.0 */ public interface IInputChar { /** * Returns true if there is more characters. * @return Returns true if there is more characters * @throws IOException - If an I/O error occurs */ public boolean hasCharacter() throws IOException; /** * Reads an eligible character regarding the type, or returns null if not eligible or no more lines. * @param type The type of reading expected * @param force True if reading is required whatever the type said * @return The eligible character as an int, or -1 if not eligible or no more characters * @throws IOException - If an I/O error occurs */ public int nextCharacter(ReadType type, boolean force) throws IOException; /** * Reads characters into a portion of an array. * @param buffer Destination buffer * @param len - Maximum number of characters to read * @return The number of characters read, or -1 if there is no more characters * @throws IOException - If an I/O error occurs */ public int nextCharacters(char[] buffer, int len) throws IOException; /** * Closes this input and releases any system resources associated with it. * @throws IOException - If an I/O error occurs */ public void close() throws IOException; }
package org.bouncycastle.jce.provider.test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PublicKey; import java.security.Security; import java.security.SignatureException; import java.security.cert.CertPath; import java.security.cert.Certificate; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Vector; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.util.encoders.Hex; import org.bouncycastle.util.test.SimpleTestResult; import org.bouncycastle.util.test.Test; import org.bouncycastle.util.test.TestResult; public class CertPathTest implements Test { static byte[] rootCertBin = Hex.decode( "3082023c308201a5a003020102020101300d06092a864886f70d0101040500305c310b300906035504061302415531283026060355040a131f546865204c6567696f6e206f662074686520426f756e637920436173746c6531233021060355040b131a426f756e6379205072696d617279204365727469666963617465301e170d3032303132323133353230385a170d3032303332333133353230385a305c310b300906035504061302415531283026060355040a131f546865204c6567696f6e206f662074686520426f756e637920436173746c6531233021060355040b131a426f756e6379205072696d61727920436572746966696361746530819d300d06092a864886f70d010101050003818b0030818702818100b259d2d6e627a768c94be36164c2d9fc79d97aab9253140e5bf17751197731d6f7540d2509e7b9ffee0a70a6e26d56e92d2edd7f85aba85600b69089f35f6bdbf3c298e05842535d9f064e6b0391cb7d306e0a2d20c4dfb4e7b49a9640bdea26c10ad69c3f05007ce2513cee44cfe01998e62b6c3637d3fc0391079b26ee36d5020111a310300e300c0603551d13040530030101ff300d06092a864886f70d0101040500038181002584a067f9d3e9a02efcf33d9fb870176311ad7741551397a3717cfa71f8724907bdfe9846d25205c9241631df9c0dabd5a980ccdb69fdfcad3694fbe6939f7dffd730d67242400b6fcc9aa718e87f1d7ea58832e4f47d253c7843cc6f4c0a206fb141b959ff639b986cc3470bd576f176cf4d4f402b549ec14e90349b8fb8f5"); static byte[] interCertBin = Hex.decode( "308202fe30820267a003020102020102300d06092a864886f70d0101040500305c310b300906035504061302415531283026060355040a131f546865204c6567696f6e206f662074686520426f756e637920436173746c6531233021060355040b131a426f756e6379205072696d617279204365727469666963617465301e170d3032303132323133353230395a170d3032303332333133353230395a3061310b300906035504061302415531283026060355040a131f546865204c6567696f6e206f662074686520426f756e637920436173746c6531283026060355040b131f426f756e637920496e7465726d65646961746520436572746966696361746530819f300d06092a864886f70d010101050003818d00308189028181008de0d113c5e736969c8d2b047a243f8fe18edad64cde9e842d3669230ca486f7cfdde1f8eec54d1905fff04acc85e61093e180cadc6cea407f193d44bb0e9449b8dbb49784cd9e36260c39e06a947299978c6ed8300724e887198cfede20f3fbde658fa2bd078be946a392bd349f2b49c486e20c405588e306706c9017308e69020300ffffa381ca3081c7301d0603551d0e041604149408336f3240f78737dad120aaed2ea76ec9c91e3081840603551d23047d307b8014c0361907adc48897a85e726f6b09ebe5e6f1295ca160a45e305c310b300906035504061302415531283026060355040a131f546865204c6567696f6e206f662074686520426f756e637920436173746c6531233021060355040b131a426f756e6379205072696d617279204365727469666963617465820101300c0603551d13040530030101ff301106096086480186f8420101040403020060300d06092a864886f70d010104050003818100a06b166b48c82ba1f81c8f142c14974050266f7b9d003e39e24e53d6f82ce43f4099937aa69b818a5193c5a842521cdb59a44b8837c2caddea70d8e013d6c9fd5e572010ee5cc6894c91783af13909eb53bd79d3c9bf6e268b0c13c41c6b16365287975683ece8a4dad9c8394faf707a00348ed01ac59287734411af4e878486"); static byte[] finalCertBin = Hex.decode( "30820259308201c2a003020102020103300d06092a864886f70d01010405003061310b300906035504061302415531283026060355040a131f546865204c6567696f6e206f662074686520426f756e637920436173746c6531283026060355040b131f426f756e637920496e7465726d656469617465204365727469666963617465301e170d3032303132323133353230395a170d3032303332333133353230395a3065310b300906035504061302415531283026060355040a131f546865204c6567696f6e206f662074686520426f756e637920436173746c6531123010060355040713094d656c626f75726e65311830160603550403130f4572696320482e2045636869646e61305a300d06092a864886f70d01010105000349003046024100b4a7e46170574f16a97082b22be58b6a2a629798419be12872a4bdba626cfae9900f76abfb12139dce5de56564fab2b6543165a040c606887420e33d91ed7ed7020111a3633061301d0603551d0e04160414d06cec6d3583bc55121b0ccb3efed726a6166468301f0603551d230418301680149408336f3240f78737dad120aaed2ea76ec9c91e300c0603551d1304053003010100301106096086480186f8420101040403020001300d06092a864886f70d010104050003818100135db1857d0bb8bf108ce4df2cba4d1cf9e4a4578c0197b4da4e6ddd4c62d25debc5ed0916341aa577caa8eebf21409f065bb94369e3f006536a0a715c429c5888504b84030a181c88cb72fc99c11571d3171f869865cee722af474b5279df9ccd6ec3b04bf0fae272ca15266b74a5ce2d14548a0c76a07b4f97dbc25ed7d0ef"); static byte[] rootCrlBin = Hex.decode( "3082012430818e020101300d06092a864886f70d0101050500305c310b300906035504061302415531283026060355040a131f546865204c6567696f6e206f662074686520426f756e637920436173746c6531233021060355040b131a426f756e6379205072696d617279204365727469666963617465170d3032303132323133353230395a170d3032303332333133353230395a300d06092a864886f70d0101050500038181001255a218c620add68a7a8a561f331d2d510b42515c53f3701f2f49946ff2513a0c6e8e606e3488679f8354dc06a79a84c5233c9c9c9f746bbf4d19e49e730850b3bb7e672d59200d3da12512a91f7bc6f56036250789860ade5b0859a2a8fd24904b271624a544c8e894f293bb0f7018679e3499bf06548618ba473b7852a577"); static byte[] interCrlBin = Hex.decode( "30820129308193020101300d06092a864886f70d01010505003061310b300906035504061302415531283026060355040a131f546865204c6567696f6e206f662074686520426f756e637920436173746c6531283026060355040b131f426f756e637920496e7465726d656469617465204365727469666963617465170d3032303132323133353230395a170d3032303332333133353230395a300d06092a864886f70d01010505000381810046e2743d2faa0a3ed3555fc860a6fed78da96ce967c0db6ec8f40de95ec8cab9c720698d705f1cd8a75a400c0b15f23751cdfd5491abb9d416f0585f425e6802a3612a30cecd593abdcd15c632e0a4e2a7a3049649138ae0367431dd626d079c13c1449058547d796f53660acd5b432e7dacf31315ed3c21eb8948a7c043f418"); private TestResult testExceptions() { byte[] enc = { (byte)0, (byte)2, (byte)3, (byte)4, (byte)5 }; MyCertPath mc = new MyCertPath(enc); ByteArrayOutputStream os = new ByteArrayOutputStream(); ByteArrayInputStream is; byte[] arr; try { ObjectOutputStream oos = new ObjectOutputStream(os); oos.writeObject(mc); oos.flush(); oos.close(); } catch (IOException e) { return new SimpleTestResult(false, getName() + ": unexpected exception.", e); } try { CertificateFactory cFac = CertificateFactory.getInstance("X.509", "BC"); arr = os.toByteArray(); is = new ByteArrayInputStream(arr); cFac.generateCertPath(is); } catch (CertificateException e) { // ignore okay } catch (Exception e) { return new SimpleTestResult(false, getName() + ": failed exception test.", e); } return new SimpleTestResult(true, getName() + ": Okay"); } public TestResult perform() { try { CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC"); X509Certificate rootCert = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(rootCertBin)); X509Certificate interCert = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(interCertBin)); X509Certificate finalCert = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(finalCertBin)); //Testing CertPath generation from List List list = new ArrayList(); list.add(interCert); CertPath certPath1 = cf.generateCertPath(list); //Testing CertPath encoding as PkiPath byte[] encoded = certPath1.getEncoded("PkiPath"); //Testing CertPath generation from InputStream ByteArrayInputStream inStream = new ByteArrayInputStream(encoded); CertPath certPath2 = cf.generateCertPath(inStream, "PkiPath"); //Comparing both CertPathes if (! certPath2.equals(certPath1)) { return new SimpleTestResult(false, this.getName() + ": CertPath differ after encoding and decoding."); } encoded = certPath1.getEncoded("PKCS7"); //Testing CertPath generation from InputStream inStream = new ByteArrayInputStream(encoded); certPath2 = cf.generateCertPath(inStream, "PKCS7"); //Comparing both CertPathes if (! certPath2.equals(certPath1)) { return new SimpleTestResult(false, this.getName() + ": CertPath differ after encoding and decoding."); } encoded = certPath1.getEncoded("PEM"); //Testing CertPath generation from InputStream inStream = new ByteArrayInputStream(encoded); certPath2 = cf.generateCertPath(inStream, "PEM"); //Comparing both CertPathes if (!certPath2.equals(certPath1)) { return new SimpleTestResult(false, this.getName() + ": CertPath differ after encoding and decoding."); } TestResult res = testExceptions(); if (!res.isSuccessful()) { return res; } // empty list test list = new ArrayList(); try { CertPath certPath = CertificateFactory.getInstance("X.509","BC").generateCertPath(list); if (certPath.getCertificates().size() != 0) { return new SimpleTestResult(false, this.getName() + ": list wrong size."); } } catch (Exception e) { return new SimpleTestResult(false, this.getName() + ": " + e); } } catch (Exception e) { return new SimpleTestResult(false, this.getName() + ": exception - " + e.toString(), e); } return new SimpleTestResult(true, this.getName() + ": Okay"); } public String getName() { return "CertPath"; } public static void main( String[] args) { Security.addProvider(new BouncyCastleProvider()); Test test = new CertPathTest(); TestResult result = test.perform(); System.out.println(result.toString()); } private static class MyCertificate extends Certificate { private final byte[] encoding; public MyCertificate(String type, byte[] encoding) { super(type); // don't copy to allow null parameter in test this.encoding = encoding; } public byte[] getEncoded() throws CertificateEncodingException { // do copy to force NPE in test return (byte[])encoding.clone(); } public void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException { } public void verify(PublicKey key, String sigProvider) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException { } public String toString() { return "[My test Certificate, type: " + getType() + "]"; } public PublicKey getPublicKey() { return new PublicKey() { public String getAlgorithm() { return "TEST"; } public byte[] getEncoded() { return new byte[] { (byte)1, (byte)2, (byte)3 }; } public String getFormat() { return "TEST_FORMAT"; } }; } } private static class MyCertPath extends CertPath { private final Vector certificates; private final Vector encodingNames; private final byte[] encoding; public MyCertPath(byte[] encoding) { super("MyEncoding"); this.encoding = encoding; certificates = new Vector(); certificates.add(new MyCertificate("MyEncoding", encoding)); encodingNames = new Vector(); encodingNames.add("MyEncoding"); } public List getCertificates() { return Collections.unmodifiableList(certificates); } public byte[] getEncoded() throws CertificateEncodingException { return (byte[])encoding.clone(); } public byte[] getEncoded(String encoding) throws CertificateEncodingException { if (getType().equals(encoding)) { return (byte[])this.encoding.clone(); } throw new CertificateEncodingException("Encoding not supported: " + encoding); } public Iterator getEncodings() { return Collections.unmodifiableCollection(encodingNames).iterator(); } } }
package io.github.utplsql.api.reporter; import io.github.utplsql.api.DBHelper; import java.sql.*; import java.util.Calendar; public abstract class Reporter implements SQLData { private String selfType; private String reporterId; private java.sql.Date startDate; public Reporter() {} public Reporter init(Connection conn) throws SQLException { setSelfType(getSQLTypeName()); setStartDate(new java.sql.Date(Calendar.getInstance().getTimeInMillis())); setReporterId(DBHelper.newSysGuid(conn)); return this; } public String getSelfType() { return this.selfType; } private void setSelfType(String selfType) { this.selfType = selfType; } public String getReporterId() { return this.reporterId; } private void setReporterId(String reporterId) { this.reporterId = reporterId; } public java.sql.Date getStartDate() { return this.startDate; } private void setStartDate(java.sql.Date startDate) { this.startDate = startDate; } @Override public void readSQL(SQLInput stream, String typeName) throws SQLException { setSelfType(stream.readString()); setReporterId(stream.readString()); setStartDate(stream.readDate()); } @Override public void writeSQL(SQLOutput stream) throws SQLException { stream.writeString(getSelfType()); stream.writeString(getReporterId()); stream.writeDate(getStartDate()); } }
package jp.ac.keio.bio.fun.gomaotsu; import java.util.ArrayList; public class Combination { private int[] c; private int n, k, count; private boolean isOneOrigin; private ArrayList<ArrayList<Integer>> listOfCombinations; public Combination(int n, int k) { this.n = n; this.k = k; count = getCombinationNum(n, k); c = new int[count]; isOneOrigin = false; } public Combination(int n, int k, boolean oneOrigin) { this(n, k); this.isOneOrigin = oneOrigin; } public int getCombinationNum(int n, int k) { int c = 1; for(int i = 1; i <= k; i++) { c = c * (n - i + 1) / i; } return c; } public void combine(int m) { if (m > k) { //printComb(); addOneComb(); } else { for (int i = c[m - 1] + 1; i <= n - k + m; i++) { c[m] = i; combine(m + 1); } } } public ArrayList<ArrayList<Integer>> getListOfCombinations() { listOfCombinations = new ArrayList<ArrayList<Integer>>(); combine(1); return listOfCombinations; } public void addOneComb() { ArrayList<Integer> al = new ArrayList<Integer>(); for (int i = 1; i <= k; i++) { if (isOneOrigin) al.add(c[i]); // one-origin else al.add(c[i]-1); // zero-origin } listOfCombinations.add(al); } public void printComb() { for (int i = 1; i <= k; i++) { System.out.print(c[i] + " "); // print index } System.out.println(); } /** * @return the c */ public int[] getC() { return c; } /** * @return the n */ public int getN() { return n; } /** * @return the k */ public int getK() { return k; } /** * @return the count */ public int getCount() { return count; } /** * @return the isOneOrigin */ public boolean isOneOrigin() { return isOneOrigin; } public static void main(String[] args) { int n, k; n = 21; k = 3; Combination c = new Combination(n, k); // zero-origin //Combination c = new Combination(n, k, true); // one-origin ArrayList<ArrayList<Integer>> comb = c.getListOfCombinations(); for (ArrayList<Integer> al : comb) { System.out.println(al); } } }
package jp.crafterkina.pipes.client; import jp.crafterkina.pipes.client.state.PipeStateMapper; import jp.crafterkina.pipes.client.tesr.TileEntityPipeRenderer; import jp.crafterkina.pipes.common.CommonProxy; import jp.crafterkina.pipes.common.RegistryEntries; import jp.crafterkina.pipes.common.block.BlockPipe; import jp.crafterkina.pipes.common.block.entity.TileEntityPipe; import jp.crafterkina.pipes.common.item.ItemPipe; import jp.crafterkina.pipes.common.pipe.strategy.StrategyAcceleration; import jp.crafterkina.pipes.common.pipe.strategy.StrategyExtraction; import jp.crafterkina.pipes.common.pipe.strategy.StrategyOneway; import net.minecraft.block.Block; import net.minecraft.client.renderer.block.model.ModelBakery; import net.minecraft.client.renderer.block.model.ModelResourceLocation; import net.minecraft.item.Item; import net.minecraftforge.client.event.ModelRegistryEvent; import net.minecraftforge.client.model.ModelLoader; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.client.FMLClientHandler; import net.minecraftforge.fml.client.registry.ClientRegistry; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class ClientProxy extends CommonProxy{ private static ModelResourceLocation getModelLocation(String name){ return new ModelResourceLocation(getResourceLocation(name), "inventory"); } @Override @SubscribeEvent protected void registerItems(RegistryEvent.Register<Item> event){ super.registerItems(event); } @Override @SubscribeEvent protected void registerBlocks(RegistryEvent.Register<Block> event){ super.registerBlocks(event); } @SubscribeEvent protected void registerModels(ModelRegistryEvent event){ { ModelLoader.setCustomModelResourceLocation(RegistryEntries.ITEM.merchant_phone, 0, getModelLocation("merchant_phone")); ModelLoader.setCustomMeshDefinition(RegistryEntries.ITEM.pipe, s -> getModelLocation(ItemPipe.getModelName(s))); ModelBakery.registerItemVariants(RegistryEntries.ITEM.pipe, getModelLocation("pipe"), getModelLocation("pipe_covered"), getModelLocation("pipe_metallic"), getModelLocation("pipe_covered_metallic")); ModelLoader.setCustomModelResourceLocation(RegistryEntries.ITEM.processor_base, 0, getModelLocation("processor_base")); ModelLoader.setCustomModelResourceLocation(RegistryEntries.ITEM.strategy_acceleration, 0, getModelLocation("processor_chipped_arrow")); ModelLoader.setCustomModelResourceLocation(RegistryEntries.ITEM.strategy_extraction, 0, getModelLocation("processor_hopper")); ModelLoader.setCustomModelResourceLocation(RegistryEntries.ITEM.strategy_oneway, 0, getModelLocation("processor_pentagon")); } { ModelLoader.setCustomStateMapper(RegistryEntries.BLOCK.pipe, new PipeStateMapper()); } } @Override protected void registerTileEntities(){ super.registerTileEntities(); ClientRegistry.bindTileEntitySpecialRenderer(TileEntityPipe.class, new TileEntityPipeRenderer()); } @Override protected void registerBlockColors(){ FMLClientHandler.instance().getClient().getBlockColors().registerBlockColorHandler(BlockPipe::getColor, RegistryEntries.BLOCK.pipe); } @Override protected void registerItemColors(){ FMLClientHandler.instance().getClient().getItemColors().registerItemColorHandler(ItemPipe::getColor, RegistryEntries.ITEM.pipe); FMLClientHandler.instance().getClient().getItemColors().registerItemColorHandler(StrategyAcceleration.ItemAccelerateProcessor::getColor, RegistryEntries.ITEM.strategy_acceleration); FMLClientHandler.instance().getClient().getItemColors().registerItemColorHandler(StrategyExtraction.ItemExtractionProcessor::getColor, RegistryEntries.ITEM.strategy_extraction); FMLClientHandler.instance().getClient().getItemColors().registerItemColorHandler(StrategyOneway.ItemOnewayProcessor::getColor, RegistryEntries.ITEM.strategy_oneway); } }
package jp.gr.java_conf.dyama.rink.ml.svm; interface Score { int getBestLabelID(); /** * clear score information. */ void clear(); /** * Returns the number of labels. * @return the number of labels */ int getNumberOfLabels(); void addJudge(int pos, int neg, double dist); /** * Pairwise score class for Multi-Class SVMs * @author Hiroyasu Yamada */ static class PairwiseScore implements Score{ /** the number of votes polled */ private int[] score_ ; private boolean add_ ; PairwiseScore(int num){ if (num <= 0) throw new IllegalArgumentException("the number of classes is 0 and fewer."); score_ = new int[num]; add_ = false; } @Override public int getBestLabelID() { if(add_ == false) throw new IllegalStateException("No judge has been added."); int best = 0; for(int i = 0 ; i < score_.length ; i++){ if (score_[best] < score_[i]) best = i ; } return best ; } @Override public void clear() { for(int i = 0 ; i < score_.length; i++ ) score_[i] = 0 ; add_ = false ; } @Override public void addJudge(int pos, int neg, double dist) { if (pos < 0 || neg < 0) throw new IllegalArgumentException("the label ID is negative."); if (neg <= pos) throw new IllegalArgumentException("the negative label ID is same to the positive label ID and fewer."); if (dist > 0.0){ score_[pos] ++ ; } else { score_[neg] ++ ; } add_ = true ; } @Override public int getNumberOfLabels() { return score_.length; } } }
package kodkod.engine.ltl2fol; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import kodkod.ast.BinaryTempFormula; import kodkod.ast.ConstantExpression; import kodkod.ast.Expression; import kodkod.ast.Formula; import kodkod.ast.IntExpression; import kodkod.ast.Node; import kodkod.ast.Relation; import kodkod.ast.RelationPredicate; import kodkod.ast.TempExpression; import kodkod.ast.UnaryTempFormula; import kodkod.ast.Variable; import kodkod.ast.operator.TemporalOperator; import kodkod.ast.visitor.AbstractReplacer; import kodkod.util.nodes.Nodes; import static kodkod.engine.ltl2fol.TemporalTranslator.L_FIRST; import static kodkod.engine.ltl2fol.TemporalTranslator.L_LAST; import static kodkod.engine.ltl2fol.TemporalTranslator.L_PREFIX; import static kodkod.engine.ltl2fol.TemporalTranslator.LEVEL; import static kodkod.engine.ltl2fol.TemporalTranslator.FIRST; import static kodkod.engine.ltl2fol.TemporalTranslator.LAST; import static kodkod.engine.ltl2fol.TemporalTranslator.LAST_; import static kodkod.engine.ltl2fol.TemporalTranslator.LOOP; import static kodkod.engine.ltl2fol.TemporalTranslator.PREFIX; import static kodkod.engine.ltl2fol.TemporalTranslator.STATE; import static kodkod.engine.ltl2fol.TemporalTranslator.TRACE; import static kodkod.engine.ltl2fol.TemporalTranslator.UNROLL_MAP; import static kodkod.engine.ltl2fol.TemporalTranslator.START; /** * Translates an LTL temporal formula into its standard Kodkod FOL * representation. Assumes that the variable relations have been previously * expanded into its static version. To do so, it explicitly introduces the time * elements into the formula, converting the temporal operators into time * quantifiers and applying the time variable to variable relations. Since * global temporal quantifications force the trace to be infinite, the formula * must be in negative normal form to guarantee a correct translation. * * As of Pardinus 1.1, traces are assumed to always loop. * * @author Eduardo Pessoa, Nuno Macedo // [HASLab] temporal model finding */ public class LTL2FOLTranslator extends AbstractReplacer { private Set<Relation> vars_found; /** Pre-computed information about the formula, allows optimizations. */ private boolean has_past; /** * Translates an LTL temporal formula into its standard Kodkod FOL * representation, given the extension of the variable relations. * * @param has_past * whether the formula has past operators. * @param has_loop * whether the formula is known to force a loop. */ private LTL2FOLTranslator(boolean has_past) { super(new HashSet<Node>()); this.has_past = has_past; this.vars_found = new HashSet<Relation>(); } /** * Converts an LTL temporal formula into a regular Kodkod FOL formula. Uses the * visitor to convert and adds any trace constraint left at the top level to * handle nested post operators. It also adds the constraints that define the * structure of the time relation constants. This is the main method that should * be called to convert temporal formulas. The formula should be in negative * normal form in order for the temporal quantifiers to be correctly translated. * Optimizations will be applied if the the formula is known to force a loop or * has no past operators. * * @param form * the LTL formula to be converted. * @param has_past * whether the formula has past operators. * @param tempTransLog * map logging the translation of top-level formulas. * @return the resulting FOL formula. */ public static Formula translate(Formula form, int state, boolean has_past, Map<Formula,Formula> tempTransLog) { LTL2FOLTranslator translator = new LTL2FOLTranslator(has_past); Formula f; if (TemporalTranslator.ExplicitUnrolls) { Variable v = Variable.unary("v"); Formula order_unr_trace1 = v.join(PREFIX).one().forAll(v.oneOf(STATE.difference(LAST))); Formula order_unr_trace2 = PREFIX.join(v).one().forAll(v.oneOf(STATE.difference(FIRST))); Formula order_unr_trace3 = FIRST.join(PREFIX.reflexiveClosure()).eq(STATE); Formula order_unr_trace4 = PREFIX.in(STATE.product(STATE)); if (has_past) { Variable v1 = Variable.unary("v1"); // all s0, s1 order_unr_trace3 = order_unr_trace3.and((v.join(UNROLL_MAP).eq(v1.join(UNROLL_MAP)).implies(v.join(TRACE).join(UNROLL_MAP).eq(v1.join(TRACE).join(UNROLL_MAP)))).forAll(v1.oneOf(LAST_.join(TRACE.reflexiveClosure()))).forAll(v.oneOf(LAST_.join(TRACE.reflexiveClosure())))); } Formula loopDecl_unr = LOOP.one(); f = Formula.and(order_unr_trace1, order_unr_trace2, order_unr_trace3, order_unr_trace4, loopDecl_unr); } else { // TotalOrder(S/Next,State,S/First,S/Last) Formula st = PREFIX.totalOrder(STATE, FIRST, LAST); // TotalOrder(L/Next,Level,L/First,L/Last) Formula lv = L_PREFIX.totalOrder(LEVEL, L_FIRST, L_LAST); Formula loopDecl_unr = LOOP.one(); f = Formula.and(st,lv,loopDecl_unr); } translator.pushLevel(); translator.pushVariable(state); // log translation of top-level formulas for (Formula fs : Nodes.roots(form)) { tempTransLog.put(fs.accept(translator), fs); } Formula hack = Formula.TRUE; if (!TemporalTranslator.ExplicitUnrolls) { for (Relation r : translator.vars_found) // r.(loop.prev) = r.last hack = hack.and(r.join(LOOP.join(PREFIX.transpose())).eq(r.join(LAST))); } return Formula.and(f,Formula.and(tempTransLog.keySet()),hack); } /** * Converts an LTL temporal expression into a regular Kodkod FOL expression in a * concrete time step, counting from the {@link TemporalTranslator#FIRST * initial} time. Uses the visitor to convert. This is the main method that * should be called to convert temporal expressions. * * @param expr * the LTL expression to be converted. * @param state * the concrete state on which to evaluate the expression. * @param has_past * whether the formula has past operators. * @param has_loop * whether the formula is known to force a loop. * @return the resulting static expression. */ public static Expression translate(Expression expr, int state, boolean has_past) { LTL2FOLTranslator translator = new LTL2FOLTranslator(has_past); translator.pushVariable(state); Expression result = expr.accept(translator); return result; } /** * Converts an LTL temporal int expression into a regular Kodkod FOL int expression * in a concrete time step, counting from the {@link TemporalTranslator#FIRST * initial} time. Uses the visitor to convert. This is the main method that * should be called to convert temporal int expressions. * * @param expr * the LTL expression to be converted. * @param state * the concrete state on which to evaluate the expression. * @param has_past * whether the formula has past operators. * @param has_loop * whether the formula is known to force a loop. * @return the resulting static expression. */ public static IntExpression translate(IntExpression expr, int state, boolean has_past) { LTL2FOLTranslator translator = new LTL2FOLTranslator(has_past); translator.pushVariable(state); IntExpression result = expr.accept(translator); return result; } @Override public Expression visit(ConstantExpression constant) { Expression eu = STATE; if (has_past) eu = UNROLL_MAP.join(STATE); if (constant.equals(Expression.UNIV)) return constant.difference(eu); else if (constant.equals(Expression.IDEN)) return constant.difference(eu.product(eu)); else return constant; } @Override public Expression visit(Relation relation) { if (relation.isVariable()) { if (has_past && TemporalTranslator.ExplicitUnrolls) return relation.getExpansion().join(getVariable().join(UNROLL_MAP)); else { if (has_past) vars_found.add(relation.getExpansion()); return relation.getExpansion().join(getVariable()); } } else return relation; } @Override public Formula visit(RelationPredicate relationPredicate) { if (TemporalTranslator.isTemporal(relationPredicate)) // cannot simply expand since it would loose symmetry breaking // return relationPredicate.toConstraints().always().accept(this); throw new UnsupportedOperationException("Total orders over variable relations not supported."); else return relationPredicate; } @Override public Formula visit(UnaryTempFormula unaryTempFormula) { pushOperator(unaryTempFormula.op()); pushLevel(); pushVariable(); Formula e = unaryTempFormula.formula().accept(this); Formula rt = getQuantifier(getOperator(), e); popOperator(); popVariable(); popLevel(); return rt; } @Override public Formula visit(BinaryTempFormula binaryTempFormula) { pushOperator(binaryTempFormula.op()); pushLevel(); pushVariable(); Formula rt, left, right; switch (binaryTempFormula.op()) { case UNTIL: right = binaryTempFormula.right().accept(this); pushVariable(); left = binaryTempFormula.left().accept(this); rt = getQuantifierUntil(left, right); popVariable(); break; case SINCE: right = binaryTempFormula.right().accept(this); pushVariable(); left = binaryTempFormula.left().accept(this); rt = getQuantifierSince(left, right); popVariable(); break; case RELEASES: Formula rightAlways = binaryTempFormula.right().accept(this); pushVariable(); left = binaryTempFormula.left().accept(this); pushLevel(); pushVariable(); right = binaryTempFormula.right().accept(this); rt = getQuantifierRelease(rightAlways, left, right); popVariable(); popLevel(); popVariable(); break; case TRIGGERED: rightAlways = binaryTempFormula.right().accept(this); pushVariable(); left = binaryTempFormula.left().accept(this); pushLevel(); pushVariable(); right = binaryTempFormula.right().accept(this); rt = getQuantifierTrigger(rightAlways, left, right); popVariable(); popLevel(); popVariable(); break; default: throw new UnsupportedOperationException("Unsupported binary temporal operator:" + binaryTempFormula.op()); } popVariable(); popLevel(); popOperator(); return rt; } @Override public Expression visit(TempExpression tempExpression) { pushOperator(tempExpression.op()); pushVariable(); Expression localExpression = tempExpression.expression().accept(this); popOperator(); popVariable(); return localExpression; } private Formula getQuantifier(TemporalOperator op, Formula e) { Variable s1; Expression s0 = getVariablePrevQuant(); if (TemporalTranslator.ExplicitUnrolls) { switch (op) { case ALWAYS: s1 = (Variable) getVariable(); return e.forAll(s1.oneOf(s0.join(TRACE.reflexiveClosure()))); case EVENTUALLY: s1 = (Variable) getVariable(); return e.forSome(s1.oneOf(s0.join(TRACE.reflexiveClosure()))); case HISTORICALLY: s1 = (Variable) getVariable(); return e.forAll(s1.oneOf(s0.join(PREFIX.transpose().reflexiveClosure()))); case ONCE: s1 = (Variable) getVariable(); return e.forSome(s1.oneOf(s0.join(PREFIX.transpose().reflexiveClosure()))); case BEFORE: Expression v2 = getVariable(); e = v2.some().and(e); return e; default: return e; } } else { Variable l1; Expression l0 = getLevelPrevQuant(); switch (op) { case ALWAYS: s1 = (Variable) getVariable(); l1 = (Variable) getLevel(); Expression rng; // (l1 = l0 && l1 != last) => s0.*next else State rng = (l1.eq(l0).and(l1.eq(L_LAST).not())).thenElse(s0.join(PREFIX.reflexiveClosure()),STATE); // l1.start.*trace & ((l1 = l0 || l1 = last) => s0.*next else State) rng = rng.intersection(l1.join(START).join(PREFIX.reflexiveClosure())); // all l1 : l0.*next, s1 : (l1.start.*next & ((l1 = l0 || l1 = last) => s0.*next else State)) | e return e.forAll(s1.oneOf(rng)).forAll(l1.oneOf(l0.join(L_PREFIX.reflexiveClosure()))); case EVENTUALLY: s1 = (Variable) getVariable(); l1 = (Variable) getLevel(); // (l1 = l0 && l1 != last) => s0.*next else State rng = (l1.eq(l0).and(l1.eq(L_LAST).not())).thenElse(s0.join(PREFIX.reflexiveClosure()),STATE); // l1.start.*trace & ((l1 = l0 || l1 = last) => s0.*next else State) rng = rng.intersection(l1.join(START).join(PREFIX.reflexiveClosure())); // some l1 : l0.*next, s1 : (l1.start.*next & ((l1 = l0 || l1 = last) => s0.*next else State)) | e return e.forSome(s1.oneOf(rng)).forSome(l1.oneOf(l0.join(L_PREFIX.reflexiveClosure()))); case HISTORICALLY: s1 = (Variable) getVariable(); l1 = (Variable) getLevel(); // l1 = l0 => s0.*prev else State rng = l1.eq(l0).thenElse(s0.join(PREFIX.transpose().reflexiveClosure()),STATE); // l1.start.*prev & (l1 = l0 => s0.*prev else State) rng = rng.intersection(l1.join(START).join(PREFIX.reflexiveClosure())); // all l1 : l0.*prev, s1 : l1.start.*prev & (l1 = l0 => s0.*prev else State) | e return e.forAll(s1.oneOf(rng)).forAll(l1.oneOf(l0.join(L_PREFIX.transpose().reflexiveClosure()))); case ONCE: s1 = (Variable) getVariable(); l1 = (Variable) getLevel(); // l1 = l0 => s0.*prev else State rng = l1.eq(l0).thenElse(s0.join(PREFIX.transpose().reflexiveClosure()),STATE); // l1.start.*prev & (l1 = l0 => s0.*prev else State) rng = rng.intersection(l1.join(START).join(PREFIX.reflexiveClosure())); // some l1 : l0.*prev, s1 : l1.start.*prev & (l1 = l0 => s0.*prev else State) | e return e.forSome(s1.oneOf(rng)).forSome(l1.oneOf(l0.join(L_PREFIX.transpose().reflexiveClosure()))); case BEFORE: // (s0 = loop && l0 != first) => last else s0.prev Expression s0n = getVariable(); // (s0 = loop && l0 != first) => l0.prev else l0 Expression l0n = getLevel(); // some (s0 = loop && l0 != first) => last else s0.prev && e e = s0n.some().and(e); return e; default: return e; } } } private Formula getQuantifierUntil(Formula left, Formula right) { Variable r = getVariableUntil(true); Variable l = getVariableUntil(false); Expression prev_l = getVariablePrevQuantUntil(false); if (TemporalTranslator.ExplicitUnrolls) { Formula nfleft = left.forAll(l.oneOf(upTo(prev_l, r, false))); nfleft = right.and(nfleft); return nfleft.forSome(r.oneOf(prev_l.join(TRACE.reflexiveClosure()))); } else { Variable vl = getLevelUntil(); Expression prev_vl = getLevelPrevQuantUntil(); Expression rng1 = (vl.eq(prev_vl.join(L_PREFIX))).thenElse(r.join(PREFIX.transpose().closure()), STATE); Expression rng0 = (vl.eq(prev_vl)).thenElse(upTo(prev_l, r, false),prev_l.join(PREFIX.reflexiveClosure()).union((vl.join(START).join(PREFIX.reflexiveClosure()).intersection(rng1)))); Formula nfleft = left.forAll(l.oneOf(rng0)); nfleft = right.and(nfleft); Expression rng = vl.eq(prev_vl).thenElse(prev_l.join(PREFIX.reflexiveClosure()),STATE); return nfleft.forSome(r.oneOf(rng.intersection(vl.join(START).join(TRACE.reflexiveClosure())))).forSome(vl.oneOf(prev_vl.join(L_PREFIX.reflexiveClosure()))); } } private Formula getQuantifierSince(Formula left, Formula right) { Variable r = getVariableUntil(true); Variable l = getVariableUntil(false); Expression prev_l = getVariablePrevQuantUntil(false); if (TemporalTranslator.ExplicitUnrolls) { Formula nfleft = left.forAll(l.oneOf(downTo(prev_l, r, false))); nfleft = right.and(nfleft); return nfleft .forSome(r.oneOf(prev_l.join(PREFIX.transpose().reflexiveClosure()))); } else { Variable vl = getLevelUntil(); Expression prev_vl = getLevelPrevQuantUntil(); Expression rng1 = (prev_vl.eq(vl.join(L_PREFIX))).thenElse(prev_l.join(PREFIX.transpose().reflexiveClosure()), STATE); Expression rng0 = (vl.eq(prev_vl)).thenElse(downTo(prev_l, r, false),r.join(PREFIX.closure()).union((prev_vl.join(START).join(PREFIX.reflexiveClosure()).intersection(rng1)))); Formula nfleft = left.forAll(l.oneOf(rng0)); nfleft = right.and(nfleft); Expression rng = vl.eq(prev_vl).thenElse(prev_l.join(PREFIX.transpose().reflexiveClosure()),STATE); return nfleft.forSome(r.oneOf(rng.intersection(vl.join(START).join(PREFIX.reflexiveClosure())))).forSome(vl.oneOf(prev_vl.join(L_PREFIX.transpose().reflexiveClosure()))); } } private Formula getQuantifierRelease(Formula always, Formula left, Formula right) { Variable r = getVariableRelease(true, false); Variable l = getVariableRelease(false, false); Variable v = getVariableRelease(false, true); Formula alw; Formula nfleft; Formula nfright; if (TemporalTranslator.ExplicitUnrolls) { alw = always.forAll(v.oneOf(getVariablePrevQuantRelease(false, true).join(TRACE.reflexiveClosure()))); nfleft = right.forAll(l.oneOf(upTo(getVariablePrevQuantRelease(false, true), r, true))); nfright = left.and(nfleft); nfright = nfright .forSome(r.oneOf(getVariablePrevQuantRelease(false, true).join(TRACE.reflexiveClosure()))); return alw.or(nfright); } else throw new UnsupportedOperationException("Releases for alterative past encoding."); } private Formula getQuantifierTrigger(Formula always, Formula left, Formula right) { Variable r = getVariableRelease(true, false); Variable l = getVariableRelease(false, false); Variable v = getVariableRelease(false, true); Formula alw; Formula nfleft; Formula nfright; if (TemporalTranslator.ExplicitUnrolls) { alw = always.forAll(v.oneOf(getVariablePrevQuantRelease(false, true).join(PREFIX.transpose().reflexiveClosure()))); nfleft = right.forAll(l.oneOf(downTo(getVariablePrevQuantRelease(false, true), r, true))); nfright = left.and(nfleft); nfright = nfright .forSome(r.oneOf(getVariablePrevQuantRelease(false, true).join(PREFIX.transpose().reflexiveClosure()))); return alw.or(nfright); } else throw new UnsupportedOperationException("Triggered for alterative past encoding."); } /** * An expression representing all states between two states, considering loops. * * @param t1 * the expression representing the lower state * @param t2 * the expression representing the upper state * @param inc1 * whether lower inclusive * @param inc2 * whether upper inclusive * @return the expression representing the range states */ private Expression upTo(Expression t1, Expression t2, boolean inc2) { Formula c = t2.in(t1.join(PREFIX.reflexiveClosure())); Expression exp1 = PREFIX.reflexiveClosure(); Expression exp2 = PREFIX.closure(); Expression exp11 = TRACE.reflexiveClosure(); Expression exp12 = TRACE.closure(); Expression e1 = (t1.join(exp1)).intersection(t2.join(exp2.transpose())); Expression e21 = (t1.join(exp11)).intersection(t2.join(exp12.transpose())); Expression e22 = (t2.join(exp1)).intersection(t1.join(exp2.transpose())); Expression e2 = e21.difference(e22); Expression e = c.thenElse(e1, e2); if (inc2) e = e.union(t2); return e; } private Expression downTo(Expression t1, Expression t2, boolean inc2) { Expression exp1 = PREFIX.reflexiveClosure(); Expression exp2 = PREFIX.closure(); Expression e1 = (t1.join(exp1.transpose())).intersection(t2.join(exp2)); Expression e = e1; if (inc2) e = e.union(t2); return e; } /* Operators Context */ private List<TemporalOperator> operators = new ArrayList<TemporalOperator>(); private void pushOperator(TemporalOperator op) { operators.add(op); } private TemporalOperator getOperator() { return operators.get(operators.size() - 1); } private void popOperator() { operators.remove(operators.size() - 1); } /* Variables */ private List<Expression> variables = new ArrayList<Expression>(); private List<Expression> variables_lvl = new ArrayList<Expression>(); private int vars = 0; private void pushVariable() { if (variables.isEmpty()) { variables.add(FIRST); return; } switch (getOperator()) { case AFTER: case PRIME: if (TemporalTranslator.ExplicitUnrolls) variables.add(getVariable().join(TRACE)); else // s0.trace variables.add(getVariable().join(TRACE)); break; case BEFORE: if (TemporalTranslator.ExplicitUnrolls) variables.add(getVariable().join(PREFIX.transpose())); else // (s0 = loop && l0 != first) => last else s0.prev variables.add((getVariable().eq(LOOP).and(getLevelPrevQuant().eq(L_FIRST).not())).thenElse(LAST,getVariable().join(PREFIX.transpose()))); break; default: Variable v = Variable.unary("t" + vars); variables.add(v); vars++; } } private void pushLevel() { if (variables_lvl.isEmpty()) { variables_lvl.add(L_FIRST); return; } switch (getOperator()) { case AFTER: case PRIME: // (s0 = last && l0 != last) => l0.next else l0 variables_lvl.add((getVariable().eq(LAST).and(getLevel().eq(L_LAST).not())).thenElse(getLevel().join(L_PREFIX),getLevel())); break; case BEFORE: // (s0 = loop && l0 != first) => l0.prev else l0 variables_lvl.add((getVariable().eq(LOOP).and(getLevel().eq(L_FIRST).not())).thenElse(getLevel().join(L_PREFIX.transpose()),getLevel())); break; default: Variable v = Variable.unary("l" + vars); variables_lvl.add(v); } } /** * Used to initialize the translation at a time other than the initial one. * * @param state * the step of the trace in which to start the translation. */ private void pushVariable(int state) { if (variables.isEmpty()) { Expression s = FIRST; for (int i = 0; i < state; i++) s = s.join(TRACE); variables.add(s); } else throw new UnsupportedOperationException("No more vars."); } private void popVariable() { variables.remove(variables.size() - 1); } private void popLevel() { variables_lvl.remove(variables_lvl.size() - 1); } private Expression getVariable() { return variables.get(variables.size() - 1); } private Expression getLevel() { return variables_lvl.get(variables_lvl.size() - 1); } private Expression getVariablePrevQuant() { return variables.get(variables.size() - 2); } private Expression getLevelPrevQuant() { return variables_lvl.get(variables_lvl.size() - 2); } private Variable getVariableUntil(boolean sideIsRight) { if (!sideIsRight) { return (Variable) variables.get(variables.size() - 1); } else { return (Variable) variables.get(variables.size() - 2); } } private Variable getLevelUntil() { return (Variable) variables_lvl.get(variables_lvl.size() - 1); } private Variable getVariableRelease(boolean sideIsRight, boolean isAlways) { if (isAlways) { return (Variable) variables.get(variables.size() - 3); } else { if (!sideIsRight) { return (Variable) variables.get(variables.size() - 1); } else { return (Variable) variables.get(variables.size() - 2); } } } private Expression getVariablePrevQuantUntil(boolean sideIsRight) { if (!sideIsRight) { return variables.get(variables.size() - 3); } else { return variables.get(variables.size() - 2); } } private Expression getLevelPrevQuantUntil() { return variables_lvl.get(variables_lvl.size() - 2); } private Expression getVariablePrevQuantRelease(boolean sideIsRight, boolean isAlways) { if (isAlways) { return variables.get(variables.size() - 4); } else { if (!sideIsRight) { return variables.get(variables.size() - 3); } else { return variables.get(variables.size() - 2); } } } }
package BlueTurtle.TSE; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import org.junit.After; import org.junit.Before; import org.junit.Test; import BlueTurtle.gui.GUIController.ASAT; /** * Test for the JavaController class. * * @author BlueTurtle. * */ public class JavaControllerTest { private String checkStyleOutputFilePath = System.getProperty("user.dir") + "/src/test/resources/exampleCheckStyle1.xml"; private String pmdOutputFilePath = System.getProperty("user.dir") + "/src/test/resources/examplePmd1.xml"; private String findBugsOutputFilePath = System.getProperty("user.dir") + "/src/test/resources/exampleFindbugs1.xml"; private String outputPath = System.getProperty("user.dir") + "/src/test/resources/testOutput.js"; /** * Clear the attributes of JavaController. */ @Before public void setUp() { JavaController.setASATOutput(ASAT.CheckStyle, null); JavaController.setASATOutput(ASAT.PMD, null); JavaController.setASATOutput(ASAT.FindBugs, null); } // /** // * Delete the created files. // */ // @After // public void cleanUp() { // File f = new File(System.getProperty("user.dir") + "/src/main/resources/SummarizedOuput.js"); // if (f.exists()) { // f.delete(); /** * Test that the user direction path is the same. */ @Test public void testUserDir() { String expected = System.getProperty("user.dir"); String actual = JavaController.getUserDir(); assertEquals(expected, actual); } /** * Test that all files are null at first. */ @Test public void allFilesStringsAreNull() { assertTrue(JavaController.getCheckStyleOutputFile() == null && JavaController.getPmdOutputFile() == null && JavaController.getFindBugsOutputFile() == null); } /** * Test changing CheckStyle output file. */ @Test public void testChangingCheckStyleOutputFile() { String emptyFile = JavaController.getCheckStyleOutputFile(); File newFile = new File("newFile"); JavaController.setASATOutput(ASAT.CheckStyle, newFile); String checkStyleFile = JavaController.getCheckStyleOutputFile(); assertNotEquals(emptyFile, checkStyleFile); } /** * Test changing PMD output file. */ @Test public void testChangingPMDOutputFile() { String emptyFile = JavaController.getPmdOutputFile(); File newFile = new File("newFile"); JavaController.setASATOutput(ASAT.PMD, newFile); String pmdFile = JavaController.getPmdOutputFile(); assertNotEquals(emptyFile, pmdFile); } /** * Test changing FindBugs output file. */ @Test public void testChangingFindBugsOutputFile() { String emptyFile = JavaController.getFindBugsOutputFile(); File newFile = new File("newFile"); JavaController.setASATOutput(ASAT.FindBugs, newFile); String findBugsFile = JavaController.getFindBugsOutputFile(); assertNotEquals(emptyFile, findBugsFile); } /** * Test SetASATOutput with a null. */ @Test public void testSetOutputWithNull() { String currentFile = JavaController.getCheckStyleOutputFile(); JavaController.setASATOutput(ASAT.CheckStyle, null); String newFile = JavaController.getCheckStyleOutputFile(); assertEquals(currentFile, newFile); } // /** // * Test execute should output file. // * // * @throws IOException // * throws an exception if a problem is encountered while reading // * the file. // */ // @Test // public void testExecute() throws IOException { // JavaController.setASATOutput(ASAT.CheckStyle, new File(checkStyleOutputFilePath)); // JavaController.setASATOutput(ASAT.PMD, new File(pmdOutputFilePath)); // JavaController.setASATOutput(ASAT.FindBugs, new File(findBugsOutputFilePath)); // JavaController jc = new JavaController(); // jc.execute(); // assertTrue(new File(System.getProperty("user.dir") + "/src/main/resources/SummarizedOuput.js").exists()); }
package mariculture.core.handlers; import mariculture.core.Core; import mariculture.core.blocks.base.BlockFluid; import mariculture.core.items.ItemBuckets; import net.minecraft.block.Block; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraftforge.event.entity.player.FillBucketEvent; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.eventhandler.Event.Result.ALLOW; public class BucketHandler { @SubscribeEvent public void onFillBucket(FillBucketEvent event) { Block block = event.world.getBlock(event.target.blockX, event.target.blockY, event.target.blockZ); if (block instanceof BlockFluid) if (event.current.getItem() == Items.bucket) { ItemStack ret = ((ItemBuckets) Core.buckets).getBucket(block); if (ret != null) { event.result = ret; event.setResult(Result.ALLOW); } } } }
package com.cloudant.tests; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.UUID; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import com.cloudant.client.api.CloudantClient; import com.cloudant.client.api.Database; import com.cloudant.client.api.model.ReplicatorDocument; import com.cloudant.client.api.model.Response; import com.cloudant.client.api.model.ViewResult; @Ignore public class ReplicatorTest { private static Properties props ; private static Database db1; private static Database db2; private static String db1URI ; private static String db2URI ; private CloudantClient account; @Before public void setUp() { account = CloudantClientHelper.getClient(); db1 = account.database("lightcouch-db-test", true); db1URI = CloudantClientHelper.SERVER_URI.toString()+ "/lightcouch-db-test"; db2 = account.database("lightcouch-db-test-2", true); db1.syncDesignDocsWithDb(); db2.syncDesignDocsWithDb(); db2URI = CloudantClientHelper.SERVER_URI.toString()+ "/lightcouch-db-test-2"; } @After public void tearDown(){ account.deleteDB("lightcouch-db-test", "delete database"); account.deleteDB("lightcouch-db-test-2", "delete database"); account.shutdown(); } @Test public void replication() { account.replicator() .createTarget(true) .source(db1URI) .target(db2URI) .save(); } @Test public void replication_filteredWithQueryParams() { Map<String, Object> queryParams = new HashMap<String, Object>(); queryParams.put("somekey1", "value 1"); account.replicator() .createTarget(true) .source(db1URI) .target(db2URI) .filter("example/example_filter") .queryParams(queryParams) .save(); } @Test public void replicatorDB() throws Exception { String version = account.serverVersion(); if (version.startsWith("0") || version.startsWith("1.0")) { return; } // trigger a replication Response response = account.replicator() .source(db1URI) .target(db2URI).continuous(true) .createTarget(true) .save(); Thread.sleep(1000); // find all replicator docs List<ReplicatorDocument> replicatorDocs = account.replicator() .findAll(); assertThat(replicatorDocs.size(), is(not(0))); // find replicator doc ReplicatorDocument replicatorDoc = account.replicator() .replicatorDocId(response.getId()) .find(); // cancel a replication account.replicator() .replicatorDocId(replicatorDoc.getId()) .replicatorDocRev(replicatorDoc.getRevision()) .remove(); } @Test public void replication_conflict() throws Exception { String docId = generateUUID(); Foo foodb1 = new Foo(docId, "title"); Foo foodb2 = null; foodb1 = new Foo(docId, "titleX"); db1.save(foodb1); account.replicator().source(db1URI) .target(db2URI).replicatorDocId(docId) .save(); Thread.sleep(1000); //we need the replication to finish before continuing foodb2 = db2.find(Foo.class, docId); foodb2.setTitle("titleY"); db2.update(foodb2); foodb1 = db1.find(Foo.class, docId); foodb1.setTitle("titleZ"); db1.update(foodb1); account.replicator().source(db1URI) .target(db2URI).save(); Thread.sleep(1000); ViewResult<String[], String, Foo> conflicts = db2.view("conflicts/conflict") .includeDocs(true).queryView(String[].class, String.class, Foo.class); assertThat(conflicts.getRows().size(), is(not(0))); } private static String generateUUID() { return UUID.randomUUID().toString().replace("-", ""); } }
package com.github.fangzy.redis; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import redis.clients.jedis.Jedis; import java.util.concurrent.*; public class JLockTest extends AbstractTests { private static final Logger LOGGER = LoggerFactory.getLogger(JLockTest.class); @Autowired private Jedis jedis; @Before public void setUp() throws Exception { jedis.del("redis:lock:test"); } @Test public void testGetLock() throws Exception { ExecutorService exec = Executors.newCachedThreadPool(); CompletionService<Integer> completionService = new ExecutorCompletionService<>(exec); for (int n = 0; n < 20; n++) { completionService.submit(new TestThread(0)); } int i = 0; for (int n = 0; n < 20; n++) { i += completionService.take().get(); } exec.shutdown(); Assert.assertEquals(20, i); } @Test public void testGetLock1() throws Exception { ExecutorService exec = Executors.newFixedThreadPool(25); CompletionService<Integer> completionService = new ExecutorCompletionService<>(exec); for (int n = 0; n < 5; n++) { completionService.submit(new TestThread(2000)); } int i = 0; for (int n = 0; n < 5; n++) { i += completionService.take().get(); } exec.shutdown(); Assert.assertEquals(1, i); } @Test public void testCheckLock() throws Exception { ExecutorService exec = Executors.newCachedThreadPool(); CompletionService<Integer> completionService = new ExecutorCompletionService<>(exec); for (int n = 0; n < 20; n++) { completionService.submit(new TestCheckLockThread(2000)); } int i = 0; for (int n = 0; n < 20; n++) { i += completionService.take().get(); } exec.shutdown(); Assert.assertEquals(1, i); } @Test public void testReleaseLock() throws Exception { JLock.getLock("test"); boolean existsBefore = jedis.exists("redis:lock:test"); JLock.releaseLock("test"); boolean existsAfter = jedis.exists("redis:lock:test"); Assert.assertTrue(existsBefore); Assert.assertFalse(existsAfter); } class TestThread implements Callable<Integer> { private final Logger logger = LoggerFactory.getLogger(getClass()); private int i = 0; public TestThread(int i) { this.i = i; } @Override public Integer call() throws Exception { int m = 0; try { logger.debug("start"); if (!JLock.getLock("test", i)) { logger.debug("timeout"); m = 0; } else { logger.debug("get lock"); if (i == 0) { Thread.sleep(1000); JLock.releaseLock("test"); } m = 1; } } catch (Exception e) { logger.error("An unexpected error occurred.", e); } return m; } } class TestCheckLockThread implements Callable<Integer> { private final Logger logger = LoggerFactory.getLogger(getClass()); private int i = 0; public TestCheckLockThread(int i) { this.i = i; } @Override public Integer call() throws Exception { int m = 0; try { logger.debug("start"); if (!JLock.checkLock("test", i)) { logger.debug("return"); m = 0; } else { logger.debug("get lock"); Thread.sleep(1000); m = 1; } } catch (Exception e) { logger.error("An unexpected error occurred.", e); } return m; } } }
package me.unrealization.jeeves.bot; import sx.blah.discord.handle.obj.IMessage; import me.unrealization.jeeves.interfaces.BotCommand; public class TaskHandler implements Runnable { private IMessage message; private BotCommand command; private String[] arguments; public TaskHandler(IMessage message, BotCommand command, String[] arguments) { this.message = message; this.command = command; this.arguments = arguments; } @Override public void run() { this.command.execute(message, arguments); } public void start() { Thread thread = new Thread(this); thread.start(); } }
package com.queen.acceptance; import com.airhacks.afterburner.injection.Injector; import com.google.code.tempusfugit.temporal.WaitFor; import com.queen.counter.clock.ClockView; import com.queen.di.SpringApplicationConfiguration; import javafx.geometry.VerticalDirection; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.shape.Rectangle; import javafx.scene.text.Text; import javafx.stage.Stage; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.testfx.framework.junit.ApplicationTest; import java.util.Optional; import static com.google.code.tempusfugit.temporal.Duration.millis; import static com.google.code.tempusfugit.temporal.Timeout.timeout; import static org.testfx.api.FxAssert.assertContext; import static org.testfx.api.FxAssert.verifyThat; public class CounterAppIT extends ApplicationTest { private final ApplicationContext injector = new AnnotationConfigApplicationContext(SpringApplicationConfiguration.class); @Override public void start(Stage stage) throws Exception { Injector.setConfigurationSource(null); Injector.setInstanceSupplier(new Injector.InstanceProvider() { @Override public boolean isInjectionAware() { return true; } @Override public boolean isScopeAware() { return true; } @Override public Object instantiate(Class<?> c) { return injector.getBean(c); } }); ClockView clockView = new ClockView(); Scene scene = new Scene(clockView.getView(), 800, 600); stage.setScene(scene); stage.show(); } @Test public void scroll_dramatic_test() throws InterruptedException { Group gs = assertContext().getNodeFinder().lookup("#group").queryFirst(); String id = gs.getChildren().stream().filter(r -> r.getClass().equals(Rectangle.class)).filter(r -> r.getTranslateY() == 0).findAny().get().getId(); Text l = (Text) gs.getChildren().stream().filter(lbl -> lbl.getClass().equals(Text.class)).filter(lbl1 -> lbl1.getId().equals(id)).findAny().get(); String t = l.getText(); moveTo("#group"); scroll(VerticalDirection.DOWN); WaitFor.waitUntil(timeout(millis(650))); verifyThat("#group", (Group g) -> { Optional<Node> r = gs.getChildren().stream().filter(rs -> rs.getClass().equals(Rectangle.class)).filter(rt -> rt.getId().equals(id)).findAny(); if (r.isPresent()) { String lb = gs.getChildren().stream().filter(rk -> rk.getClass().equals(Text.class)).filter(tr -> tr.getId().equals(id)).map(tt -> ((Text) tt).getText()).findAny().get(); int ints = new Integer(lb); int intb = new Integer(t); return r.get().getTranslateY() == 180 && ints == intb - 4; } return false; }); } }
package net.addradio.codec.mpeg.audio; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.addradio.codec.id3.model.ID3Tag; import net.addradio.codec.mpeg.audio.codecs.MPEGAudioCodecException; import net.addradio.codec.mpeg.audio.model.MPEGAudioContent; import net.addradio.codec.mpeg.audio.model.MPEGAudioFrame; import net.addradio.codec.mpeg.audio.tools.MPEGAudioContentCollectorHandler; import net.addradio.codec.mpeg.audio.tools.MPEGAudioContentFilter; import net.addradio.codec.mpeg.audio.tools.MPEGAudioContentHandler; import net.addradio.codec.mpeg.audio.tools.MPEGAudioFirstContentOnlyHandler; /** * MPEGAudio. */ public class MPEGAudio { /** {@link Logger} LOG. */ private final static Logger LOG = LoggerFactory.getLogger(MPEGAudio.class); /** * decode. * @param file {@link File} * @return {@link DecodingResult} or {@code null} if file could not be opened. */ public static final DecodingResult decode(final File file) { return decode(file, MPEGAudioContentFilter.ACCEPT_ALL); } /** * decode. * @param file {@link File} * @param filter {@link MPEGAudioContentFilter} * @return {@link DecodingResult} or {@code null} if file could not be opened. */ public static DecodingResult decode(final File file, final MPEGAudioContentFilter filter) { try (final InputStream is = new FileInputStream(file)) { return decode(is, filter); } catch (final IOException e1) { MPEGAudio.LOG.error(e1.getLocalizedMessage(), e1); } return null; } /** * decode. * @param is {@link InputStream} * @return {@link DecodingResult} */ public static final DecodingResult decode(final InputStream is) { return decode(is, MPEGAudioContentFilter.ACCEPT_ALL); } /** * decode. * @param is {@link InputStream} * @param filter {@link MPEGAudioContentFilter} * @return {@link DecodingResult} */ public static DecodingResult decode(final InputStream is, final MPEGAudioContentFilter filter) { final MPEGAudioContentCollectorHandler handler = new MPEGAudioContentCollectorHandler(); final long sb = decode(is, filter, handler); return new DecodingResult(sb, handler.getContents()); } /** * decode. * @param is {@link InputStream} * @param filter {@link MPEGAudioContentFilter} * @param handler {@link MPEGAudioContentHandler} * @return {@code long} number of skipped bits or {@code -1} in case of occurring IOException; */ public static long decode(final InputStream is, final MPEGAudioContentFilter filter, final MPEGAudioContentHandler handler) { try (final MPEGAudioFrameInputStream mafis = new MPEGAudioFrameInputStream(is)) { MPEGAudioContent frame = null; while ((frame = mafis.readFrame()) != null) { if (filter.accept(frame)) { if (handler.handle(frame)) { break; } } } return mafis.getSkippedBits(); } catch (final IOException e) { MPEGAudio.LOG.error(e.getLocalizedMessage(), e); } return -1; } /** * decode. * @param fileName {@link String} * @return {@link DecodingResult} or {@code null} if file could not be opened. */ public static final DecodingResult decode(final String fileName) { return decode(fileName != null ? new File(fileName) : null); } /** * decode. * @param fileName {@link String} * @param filter {@link MPEGAudioContentFilter} * @return {@link DecodingResult} or {@code null} if file could not be opened. */ public static final DecodingResult decode(final String fileName, final MPEGAudioContentFilter filter) { return decode(fileName != null ? new File(fileName) : null, filter); } /** * decodeFirstID3Tag. * @param is {@link InputStream} * @return {@link ID3Tag} */ public static ID3Tag decodeFirstID3Tag(final InputStream is) { return (ID3Tag) decodeFirstMPEGAudioContent(is, MPEGAudioContentFilter.ID3_TAGS); } /** * decodeFirstMPEGAudioContent. * @param is {@link InputStream} * @param filter {@link MPEGAudioContentFilter} * @return {@link MPEGAudioContent} first content decoded from stream matching the filter's criteria or {@code null} if no adequate content will be found. */ public static MPEGAudioContent decodeFirstMPEGAudioContent(final InputStream is, final MPEGAudioContentFilter filter) { final MPEGAudioFirstContentOnlyHandler handler = new MPEGAudioFirstContentOnlyHandler(); decode(is, filter, handler); return handler.getFirstContent(); } /** * decodeFirstMPEGAudioFrame. * @param buffer {@code byte[]} * @return {@link MPEGAudioFrame} or {@code null} if nothing could be decoded. */ public static MPEGAudioFrame decodeFirstMPEGAudioFrame(final byte[] buffer) { return decodeFirstMPEGAudioFrame(new ByteArrayInputStream(buffer)); } /** * decodeFirstMPEGAudioFrame. * @param is {@link InputStream} * @return {@link MPEGAudioFrame} */ public static MPEGAudioFrame decodeFirstMPEGAudioFrame(final InputStream is) { return (MPEGAudioFrame) decodeFirstMPEGAudioContent(is, MPEGAudioContentFilter.MPEG_AUDIO_FRAMES); } /** * encode. * @param frames {@link List}{@code <}{@link MPEGAudioContent}{@code >} * @return {@code byte[]} or {@code null} if an error occurred. */ public static byte[] encode(final List<? extends MPEGAudioContent> frames) { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { encode(frames, baos); return baos.toByteArray(); } catch (final IOException e) { MPEGAudio.LOG.error(e.getLocalizedMessage(), e); } return null; } /** * encode. * @param frames {@link List}{@code <}{@link MPEGAudioContent}{@code >} * @param os {@link OutputStream} * @throws IOException due to IO problems. */ public static void encode(final List<? extends MPEGAudioContent> frames, final OutputStream os) throws IOException { try (MPEGAudioFrameOutputStream mafos = new MPEGAudioFrameOutputStream(os)) { for (final MPEGAudioContent mpegAudioFrame : frames) { try { mafos.writeFrame(mpegAudioFrame); mafos.flush(); } catch (final MPEGAudioCodecException e) { MPEGAudio.LOG.error(e.getLocalizedMessage(), e); } } } } }