answer stringlengths 17 10.2M |
|---|
package eu.bitwalker.useragentutils;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Enum constants for most common browsers, including e-mail clients and bots.
* @author harald
*
*/
public enum Browser {
/**
* Outlook email client
*/
OUTLOOK( Manufacturer.MICROSOFT, null, 100, "Outlook", new String[] {"MSOffice"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, "MSOffice (([0-9]+))"), // before IE7
/**
* Microsoft Outlook 2007 identifies itself as MSIE7 but uses the html rendering engine of Word 2007.
* Example user agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 1.1.4322; MSOffice 12)
*/
OUTLOOK2007( Manufacturer.MICROSOFT, Browser.OUTLOOK, 107, "Outlook 2007", new String[] {"MSOffice 12"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, null), // before IE7
OUTLOOK2013( Manufacturer.MICROSOFT, Browser.OUTLOOK, 109, "Outlook 2013", new String[] {"Microsoft Outlook 15"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, null), // before IE7
OUTLOOK2010( Manufacturer.MICROSOFT, Browser.OUTLOOK, 108, "Outlook 2010", new String[] {"MSOffice 14", "Microsoft Outlook 14"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, null), // before IE7
/**
* Family of Internet Explorer browsers
*/
IE( Manufacturer.MICROSOFT, null, 1, "Internet Explorer", new String[] { "MSIE", "Trident", "IE " }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, "MSIE (([\\d]+)\\.([\\w]+))" ), // before Mozilla
/**
* Since version 7 Outlook Express is identifying itself. By detecting Outlook Express we can not
* identify the Internet Explorer version which is probably used for the rendering.
* Obviously this product is now called Windows Live Mail Desktop or just Windows Live Mail.
*/
OUTLOOK_EXPRESS7( Manufacturer.MICROSOFT, Browser.IE, 110, "Windows Live Mail", new String[] {"Outlook-Express/7.0"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.TRIDENT, null), // before IE7, previously known as Outlook Express. First released in 2006, offered with different name later
/**
* Since 2007 the mobile edition of Internet Explorer identifies itself as IEMobile in the user-agent.
* If previous versions have to be detected, use the operating system information as well.
*/
IEMOBILE11( Manufacturer.MICROSOFT, Browser.IE, 125, "IE Mobile 11", new String[] { "IEMobile/11" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE strings
IEMOBILE10( Manufacturer.MICROSOFT, Browser.IE, 124, "IE Mobile 10", new String[] { "IEMobile/10" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE strings
IEMOBILE9( Manufacturer.MICROSOFT, Browser.IE, 123, "IE Mobile 9", new String[] { "IEMobile/9" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE strings
IEMOBILE7( Manufacturer.MICROSOFT, Browser.IE, 121, "IE Mobile 7", new String[] { "IEMobile 7" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE strings
IEMOBILE6( Manufacturer.MICROSOFT, Browser.IE, 120, "IE Mobile 6", new String[] { "IEMobile 6" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE
IE11( Manufacturer.MICROSOFT, Browser.IE, 95, "Internet Explorer 11", new String[] { "Trident/7", "IE 11." }, new String[] {"MSIE 7"}, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, "(?:Trident\\/7|IE)(?:\\.[0-9]*;)?(?:.*rv:| )(([0-9]+)\\.?([0-9]+))" ), // before Mozilla
IE10( Manufacturer.MICROSOFT, Browser.IE, 92, "Internet Explorer 10", new String[] { "MSIE 10" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
IE9( Manufacturer.MICROSOFT, Browser.IE, 90, "Internet Explorer 9", new String[] { "MSIE 9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
IE8( Manufacturer.MICROSOFT, Browser.IE, 80, "Internet Explorer 8", new String[] { "MSIE 8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
IE7( Manufacturer.MICROSOFT, Browser.IE, 70, "Internet Explorer 7", new String[] { "MSIE 7" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE
IE6( Manufacturer.MICROSOFT, Browser.IE, 60, "Internet Explorer 6", new String[] { "MSIE 6" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
IE5_5( Manufacturer.MICROSOFT, Browser.IE, 55, "Internet Explorer 5.5", new String[] { "MSIE 5.5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE
IE5( Manufacturer.MICROSOFT, Browser.IE, 50, "Internet Explorer 5", new String[] { "MSIE 5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
/**
* Google Chrome browser
*/
CHROME( Manufacturer.GOOGLE, null, 1, "Chrome", new String[] { "Chrome", "CrMo", "CriOS" }, new String[] { "OPR/", "Web Preview" } , BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "Chrome\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)" ), // before Mozilla
CHROME_MOBILE( Manufacturer.GOOGLE, Browser.CHROME, 100, "Chrome Mobile", new String[] { "CrMo","CriOS", "Mobile Safari" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, "(?:CriOS|CrMo|Chrome)\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)" ),
CHROME40( Manufacturer.GOOGLE, Browser.CHROME, 45, "Chrome 40", new String[] { "Chrome/40" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME39( Manufacturer.GOOGLE, Browser.CHROME, 44, "Chrome 39", new String[] { "Chrome/39" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME38( Manufacturer.GOOGLE, Browser.CHROME, 43, "Chrome 38", new String[] { "Chrome/38" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME37( Manufacturer.GOOGLE, Browser.CHROME, 42, "Chrome 37", new String[] { "Chrome/37" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME36( Manufacturer.GOOGLE, Browser.CHROME, 41, "Chrome 36", new String[] { "Chrome/36" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME35( Manufacturer.GOOGLE, Browser.CHROME, 40, "Chrome 35", new String[] { "Chrome/35" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME34( Manufacturer.GOOGLE, Browser.CHROME, 39, "Chrome 34", new String[] { "Chrome/34" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME33( Manufacturer.GOOGLE, Browser.CHROME, 38, "Chrome 33", new String[] { "Chrome/33" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME32( Manufacturer.GOOGLE, Browser.CHROME, 37, "Chrome 32", new String[] { "Chrome/32" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME31( Manufacturer.GOOGLE, Browser.CHROME, 36, "Chrome 31", new String[] { "Chrome/31" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME30( Manufacturer.GOOGLE, Browser.CHROME, 35, "Chrome 30", new String[] { "Chrome/30" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME29( Manufacturer.GOOGLE, Browser.CHROME, 34, "Chrome 29", new String[] { "Chrome/29" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME28( Manufacturer.GOOGLE, Browser.CHROME, 33, "Chrome 28", new String[] { "Chrome/28" }, new String[] { "OPR/", "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME27( Manufacturer.GOOGLE, Browser.CHROME, 32, "Chrome 27", new String[] { "Chrome/27" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME26( Manufacturer.GOOGLE, Browser.CHROME, 31, "Chrome 26", new String[] { "Chrome/26" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME25( Manufacturer.GOOGLE, Browser.CHROME, 30, "Chrome 25", new String[] { "Chrome/25" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME24( Manufacturer.GOOGLE, Browser.CHROME, 29, "Chrome 24", new String[] { "Chrome/24" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME23( Manufacturer.GOOGLE, Browser.CHROME, 28, "Chrome 23", new String[] { "Chrome/23" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME22( Manufacturer.GOOGLE, Browser.CHROME, 27, "Chrome 22", new String[] { "Chrome/22" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME21( Manufacturer.GOOGLE, Browser.CHROME, 26, "Chrome 21", new String[] { "Chrome/21" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME20( Manufacturer.GOOGLE, Browser.CHROME, 25, "Chrome 20", new String[] { "Chrome/20" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME19( Manufacturer.GOOGLE, Browser.CHROME, 24, "Chrome 19", new String[] { "Chrome/19" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME18( Manufacturer.GOOGLE, Browser.CHROME, 23, "Chrome 18", new String[] { "Chrome/18" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME17( Manufacturer.GOOGLE, Browser.CHROME, 22, "Chrome 17", new String[] { "Chrome/17" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME16( Manufacturer.GOOGLE, Browser.CHROME, 21, "Chrome 16", new String[] { "Chrome/16" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME15( Manufacturer.GOOGLE, Browser.CHROME, 20, "Chrome 15", new String[] { "Chrome/15" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME14( Manufacturer.GOOGLE, Browser.CHROME, 19, "Chrome 14", new String[] { "Chrome/14" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME13( Manufacturer.GOOGLE, Browser.CHROME, 18, "Chrome 13", new String[] { "Chrome/13" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME12( Manufacturer.GOOGLE, Browser.CHROME, 17, "Chrome 12", new String[] { "Chrome/12" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME11( Manufacturer.GOOGLE, Browser.CHROME, 16, "Chrome 11", new String[] { "Chrome/11" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME10( Manufacturer.GOOGLE, Browser.CHROME, 15, "Chrome 10", new String[] { "Chrome/10" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME9( Manufacturer.GOOGLE, Browser.CHROME, 10, "Chrome 9", new String[] { "Chrome/9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME8( Manufacturer.GOOGLE, Browser.CHROME, 5, "Chrome 8", new String[] { "Chrome/8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
OMNIWEB( Manufacturer.OTHER, null, 2, "Omniweb", new String[] { "OmniWeb" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null),
SAFARI( Manufacturer.APPLE, null, 1, "Safari", new String[] { "Safari" }, new String[] { "OPR/", "Coast/", "Web Preview","Googlebot-Mobile" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "Version\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)" ), // before AppleWebKit
BLACKBERRY10( Manufacturer.BLACKBERRY, Browser.SAFARI, 10, "BlackBerry", new String[] { "BB10" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, null),
MOBILE_SAFARI( Manufacturer.APPLE, Browser.SAFARI, 2, "Mobile Safari", new String[] { "Mobile Safari","Mobile/" }, new String[] { "Coast/", "Googlebot-Mobile" }, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, null ), // before Safari
SILK( Manufacturer.AMAZON, Browser.SAFARI, 15, "Silk", new String[] { "Silk/" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "Silk\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\-[\\w]+)?)" ),
SAFARI7( Manufacturer.APPLE, Browser.SAFARI, 7, "Safari 7", new String[] { "Version/7" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit
SAFARI6( Manufacturer.APPLE, Browser.SAFARI, 6, "Safari 6", new String[] { "Version/6" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit
SAFARI5( Manufacturer.APPLE, Browser.SAFARI, 3, "Safari 5", new String[] { "Version/5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit
SAFARI4( Manufacturer.APPLE, Browser.SAFARI, 4, "Safari 4", new String[] { "Version/4" }, new String[] { "Googlebot-Mobile" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit
COAST( Manufacturer.OPERA, null, 500, "Opera", new String[] { " Coast/" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, "Coast\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
COAST1( Manufacturer.OPERA, Browser.COAST, 501, "Opera", new String[] { " Coast/1." }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, "Coast\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA( Manufacturer.OPERA, null, 1, "Opera", new String[] { " OPR/", "Opera" }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, "Opera\\/(([\\d]+)\\.([\\w]+))"), // before MSIE
OPERA_MINI( Manufacturer.OPERA, Browser.OPERA, 20, "Opera Mini", new String[] { "Opera Mini"}, null, BrowserType.MOBILE_BROWSER, RenderingEngine.PRESTO, null), // Opera for mobile devices
OPERA25( Manufacturer.OPERA, Browser.OPERA, 25, "Opera 25", new String[] { "OPR/25." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA24( Manufacturer.OPERA, Browser.OPERA, 24, "Opera 24", new String[] { "OPR/24." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA23( Manufacturer.OPERA, Browser.OPERA, 23, "Opera 23", new String[] { "OPR/23." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA20( Manufacturer.OPERA, Browser.OPERA, 21, "Opera 20", new String[] { "OPR/20." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA19( Manufacturer.OPERA, Browser.OPERA, 19, "Opera 19", new String[] { "OPR/19." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA18( Manufacturer.OPERA, Browser.OPERA, 18, "Opera 18", new String[] { "OPR/18." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA17( Manufacturer.OPERA, Browser.OPERA, 17, "Opera 17", new String[] { "OPR/17." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA16( Manufacturer.OPERA, Browser.OPERA, 16, "Opera 16", new String[] { "OPR/16." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA15( Manufacturer.OPERA, Browser.OPERA, 15, "Opera 15", new String[] { "OPR/15." }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "OPR\\/(([\\d]+)\\.([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"),
OPERA12( Manufacturer.OPERA, Browser.OPERA, 12, "Opera 12", new String[] { "Opera/12", "Version/12." }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, "Version\\/(([\\d]+)\\.([\\w]+))"),
OPERA11( Manufacturer.OPERA, Browser.OPERA, 11, "Opera 11", new String[] { "Version/11." }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, "Version\\/(([\\d]+)\\.([\\w]+))"),
OPERA10( Manufacturer.OPERA, Browser.OPERA, 10, "Opera 10", new String[] { "Opera/9.8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, "Version\\/(([\\d]+)\\.([\\w]+))"),
OPERA9( Manufacturer.OPERA, Browser.OPERA, 5, "Opera 9", new String[] { "Opera/9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, null),
KONQUEROR( Manufacturer.OTHER, null, 1, "Konqueror", new String[] { "Konqueror"}, null, BrowserType.WEB_BROWSER, RenderingEngine.KHTML, "Konqueror\\/(([0-9]+)\\.?([\\w]+)?(-[\\w]+)?)" ),
DOLFIN2( Manufacturer.SAMSUNG, null, 1, "Samsung Dolphin 2", new String[] { "Dolfin/2" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, null ), // webkit based browser for the bada os
/*
* Apple WebKit compatible client. Can be a browser or an application with embedded browser using UIWebView.
*/
APPLE_WEB_KIT( Manufacturer.APPLE, null, 50, "Apple WebKit", new String[] { "AppleWebKit" }, new String[] { "OPR/", "Web Preview", "Googlebot-Mobile" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit
APPLE_ITUNES( Manufacturer.APPLE, Browser.APPLE_WEB_KIT, 52, "iTunes", new String[] { "iTunes" }, null, BrowserType.APP, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit
APPLE_APPSTORE( Manufacturer.APPLE, Browser.APPLE_WEB_KIT, 53, "App Store", new String[] { "MacAppStore" }, null, BrowserType.APP, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit
ADOBE_AIR( Manufacturer.ADOBE, Browser.APPLE_WEB_KIT, 1, "Adobe AIR application", new String[] { "AdobeAIR" }, null, BrowserType.APP, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit
LOTUS_NOTES( Manufacturer.OTHER, null, 3, "Lotus Notes", new String[] { "Lotus-Notes" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, "Lotus-Notes\\/(([\\d]+)\\.([\\w]+))"), // before Mozilla
CAMINO( Manufacturer.OTHER, null, 5, "Camino", new String[] { "Camino" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "Camino\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)" ), // using Gecko Engine
CAMINO2( Manufacturer.OTHER, Browser.CAMINO, 17, "Camino 2", new String[] { "Camino/2" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FLOCK( Manufacturer.OTHER, null, 4, "Flock", new String[]{"Flock"}, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "Flock\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)"),
FIREFOX( Manufacturer.MOZILLA, null, 10, "Firefox", new String[] { "Firefox" }, new String[] {"ggpht.com"}, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "Firefox\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"), // using Gecko Engine
FIREFOX3MOBILE( Manufacturer.MOZILLA, Browser.FIREFOX, 31, "Firefox 3 Mobile", new String[] { "Firefox/3.5 Maemo" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX_MOBILE( Manufacturer.MOZILLA, Browser.FIREFOX, 200, "Firefox Mobile", new String[] { "Mobile" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX_MOBILE23(Manufacturer.MOZILLA, FIREFOX_MOBILE, 223, "Firefox Mobile 23", new String[] { "Firefox/23" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX40( Manufacturer.MOZILLA, Browser.FIREFOX, 217, "Firefox 40", new String[] { "Firefox/40" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX39( Manufacturer.MOZILLA, Browser.FIREFOX, 216, "Firefox 39", new String[] { "Firefox/39" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX38( Manufacturer.MOZILLA, Browser.FIREFOX, 215, "Firefox 38", new String[] { "Firefox/38" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX37( Manufacturer.MOZILLA, Browser.FIREFOX, 214, "Firefox 37", new String[] { "Firefox/37" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX36( Manufacturer.MOZILLA, Browser.FIREFOX, 213, "Firefox 36", new String[] { "Firefox/36" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX35( Manufacturer.MOZILLA, Browser.FIREFOX, 212, "Firefox 35", new String[] { "Firefox/35" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX34( Manufacturer.MOZILLA, Browser.FIREFOX, 211, "Firefox 34", new String[] { "Firefox/34" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX33( Manufacturer.MOZILLA, Browser.FIREFOX, 210, "Firefox 33", new String[] { "Firefox/33" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX32( Manufacturer.MOZILLA, Browser.FIREFOX, 109, "Firefox 32", new String[] { "Firefox/32" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX31( Manufacturer.MOZILLA, Browser.FIREFOX, 310, "Firefox 31", new String[] { "Firefox/31" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX30( Manufacturer.MOZILLA, Browser.FIREFOX, 300, "Firefox 30", new String[] { "Firefox/30" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX29( Manufacturer.MOZILLA, Browser.FIREFOX, 290, "Firefox 29", new String[] { "Firefox/29" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX28( Manufacturer.MOZILLA, Browser.FIREFOX, 280, "Firefox 28", new String[] { "Firefox/28" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX27( Manufacturer.MOZILLA, Browser.FIREFOX, 108, "Firefox 27", new String[] { "Firefox/27" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX26( Manufacturer.MOZILLA, Browser.FIREFOX, 107, "Firefox 26", new String[] { "Firefox/26" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX25( Manufacturer.MOZILLA, Browser.FIREFOX, 106, "Firefox 25", new String[] { "Firefox/25" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX24( Manufacturer.MOZILLA, Browser.FIREFOX, 105, "Firefox 24", new String[] { "Firefox/24" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX23( Manufacturer.MOZILLA, Browser.FIREFOX, 104, "Firefox 23", new String[] { "Firefox/23" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX22( Manufacturer.MOZILLA, Browser.FIREFOX, 103, "Firefox 22", new String[] { "Firefox/22" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX21( Manufacturer.MOZILLA, Browser.FIREFOX, 102, "Firefox 21", new String[] { "Firefox/21" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX20( Manufacturer.MOZILLA, Browser.FIREFOX, 101, "Firefox 20", new String[] { "Firefox/20" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX19( Manufacturer.MOZILLA, Browser.FIREFOX, 100, "Firefox 19", new String[] { "Firefox/19" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX18( Manufacturer.MOZILLA, Browser.FIREFOX, 99, "Firefox 18", new String[] { "Firefox/18" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX17( Manufacturer.MOZILLA, Browser.FIREFOX, 98, "Firefox 17", new String[] { "Firefox/17" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX16( Manufacturer.MOZILLA, Browser.FIREFOX, 97, "Firefox 16", new String[] { "Firefox/16" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX15( Manufacturer.MOZILLA, Browser.FIREFOX, 96, "Firefox 15", new String[] { "Firefox/15" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX14( Manufacturer.MOZILLA, Browser.FIREFOX, 95, "Firefox 14", new String[] { "Firefox/14" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX13( Manufacturer.MOZILLA, Browser.FIREFOX, 94, "Firefox 13", new String[] { "Firefox/13" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX12( Manufacturer.MOZILLA, Browser.FIREFOX, 93, "Firefox 12", new String[] { "Firefox/12" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX11( Manufacturer.MOZILLA, Browser.FIREFOX, 92, "Firefox 11", new String[] { "Firefox/11" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX10( Manufacturer.MOZILLA, Browser.FIREFOX, 91, "Firefox 10", new String[] { "Firefox/10" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX9( Manufacturer.MOZILLA, Browser.FIREFOX, 90, "Firefox 9", new String[] { "Firefox/9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX8( Manufacturer.MOZILLA, Browser.FIREFOX, 80, "Firefox 8", new String[] { "Firefox/8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX7( Manufacturer.MOZILLA, Browser.FIREFOX, 70, "Firefox 7", new String[] { "Firefox/7" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX6( Manufacturer.MOZILLA, Browser.FIREFOX, 60, "Firefox 6", new String[] { "Firefox/6" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX5( Manufacturer.MOZILLA, Browser.FIREFOX, 50, "Firefox 5", new String[] { "Firefox/5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX4( Manufacturer.MOZILLA, Browser.FIREFOX, 40, "Firefox 4", new String[] { "Firefox/4" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX3( Manufacturer.MOZILLA, Browser.FIREFOX, 30, "Firefox 3", new String[] { "Firefox/3" }, new String[] {"ggpht.com"}, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX2( Manufacturer.MOZILLA, Browser.FIREFOX, 20, "Firefox 2", new String[] { "Firefox/2" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX1_5( Manufacturer.MOZILLA, Browser.FIREFOX, 15, "Firefox 1.5", new String[] { "Firefox/1.5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
/*
* Thunderbird email client, based on the same Gecko engine Firefox is using.
*/
THUNDERBIRD( Manufacturer.MOZILLA, null, 110, "Thunderbird", new String[] { "Thunderbird" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, "Thunderbird\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)" ), // using Gecko Engine
THUNDERBIRD12( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 185, "Thunderbird 12", new String[] { "Thunderbird/12" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD11( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 184, "Thunderbird 11", new String[] { "Thunderbird/11" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD10( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 183, "Thunderbird 10", new String[] { "Thunderbird/10" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD8( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 180, "Thunderbird 8", new String[] { "Thunderbird/8" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD7( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 170, "Thunderbird 7", new String[] { "Thunderbird/7" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD6( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 160, "Thunderbird 6", new String[] { "Thunderbird/6" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD3( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 130, "Thunderbird 3", new String[] { "Thunderbird/3" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD2( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 120, "Thunderbird 2", new String[] { "Thunderbird/2" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
SEAMONKEY( Manufacturer.OTHER, null, 15, "SeaMonkey", new String[]{"SeaMonkey"}, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "SeaMonkey\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)"), // using Gecko Engine
BOT( Manufacturer.OTHER, null,12, "Robot/Spider", new String[] {"Googlebot", "Web Preview", "bot", "spider", "crawler", "Feedfetcher", "Slurp", "Twiceler", "Nutch", "BecomeBot"}, null, BrowserType.ROBOT, RenderingEngine.OTHER, null),
BOT_MOBILE( Manufacturer.OTHER, Browser.BOT, 20 , "Mobil Robot/Spider", new String[] {"Googlebot-Mobile"}, null, BrowserType.ROBOT, RenderingEngine.OTHER, null),
MOZILLA( Manufacturer.MOZILLA, null, 1, "Mozilla", new String[] { "Mozilla", "Moozilla" }, new String[] {"ggpht.com"}, BrowserType.WEB_BROWSER, RenderingEngine.OTHER, null), // rest of the mozilla browsers
CFNETWORK( Manufacturer.OTHER, null, 6, "CFNetwork", new String[] { "CFNetwork" }, null, BrowserType.UNKNOWN, RenderingEngine.OTHER, null ), // Mac OS X cocoa library
EUDORA( Manufacturer.OTHER, null, 7, "Eudora", new String[] { "Eudora", "EUDORA" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null ), // email client by Qualcomm
POCOMAIL( Manufacturer.OTHER, null, 8, "PocoMail", new String[] { "PocoMail" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null ),
THEBAT( Manufacturer.OTHER, null, 9, "The Bat!", new String[]{"The Bat"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null), // Email Client
NETFRONT( Manufacturer.OTHER, null, 10, "NetFront", new String[]{"NetFront"}, null, BrowserType.MOBILE_BROWSER, RenderingEngine.OTHER, null), // mobile device browser
EVOLUTION( Manufacturer.OTHER, null, 11, "Evolution", new String[]{"CamelHttpStream"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null),
LYNX( Manufacturer.OTHER, null, 13, "Lynx", new String[]{"Lynx"}, null, BrowserType.TEXT_BROWSER, RenderingEngine.OTHER, "Lynx\\/(([0-9]+)\\.([\\d]+)\\.?([\\w-+]+)?\\.?([\\w-+]+)?)"),
DOWNLOAD( Manufacturer.OTHER, null, 16, "Downloading Tool", new String[]{"cURL","wget", "ggpht.com", "Apache-HttpClient"}, null, BrowserType.TOOL, RenderingEngine.OTHER, null),
UNKNOWN( Manufacturer.OTHER, null, 14, "Unknown", new String[0], null, BrowserType.UNKNOWN, RenderingEngine.OTHER, null ),
@Deprecated
APPLE_MAIL( Manufacturer.APPLE, null, 51, "Apple Mail", new String[0], null, BrowserType.EMAIL_CLIENT, RenderingEngine.WEBKIT, null); // not detectable any longer.
/*
* An id for each browser version which is unique per manufacturer.
*/
private final short id;
private final String name;
private final String[] aliases;
private final String[] excludeList; // don't match when these values are in the agent-string
private final BrowserType browserType;
private final Manufacturer manufacturer;
private final RenderingEngine renderingEngine;
private final Browser parent;
private List<Browser> children;
private Pattern versionRegEx;
private static List<Browser> topLevelBrowsers;
private Browser(Manufacturer manufacturer, Browser parent, int versionId, String name, String[] aliases, String[] exclude, BrowserType browserType, RenderingEngine renderingEngine, String versionRegexString) {
this.id = (short) ( ( manufacturer.getId() << 8) + (byte) versionId);
this.name = name;
this.parent = parent;
this.children = new ArrayList<Browser>();
this.aliases = toLowerCase(aliases);
this.excludeList = toLowerCase(exclude);
this.browserType = browserType;
this.manufacturer = manufacturer;
this.renderingEngine = renderingEngine;
if (versionRegexString != null)
this.versionRegEx = Pattern.compile(versionRegexString);
if (this.parent == null)
addTopLevelBrowser(this);
else
this.parent.children.add(this);
}
private static String[] toLowerCase(String[] strArr) {
if (strArr == null) return null;
String[] res = new String[strArr.length];
for (int i=0; i<strArr.length; i++) {
res[i] = strArr[i].toLowerCase();
}
return res;
}
// create collection of top level browsers during initialization
private static void addTopLevelBrowser(Browser browser) {
if(topLevelBrowsers == null)
topLevelBrowsers = new ArrayList<Browser>();
topLevelBrowsers.add(browser);
}
public short getId() {
return id;
}
public String getName() {
return name;
}
private Pattern getVersionRegEx() {
if (this.versionRegEx == null) {
if (this.getGroup() != this)
return this.getGroup().getVersionRegEx();
else
return null;
}
return this.versionRegEx;
}
/**
* Detects the detailed version information of the browser. Depends on the userAgent to be available.
* Returns null if it can not detect the version information.
* @return Version
*/
public Version getVersion(String userAgentString) {
Pattern pattern = this.getVersionRegEx();
if (userAgentString != null && pattern != null) {
Matcher matcher = pattern.matcher(userAgentString);
if (matcher.find()) {
String fullVersionString = matcher.group(1);
String majorVersion = matcher.group(2);
String minorVersion = "0";
if (matcher.groupCount() > 2) // usually but not always there is a minor version
minorVersion = matcher.group(3);
return new Version (fullVersionString,majorVersion,minorVersion);
}
}
return null;
}
/**
* @return the browserType
*/
public BrowserType getBrowserType() {
return browserType;
}
/**
* @return the manufacturer
*/
public Manufacturer getManufacturer() {
return manufacturer;
}
/**
* @return the rendering engine
*/
public RenderingEngine getRenderingEngine() {
return renderingEngine;
}
/**
* @return top level browser family
*/
public Browser getGroup() {
if (this.parent != null) {
return parent.getGroup();
}
return this;
}
/*
* Checks if the given user-agent string matches to the browser.
* Only checks for one specific browser.
*/
public boolean isInUserAgentString(String agentString)
{
if (agentString == null) return false;
String agentStringLowerCase = agentString.toLowerCase();
for (String alias : aliases)
{
if (agentStringLowerCase.contains(alias))
return true;
}
return false;
}
/**
* Checks if the given user-agent does not contain one of the tokens which should not match.
* In most cases there are no excluding tokens, so the impact should be small.
* @param agentString
* @return
*/
private boolean containsExcludeToken(String agentString)
{
if (agentString == null) return false;
if (excludeList != null) {
String agentStringLowerCase = agentString.toLowerCase();
for (String exclude : excludeList) {
if (agentStringLowerCase.contains(exclude))
return true;
}
}
return false;
}
private Browser checkUserAgent(String agentString) {
if (this.isInUserAgentString(agentString)) {
if (this.children.size() > 0) {
for (Browser childBrowser : this.children) {
Browser match = childBrowser.checkUserAgent(agentString);
if (match != null) {
return match;
}
}
}
// if children didn't match we continue checking the current to prevent false positives
if (!this.containsExcludeToken(agentString)) {
return this;
}
}
return null;
}
/**
* Iterates over all Browsers to compare the browser signature with
* the user agent string. If no match can be found Browser.UNKNOWN will
* be returned.
* Starts with the top level browsers and only if one of those matches
* checks children browsers.
* Steps out of loop as soon as there is a match.
* @param agentString
* @return Browser
*/
public static Browser parseUserAgentString(String agentString)
{
return parseUserAgentString(agentString, topLevelBrowsers);
}
/**
* Iterates over the given Browsers (incl. children) to compare the browser
* signature with the user agent string.
* If no match can be found Browser.UNKNOWN will be returned.
* Steps out of loop as soon as there is a match.
* Be aware that if the order of the provided Browsers is incorrect or if the set is too limited it can lead to false matches!
* @param agentString
* @return Browser
*/
public static Browser parseUserAgentString(String agentString, List<Browser> browsers)
{
for (Browser browser : browsers) {
Browser match = browser.checkUserAgent(agentString);
if (match != null) {
return match; // either current operatingSystem or a child object
}
}
return Browser.UNKNOWN;
}
public static Browser valueOf(short id)
{
for (Browser browser : Browser.values())
{
if (browser.getId() == id)
return browser;
}
// same behavior as standard valueOf(string) method
throw new IllegalArgumentException(
"No enum const for id " + id);
}
} |
package eu.bitwalker.useragentutils;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Enum constants for most common browsers, including e-mail clients and bots.
* @author harald
*
*/
public enum Browser {
OPERA( Manufacturer.OPERA, null, 1, "Opera", new String[] { "Opera" }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, "Opera\\/(([\\d]+)\\.([\\w]+))"), // before MSIE
OPERA_MINI( Manufacturer.OPERA, Browser.OPERA, 20, "Opera Mini", new String[] { "Opera Mini"}, null, BrowserType.MOBILE_BROWSER, RenderingEngine.PRESTO, null), // Opera for mobile devices
/**
* For some strange reason Opera uses 9.80 in the user-agent string and otherwise it is very inconsistent. Use the getVersion method if you really want to know which version it is.
*/
OPERA10( Manufacturer.OPERA, Browser.OPERA, 10, "Opera 10", new String[] { "Opera/9.8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, "Version\\/(([\\d]+)\\.([\\w]+))"),
OPERA9( Manufacturer.OPERA, Browser.OPERA, 5, "Opera 9", new String[] { "Opera/9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.PRESTO, null),
KONQUEROR( Manufacturer.OTHER, null, 1, "Konqueror", new String[] { "Konqueror"}, null, BrowserType.WEB_BROWSER, RenderingEngine.KHTML, "Konqueror\\/(([0-9]+)\\.?([\\w]+)?(-[\\w]+)?)" ),
/**
* Outlook email client
*/
OUTLOOK( Manufacturer.MICROSOFT, null, 100, "Outlook", new String[] {"MSOffice"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, "MSOffice (([0-9]+))"), // before IE7
/**
* Microsoft Outlook 2007 identifies itself as MSIE7 but uses the html rendering engine of Word 2007.
* Example user agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 1.1.4322; MSOffice 12)
*/
OUTLOOK2007( Manufacturer.MICROSOFT, Browser.OUTLOOK, 107, "Outlook 2007", new String[] {"MSOffice 12"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, null), // before IE7
OUTLOOK2013( Manufacturer.MICROSOFT, Browser.OUTLOOK, 109, "Outlook 2013", new String[] {"Microsoft Outlook 15"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, null), // before IE7
OUTLOOK2010( Manufacturer.MICROSOFT, Browser.OUTLOOK, 108, "Outlook 2010", new String[] {"MSOffice 14", "Microsoft Outlook 14"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.WORD, null), // before IE7
/**
* Family of Internet Explorer browsers
*/
IE( Manufacturer.MICROSOFT, null, 1, "Internet Explorer", new String[] { "MSIE"}, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, "MSIE (([\\d]+)\\.([\\w]+))" ), // before Mozilla
/**
* Since version 7 Outlook Express is identifying itself. By detecting Outlook Express we can not
* identify the Internet Explorer version which is probably used for the rendering.
* Obviously this product is now called Windows Live Mail Desktop or just Windows Live Mail.
*/
OUTLOOK_EXPRESS7( Manufacturer.MICROSOFT, Browser.IE, 110, "Windows Live Mail", new String[] {"Outlook-Express/7.0"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.TRIDENT, null), // before IE7, previously known as Outlook Express. First released in 2006, offered with different name later
/**
* Since 2007 the mobile edition of Internet Explorer identifies itself as IEMobile in the user-agent.
* If previous versions have to be detected, use the operating system information as well.
*/
IEMOBILE9( Manufacturer.MICROSOFT, Browser.IE, 123, "IE Mobile 9", new String[] { "IEMobile/9" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE strings
IEMOBILE7( Manufacturer.MICROSOFT, Browser.IE, 121, "IE Mobile 7", new String[] { "IEMobile 7" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE strings
IEMOBILE6( Manufacturer.MICROSOFT, Browser.IE, 120, "IE Mobile 6", new String[] { "IEMobile 6" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE
IE10( Manufacturer.MICROSOFT, Browser.IE, 92, "Internet Explorer 10", new String[] { "MSIE 10" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
IE9( Manufacturer.MICROSOFT, Browser.IE, 90, "Internet Explorer 9", new String[] { "MSIE 9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
IE8( Manufacturer.MICROSOFT, Browser.IE, 80, "Internet Explorer 8", new String[] { "MSIE 8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
IE7( Manufacturer.MICROSOFT, Browser.IE, 70, "Internet Explorer 7", new String[] { "MSIE 7" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE
IE6( Manufacturer.MICROSOFT, Browser.IE, 60, "Internet Explorer 6", new String[] { "MSIE 6" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
IE5_5( Manufacturer.MICROSOFT, Browser.IE, 55, "Internet Explorer 5.5", new String[] { "MSIE 5.5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null), // before MSIE
IE5( Manufacturer.MICROSOFT, Browser.IE, 50, "Internet Explorer 5", new String[] { "MSIE 5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.TRIDENT, null ), // before MSIE
/**
* Google Chrome browser
*/
CHROME( Manufacturer.GOOGLE, null, 1, "Chrome", new String[] { "Chrome" }, new String[] { "Web Preview" } , BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "Chrome\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)" ), // before Mozilla
CHROME28( Manufacturer.GOOGLE, Browser.CHROME, 33, "Chrome 28", new String[] { "Chrome/28" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME27( Manufacturer.GOOGLE, Browser.CHROME, 32, "Chrome 27", new String[] { "Chrome/27" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME26( Manufacturer.GOOGLE, Browser.CHROME, 31, "Chrome 26", new String[] { "Chrome/26" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME25( Manufacturer.GOOGLE, Browser.CHROME, 30, "Chrome 25", new String[] { "Chrome/25" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME24( Manufacturer.GOOGLE, Browser.CHROME, 29, "Chrome 24", new String[] { "Chrome/24" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME23( Manufacturer.GOOGLE, Browser.CHROME, 28, "Chrome 23", new String[] { "Chrome/23" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME22( Manufacturer.GOOGLE, Browser.CHROME, 27, "Chrome 22", new String[] { "Chrome/22" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME21( Manufacturer.GOOGLE, Browser.CHROME, 26, "Chrome 21", new String[] { "Chrome/21" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME20( Manufacturer.GOOGLE, Browser.CHROME, 25, "Chrome 20", new String[] { "Chrome/20" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME19( Manufacturer.GOOGLE, Browser.CHROME, 24, "Chrome 19", new String[] { "Chrome/19" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME18( Manufacturer.GOOGLE, Browser.CHROME, 23, "Chrome 18", new String[] { "Chrome/18" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME17( Manufacturer.GOOGLE, Browser.CHROME, 22, "Chrome 17", new String[] { "Chrome/17" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME16( Manufacturer.GOOGLE, Browser.CHROME, 21, "Chrome 16", new String[] { "Chrome/16" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME15( Manufacturer.GOOGLE, Browser.CHROME, 20, "Chrome 15", new String[] { "Chrome/15" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME14( Manufacturer.GOOGLE, Browser.CHROME, 19, "Chrome 14", new String[] { "Chrome/14" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME13( Manufacturer.GOOGLE, Browser.CHROME, 18, "Chrome 13", new String[] { "Chrome/13" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME12( Manufacturer.GOOGLE, Browser.CHROME, 17, "Chrome 12", new String[] { "Chrome/12" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME11( Manufacturer.GOOGLE, Browser.CHROME, 16, "Chrome 11", new String[] { "Chrome/11" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME10( Manufacturer.GOOGLE, Browser.CHROME, 15, "Chrome 10", new String[] { "Chrome/10" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME9( Manufacturer.GOOGLE, Browser.CHROME, 10, "Chrome 9", new String[] { "Chrome/9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
CHROME8( Manufacturer.GOOGLE, Browser.CHROME, 5, "Chrome 8", new String[] { "Chrome/8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before Mozilla
OMNIWEB( Manufacturer.OTHER, null, 2, "Omniweb", new String[] { "OmniWeb" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null),
SAFARI( Manufacturer.APPLE, null, 1, "Safari", new String[] { "Safari" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "Version\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)" ), // before AppleWebKit
CHROME_MOBILE( Manufacturer.GOOGLE, Browser.SAFARI, 100, "Chrome Mobile", new String[] { "CrMo","CriOS" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, "(?:CriOS|CrMo)\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)" ),
MOBILE_SAFARI( Manufacturer.APPLE, Browser.SAFARI, 2, "Mobile Safari", new String[] { "Mobile Safari","Mobile/" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, null ), // before Safari
SILK( Manufacturer.AMAZON, Browser.SAFARI, 15, "Silk", new String[] { "Silk/" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, "Silk\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\-[\\w]+)?)" ),
SAFARI6( Manufacturer.APPLE, Browser.SAFARI, 6, "Safari 6", new String[] { "Version/6" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit
SAFARI5( Manufacturer.APPLE, Browser.SAFARI, 3, "Safari 5", new String[] { "Version/5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit
SAFARI4( Manufacturer.APPLE, Browser.SAFARI, 4, "Safari 4", new String[] { "Version/4" }, null, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null ), // before AppleWebKit
DOLFIN2( Manufacturer.SAMSUNG, null, 1, "Samsung Dolphin 2", new String[] { "Dolfin/2" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.WEBKIT, null ), // webkit based browser for the bada os
/*
* Apple WebKit compatible client. Can be a browser or an application with embedded browser using UIWebView.
*/
APPLE_WEB_KIT( Manufacturer.APPLE, null, 50, "Apple WebKit", new String[] { "AppleWebKit" }, new String[] { "Web Preview" }, BrowserType.WEB_BROWSER, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit
APPLE_ITUNES( Manufacturer.APPLE, Browser.APPLE_WEB_KIT, 52, "iTunes", new String[] { "iTunes" }, null, BrowserType.APP, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit
APPLE_APPSTORE( Manufacturer.APPLE, Browser.APPLE_WEB_KIT, 53, "App Store", new String[] { "MacAppStore" }, null, BrowserType.APP, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit
ADOBE_AIR( Manufacturer.ADOBE, Browser.APPLE_WEB_KIT, 1, "Adobe AIR application", new String[] { "AdobeAIR" }, null, BrowserType.APP, RenderingEngine.WEBKIT, null), // Microsoft Entrourage/Outlook 2010 also only identifies itself as AppleWebKit
LOTUS_NOTES( Manufacturer.OTHER, null, 3, "Lotus Notes", new String[] { "Lotus-Notes" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, "Lotus-Notes\\/(([\\d]+)\\.([\\w]+))"), // before Mozilla
CAMINO( Manufacturer.OTHER, null, 5, "Camino", new String[] { "Camino" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "Camino\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)" ), // using Gecko Engine
CAMINO2( Manufacturer.OTHER, Browser.CAMINO, 17, "Camino 2", new String[] { "Camino/2" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FLOCK( Manufacturer.OTHER, null, 4, "Flock", new String[]{"Flock"}, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "Flock\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)"),
FIREFOX( Manufacturer.MOZILLA, null, 10, "Firefox", new String[] { "Firefox" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "Firefox\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)"), // using Gecko Engine
FIREFOX3MOBILE( Manufacturer.MOZILLA, Browser.FIREFOX, 31, "Firefox 3 Mobile", new String[] { "Firefox/3.5 Maemo" }, null, BrowserType.MOBILE_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX23( Manufacturer.MOZILLA, Browser.FIREFOX, 104, "Firefox 23", new String[] { "Firefox/23" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX22( Manufacturer.MOZILLA, Browser.FIREFOX, 103, "Firefox 22", new String[] { "Firefox/22" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX21( Manufacturer.MOZILLA, Browser.FIREFOX, 102, "Firefox 21", new String[] { "Firefox/21" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX20( Manufacturer.MOZILLA, Browser.FIREFOX, 101, "Firefox 20", new String[] { "Firefox/20" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX19( Manufacturer.MOZILLA, Browser.FIREFOX, 100, "Firefox 19", new String[] { "Firefox/19" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX18( Manufacturer.MOZILLA, Browser.FIREFOX, 99, "Firefox 18", new String[] { "Firefox/18" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX17( Manufacturer.MOZILLA, Browser.FIREFOX, 98, "Firefox 17", new String[] { "Firefox/17" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX16( Manufacturer.MOZILLA, Browser.FIREFOX, 97, "Firefox 16", new String[] { "Firefox/16" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX15( Manufacturer.MOZILLA, Browser.FIREFOX, 96, "Firefox 15", new String[] { "Firefox/15" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX14( Manufacturer.MOZILLA, Browser.FIREFOX, 95, "Firefox 14", new String[] { "Firefox/14" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX13( Manufacturer.MOZILLA, Browser.FIREFOX, 94, "Firefox 13", new String[] { "Firefox/13" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX12( Manufacturer.MOZILLA, Browser.FIREFOX, 93, "Firefox 12", new String[] { "Firefox/12" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX11( Manufacturer.MOZILLA, Browser.FIREFOX, 92, "Firefox 11", new String[] { "Firefox/11" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX10( Manufacturer.MOZILLA, Browser.FIREFOX, 91, "Firefox 10", new String[] { "Firefox/10" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX9( Manufacturer.MOZILLA, Browser.FIREFOX, 90, "Firefox 9", new String[] { "Firefox/9" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX8( Manufacturer.MOZILLA, Browser.FIREFOX, 80, "Firefox 8", new String[] { "Firefox/8" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX7( Manufacturer.MOZILLA, Browser.FIREFOX, 70, "Firefox 7", new String[] { "Firefox/7" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX6( Manufacturer.MOZILLA, Browser.FIREFOX, 60, "Firefox 6", new String[] { "Firefox/6" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX5( Manufacturer.MOZILLA, Browser.FIREFOX, 50, "Firefox 5", new String[] { "Firefox/5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX4( Manufacturer.MOZILLA, Browser.FIREFOX, 40, "Firefox 4", new String[] { "Firefox/4" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX3( Manufacturer.MOZILLA, Browser.FIREFOX, 30, "Firefox 3", new String[] { "Firefox/3" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX2( Manufacturer.MOZILLA, Browser.FIREFOX, 20, "Firefox 2", new String[] { "Firefox/2" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
FIREFOX1_5( Manufacturer.MOZILLA, Browser.FIREFOX, 15, "Firefox 1.5", new String[] { "Firefox/1.5" }, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, null ), // using Gecko Engine
/*
* Thunderbird email client, based on the same Gecko engine Firefox is using.
*/
THUNDERBIRD( Manufacturer.MOZILLA, null, 110, "Thunderbird", new String[] { "Thunderbird" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, "Thunderbird\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?(\\.[\\w]+)?)" ), // using Gecko Engine
THUNDERBIRD12( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 185, "Thunderbird 12", new String[] { "Thunderbird/12" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD11( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 184, "Thunderbird 11", new String[] { "Thunderbird/11" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD10( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 183, "Thunderbird 10", new String[] { "Thunderbird/10" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD8( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 180, "Thunderbird 8", new String[] { "Thunderbird/8" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD7( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 170, "Thunderbird 7", new String[] { "Thunderbird/7" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD6( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 160, "Thunderbird 6", new String[] { "Thunderbird/6" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD3( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 130, "Thunderbird 3", new String[] { "Thunderbird/3" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
THUNDERBIRD2( Manufacturer.MOZILLA, Browser.THUNDERBIRD, 120, "Thunderbird 2", new String[] { "Thunderbird/2" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.GECKO, null ), // using Gecko Engine
SEAMONKEY( Manufacturer.OTHER, null, 15, "SeaMonkey", new String[]{"SeaMonkey"}, null, BrowserType.WEB_BROWSER, RenderingEngine.GECKO, "SeaMonkey\\/(([0-9]+)\\.?([\\w]+)?(\\.[\\w]+)?)"), // using Gecko Engine
BOT( Manufacturer.OTHER, null,12, "Robot/Spider", new String[]{"Googlebot", "Web Preview", "bot", "spider", "crawler", "Feedfetcher", "Slurp", "Twiceler", "Nutch", "BecomeBot"}, null, BrowserType.ROBOT, RenderingEngine.OTHER, null),
MOZILLA( Manufacturer.MOZILLA, null, 1, "Mozilla", new String[] { "Mozilla", "Moozilla" }, null, BrowserType.WEB_BROWSER, RenderingEngine.OTHER, null), // rest of the mozilla browsers
CFNETWORK( Manufacturer.OTHER, null, 6, "CFNetwork", new String[] { "CFNetwork" }, null, BrowserType.UNKNOWN, RenderingEngine.OTHER, null ), // Mac OS X cocoa library
EUDORA( Manufacturer.OTHER, null, 7, "Eudora", new String[] { "Eudora", "EUDORA" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null ), // email client by Qualcomm
POCOMAIL( Manufacturer.OTHER, null, 8, "PocoMail", new String[] { "PocoMail" }, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null ),
THEBAT( Manufacturer.OTHER, null, 9, "The Bat!", new String[]{"The Bat"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null), // Email Client
NETFRONT( Manufacturer.OTHER, null, 10, "NetFront", new String[]{"NetFront"}, null, BrowserType.MOBILE_BROWSER, RenderingEngine.OTHER, null), // mobile device browser
EVOLUTION( Manufacturer.OTHER, null, 11, "Evolution", new String[]{"CamelHttpStream"}, null, BrowserType.EMAIL_CLIENT, RenderingEngine.OTHER, null),
LYNX( Manufacturer.OTHER, null, 13, "Lynx", new String[]{"Lynx"}, null, BrowserType.TEXT_BROWSER, RenderingEngine.OTHER, "Lynx\\/(([0-9]+)\\.([\\d]+)\\.?([\\w-+]+)?\\.?([\\w-+]+)?)"),
DOWNLOAD( Manufacturer.OTHER, null, 16, "Downloading Tool", new String[]{"cURL","wget"}, null, BrowserType.TEXT_BROWSER, RenderingEngine.OTHER, null),
UNKNOWN( Manufacturer.OTHER, null, 14, "Unknown", new String[0], null, BrowserType.UNKNOWN, RenderingEngine.OTHER, null ),
@Deprecated
APPLE_MAIL( Manufacturer.APPLE, null, 51, "Apple Mail", new String[0], null, BrowserType.EMAIL_CLIENT, RenderingEngine.WEBKIT, null); // not detectable any longer.
private final short id;
private final String name;
private final String[] aliases;
private final String[] excludeList; // don't match when these values are in the agent-string
private final BrowserType browserType;
private final Manufacturer manufacturer;
private final RenderingEngine renderingEngine;
private final Browser parent;
private List<Browser> children;
private Pattern versionRegEx;
private static List<Browser> topLevelBrowsers;
private Browser(Manufacturer manufacturer, Browser parent, int versionId, String name, String[] aliases, String[] exclude, BrowserType browserType, RenderingEngine renderingEngine, String versionRegexString) {
this.id = (short) ( ( manufacturer.getId() << 8) + (byte) versionId);
this.name = name;
this.parent = parent;
this.children = new ArrayList<Browser>();
this.aliases = aliases;
this.excludeList = exclude;
this.browserType = browserType;
this.manufacturer = manufacturer;
this.renderingEngine = renderingEngine;
if (versionRegexString != null)
this.versionRegEx = Pattern.compile(versionRegexString);
if (this.parent == null)
addTopLevelBrowser(this);
else
this.parent.children.add(this);
}
// create collection of top level browsers during initialization
private static void addTopLevelBrowser(Browser browser) {
if(topLevelBrowsers == null)
topLevelBrowsers = new ArrayList<Browser>();
topLevelBrowsers.add(browser);
}
public short getId() {
return id;
}
public String getName() {
return name;
}
private Pattern getVersionRegEx() {
if (this.versionRegEx == null) {
if (this.getGroup() != this)
return this.getGroup().getVersionRegEx();
else
return null;
}
return this.versionRegEx;
}
/**
* Detects the detailed version information of the browser. Depends on the userAgent to be available.
* Returns null if it can not detect the version information.
* @return Version
*/
public Version getVersion(String userAgentString) {
Pattern pattern = this.getVersionRegEx();
if (userAgentString != null && pattern != null) {
Matcher matcher = pattern.matcher(userAgentString);
if (matcher.find()) {
String fullVersionString = matcher.group(1);
String majorVersion = matcher.group(2);
String minorVersion = "0";
if (matcher.groupCount() > 2) // usually but not always there is a minor version
minorVersion = matcher.group(3);
return new Version (fullVersionString,majorVersion,minorVersion);
}
}
return null;
}
/**
* @return the browserType
*/
public BrowserType getBrowserType() {
return browserType;
}
/**
* @return the manufacturer
*/
public Manufacturer getManufacturer() {
return manufacturer;
}
/**
* @return the rendering engine
*/
public RenderingEngine getRenderingEngine() {
return renderingEngine;
}
/**
* @return top level browser family
*/
public Browser getGroup() {
if (this.parent != null) {
return parent.getGroup();
}
return this;
}
/*
* Checks if the given user-agent string matches to the browser.
* Only checks for one specific browser.
*/
public boolean isInUserAgentString(String agentString)
{
for (String alias : aliases)
{
if (agentString.toLowerCase().indexOf(alias.toLowerCase()) != -1)
return true;
}
return false;
}
/**
* Checks if the given user-agent does not contain one of the tokens which should not match.
* In most cases there are no excluding tokens, so the impact should be small.
* @param agentString
* @return
*/
private boolean containsExcludeToken(String agentString)
{
if (excludeList != null) {
for (String exclude : excludeList) {
if (agentString.toLowerCase().indexOf(exclude.toLowerCase()) != -1)
return true;
}
}
return false;
}
private Browser checkUserAgent(String agentString) {
if (this.isInUserAgentString(agentString)) {
if (this.children.size() > 0) {
for (Browser childBrowser : this.children) {
Browser match = childBrowser.checkUserAgent(agentString);
if (match != null) {
return match;
}
}
}
// if children didn't match we continue checking the current to prevent false positives
if (!this.containsExcludeToken(agentString)) {
return this;
}
}
return null;
}
/**
* Iterates over all Browsers to compare the browser signature with
* the user agent string. If no match can be found Browser.UNKNOWN will
* be returned.
* Starts with the top level browsers and only if one of those matches
* checks children browsers.
* Steps out of loop as soon as there is a match.
* @param agentString
* @return Browser
*/
public static Browser parseUserAgentString(String agentString)
{
return parseUserAgentString(agentString, topLevelBrowsers);
}
/**
* Iterates over the given Browsers (incl. children) to compare the browser
* signature with the user agent string.
* If no match can be found Browser.UNKNOWN will be returned.
* Steps out of loop as soon as there is a match.
* Be aware that if the order of the provided Browsers is incorrect or if the set is too limited it can lead to false matches!
* @param agentString
* @return Browser
*/
public static Browser parseUserAgentString(String agentString, List<Browser> browsers)
{
for (Browser browser : browsers) {
Browser match = browser.checkUserAgent(agentString);
if (match != null) {
return match; // either current operatingSystem or a child object
}
}
return Browser.UNKNOWN;
}
public static Browser valueOf(short id)
{
for (Browser browser : Browser.values())
{
if (browser.getId() == id)
return browser;
}
// same behavior as standard valueOf(string) method
throw new IllegalArgumentException(
"No enum const for id " + id);
}
} |
package info.debatty.java.aggregation;
class Lines {
StraightLine[] lines;
static boolean McAllister = false;
// false = Modificacio meva C & O
// true = Alternativa de McAllister i Roulier segons Iqbal
static double infinit = Double.MAX_VALUE;
Lines(Point[] points) {
lines = new StraightLine[points.length];
for (int i = 1; i < points.length; i++) {
lines[i] = new StraightLine(0, 0);
}
double[] s = new double[points.length];
double[] m = new double[points.length];
int i = 0;
int N = points.length - 1; //N es la darrera posicio de d, i d es num_values+1
for (i = 2; i <= N; i++) {
s[i] = Point.calculaSi(points[i], points[i - 1]);
}
for (i = 2; i <= N - 1; i++) {
m[i] = Point.calculaMi(s[i], s[i + 1],
points[i], points[i - 1], points[i + 1]);
}
if (McAllister) {
if ((s[2] * (2 * s[2] - m[2])) > 0.0) {
m[1] = 2 * s[2] - m[2];
} else {
m[1] = 0.0;
}
} else {
if ((m[2] == 0.0) && (s[2] == 0.0)) {
m[1] = 0.0;
} else if (m[2] == 0.0) {
m[1] = infinit;
} else {
m[1] = s[2] * s[2] / m[2];
}
}
if (McAllister) {
if ((s[N] * (2 * s[N] - m[N - 1])) > 0.0) {
m[N] = 2 * s[N] - m[N - 1];
} else {
m[N] = 0.0;
}
} else {
if ((m[N - 1] == 0.0) && (s[N] == 0.0)) {
m[N] = 0.0;
} else if (m[N - 1] == 0.0) {
m[N] = infinit;
} else {
m[N] = s[N] * s[N]
/ m[N - 1];
}
}
for (i = 1; i <= N; i++) {
this.lines[i].a = m[i];
this.lines[i].b = points[i].y - m[i] * points[i].x;
}
}
public static void setMcAllister() {
McAllister = true;
}
} |
package io.github.classgraph;
import java.lang.annotation.Annotation;
import java.lang.annotation.IncompleteAnnotationException;
import java.lang.annotation.Inherited;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import nonapi.io.github.classgraph.utils.ReflectionUtils;
/** Holds metadata about a specific annotation instance on a class, method, method parameter or field. */
public class AnnotationInfo extends ScanResultObject implements Comparable<AnnotationInfo>, HasName {
/** The name. */
private String name;
/** The annotation param values. */
private AnnotationParameterValueList annotationParamValues;
/**
* Set to true once any Object[] arrays of boxed types in annotationParamValues have been lazily converted to
* primitive arrays.
*/
private transient boolean annotationParamValuesHasBeenConvertedToPrimitive;
/** The annotation param values with defaults. */
private transient AnnotationParameterValueList annotationParamValuesWithDefaults;
/** Default constructor for deserialization. */
AnnotationInfo() {
super();
}
/**
* Constructor.
*
* @param name
* The name of the annotation.
* @param annotationParamValues
* The annotation parameter values, or null if none.
*/
AnnotationInfo(final String name, final AnnotationParameterValueList annotationParamValues) {
super();
this.name = name;
this.annotationParamValues = annotationParamValues;
}
/**
* Get the name.
*
* @return The name of the annotation class.
*/
@Override
public String getName() {
return name;
}
/**
* Checks if the annotation is inherited.
*
* @return true if this annotation is meta-annotated with {@link Inherited}.
*/
public boolean isInherited() {
return getClassInfo().isInherited;
}
/**
* Get the default parameter values.
*
* @return the list of default parameter values for this annotation, or the empty list if none.
*/
public AnnotationParameterValueList getDefaultParameterValues() {
return getClassInfo().getAnnotationDefaultParameterValues();
}
/**
* Get the parameter values.
*
* @return The parameter values of this annotation, including any default parameter values inherited from the
* annotation class definition, or the empty list if none.
*/
public AnnotationParameterValueList getParameterValues() {
if (annotationParamValuesWithDefaults == null) {
final ClassInfo classInfo = getClassInfo();
if (classInfo == null) {
// ClassInfo has not yet been set, just return values without defaults
// (happens when trying to log AnnotationInfo during scanning, before ScanResult is available)
return annotationParamValues == null ? AnnotationParameterValueList.EMPTY_LIST
: annotationParamValues;
}
// Lazily convert any Object[] arrays of boxed types to primitive arrays
if (annotationParamValues != null && !annotationParamValuesHasBeenConvertedToPrimitive) {
annotationParamValues.convertWrapperArraysToPrimitiveArrays(classInfo);
annotationParamValuesHasBeenConvertedToPrimitive = true;
}
if (classInfo.annotationDefaultParamValues != null
&& !classInfo.annotationDefaultParamValuesHasBeenConvertedToPrimitive) {
classInfo.annotationDefaultParamValues.convertWrapperArraysToPrimitiveArrays(classInfo);
classInfo.annotationDefaultParamValuesHasBeenConvertedToPrimitive = true;
}
// Check if one or both of the defaults and the values in this annotation instance are null (empty)
final AnnotationParameterValueList defaultParamValues = classInfo.annotationDefaultParamValues;
if (defaultParamValues == null && annotationParamValues == null) {
return AnnotationParameterValueList.EMPTY_LIST;
} else if (defaultParamValues == null) {
return annotationParamValues;
} else if (annotationParamValues == null) {
return defaultParamValues;
}
// Overwrite defaults with non-defaults
final Map<String, Object> allParamValues = new HashMap<>();
for (final AnnotationParameterValue defaultParamValue : defaultParamValues) {
allParamValues.put(defaultParamValue.getName(), defaultParamValue.getValue());
}
for (final AnnotationParameterValue annotationParamValue : this.annotationParamValues) {
allParamValues.put(annotationParamValue.getName(), annotationParamValue.getValue());
}
// Put annotation values in the same order as the annotation methods (there is one method for each
// annotation constant)
if (classInfo.methodInfo == null) {
// Should not happen (when classfile is read, methods are always read, whether or not
// scanSpec.enableMethodInfo is true)
throw new IllegalArgumentException("Could not find methods for annotation " + classInfo.getName());
}
annotationParamValuesWithDefaults = new AnnotationParameterValueList();
for (final MethodInfo mi : classInfo.methodInfo) {
final String paramName = mi.getName();
switch (paramName) {
// None of these method names should be present in the @interface class itself, it should only
// contain methods for the annotation constants (but skip them anyway to be safe). These methods
// should only exist in concrete instances of the annotation.
case "<init>":
case "<clinit>":
case "hashCode":
case "equals":
case "toString":
case "annotationType":
// Skip
break;
default:
// Annotation constant
final Object paramValue = allParamValues.get(paramName);
// Annotation values cannot be null (or absent, from either defaults or annotation instance)
if (paramValue != null) {
annotationParamValuesWithDefaults.add(new AnnotationParameterValue(paramName, paramValue));
}
break;
}
}
}
return annotationParamValuesWithDefaults;
}
/**
* Get the name of the annotation class, for {@link #getClassInfo()}.
*
* @return the class name
*/
@Override
protected String getClassName() {
return name;
}
/**
* Get the class info.
*
* @return The {@link ClassInfo} object for the annotation class.
*/
@Override
public ClassInfo getClassInfo() {
getClassName();
return super.getClassInfo();
}
/* (non-Javadoc)
* @see io.github.classgraph.ScanResultObject#setScanResult(io.github.classgraph.ScanResult)
*/
@Override
void setScanResult(final ScanResult scanResult) {
super.setScanResult(scanResult);
if (annotationParamValues != null) {
for (final AnnotationParameterValue a : annotationParamValues) {
a.setScanResult(scanResult);
}
}
}
/**
* Find the names of any classes referenced in the type descriptors of annotation parameters.
*
* @param referencedClassNames
* the referenced class names
*/
@Override
void findReferencedClassNames(final Set<String> referencedClassNames) {
referencedClassNames.add(name);
if (annotationParamValues != null) {
for (final AnnotationParameterValue annotationParamValue : annotationParamValues) {
annotationParamValue.findReferencedClassNames(referencedClassNames);
}
}
}
public Annotation loadClassAndInstantiate() {
final Class<? extends Annotation> annotationClass = getClassInfo().loadClass(Annotation.class);
return (Annotation) Proxy.newProxyInstance(annotationClass.getClassLoader(),
new Class[] { annotationClass }, new AnnotationInvocationHandler(annotationClass, this));
}
/** {@link InvocationHandler} for dynamically instantiating an {@link Annotation} object. */
private static class AnnotationInvocationHandler implements InvocationHandler {
/** The annotation class. */
private final Class<? extends Annotation> annotationClass;
/** The {@link AnnotationInfo} object for this annotation. */
private final AnnotationInfo annotationInfo;
/** The annotation parameter values instantiated. */
private final Map<String, Object> annotationParameterValuesInstantiated = new HashMap<>();
/**
* Constructor.
*
* @param annotationClass
* the annotation class
* @param annotationInfo
* the annotation info
*/
AnnotationInvocationHandler(final Class<? extends Annotation> annotationClass,
final AnnotationInfo annotationInfo) {
this.annotationClass = annotationClass;
this.annotationInfo = annotationInfo;
// Instantiate the annotation parameter values (this loads and gets references for class literals,
// enum constants, etc.)
for (final AnnotationParameterValue apv : annotationInfo.getParameterValues()) {
final Object instantiatedValue = apv.instantiate(annotationInfo.getClassInfo());
if (instantiatedValue == null) {
// Annotations cannot contain null values
throw new IllegalArgumentException("Got null value for annotation parameter " + apv.getName()
+ " of annotation " + annotationInfo.getName());
}
this.annotationParameterValuesInstantiated.put(apv.getName(), instantiatedValue);
}
}
/* (non-Javadoc)
* @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method,
* java.lang.Object[])
*/
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) {
final String methodName = method.getName();
final Class<?>[] paramTypes = method.getParameterTypes();
if ((args == null ? 0 : args.length) != paramTypes.length) {
throw new IllegalArgumentException(
"Wrong number of arguments for " + annotationClass.getName() + "." + methodName + ": got "
+ (args == null ? 0 : args.length) + ", expected " + paramTypes.length);
}
if (args != null && paramTypes.length == 1) {
if (methodName.equals("equals") && paramTypes[0] == Object.class) {
// equals() needs to function the same as the JDK implementation
// (see src/share/classes/sun/reflect/annotation/AnnotationInvocationHandler.java in the JDK)
if (this == args[0]) {
return true;
} else if (!annotationClass.isInstance(args[0])) {
return false;
}
for (final Entry<String, Object> ent : annotationParameterValuesInstantiated.entrySet()) {
final String paramName = ent.getKey();
final Object paramVal = ent.getValue();
final Object otherParamVal = ReflectionUtils.invokeMethod(args[0], paramName,
/* throwException = */ false);
if ((paramVal == null) != (otherParamVal == null)) {
// Annotation values should never be null, but just to be safe
return false;
} else if (paramVal == null && otherParamVal == null) {
return true;
} else if (!paramVal.equals(otherParamVal)) {
return false;
}
}
return true;
} else {
// .equals(Object) is the only method of an enum that can take one parameter
throw new IllegalArgumentException();
}
} else if (paramTypes.length == 0) {
// Handle .toString(), .hashCode(), .annotationType()
switch (methodName) {
case "toString":
return annotationInfo.toString();
case "hashCode": {
// hashCode() needs to function the same as the JDK implementation
// (see src/share/classes/sun/reflect/annotation/AnnotationInvocationHandler.java in the JDK)
int result = 0;
for (final Entry<String, Object> ent : annotationParameterValuesInstantiated.entrySet()) {
final String paramName = ent.getKey();
final Object paramVal = ent.getValue();
int paramValHashCode;
if (paramVal == null) {
// Annotation values should never be null, but just to be safe
paramValHashCode = 0;
} else {
final Class<?> type = paramVal.getClass();
if (!type.isArray()) {
paramValHashCode = paramVal.hashCode();
} else if (type == byte[].class) {
paramValHashCode = Arrays.hashCode((byte[]) paramVal);
} else if (type == char[].class) {
paramValHashCode = Arrays.hashCode((char[]) paramVal);
} else if (type == double[].class) {
paramValHashCode = Arrays.hashCode((double[]) paramVal);
} else if (type == float[].class) {
paramValHashCode = Arrays.hashCode((float[]) paramVal);
} else if (type == int[].class) {
paramValHashCode = Arrays.hashCode((int[]) paramVal);
} else if (type == long[].class) {
paramValHashCode = Arrays.hashCode((long[]) paramVal);
} else if (type == short[].class) {
paramValHashCode = Arrays.hashCode((short[]) paramVal);
} else if (type == boolean[].class) {
paramValHashCode = Arrays.hashCode((boolean[]) paramVal);
} else {
paramValHashCode = Arrays.hashCode((Object[]) paramVal);
}
}
result += (127 * paramName.hashCode()) ^ paramValHashCode;
}
return result;
}
case "annotationType":
return annotationClass;
default:
// Fall through (other method names are used for returning annotation parameter values)
break;
}
} else {
// Throw exception for 2 or more params
throw new IllegalArgumentException();
}
// Instantiate the annotation parameter value (this loads and gets references for class literals,
// enum constants, etc.)
final Object annotationParameterValue = annotationParameterValuesInstantiated.get(methodName);
if (annotationParameterValue == null) {
// Undefined enum constant (enum values cannot be null)
throw new IncompleteAnnotationException(annotationClass, methodName);
}
// Clone any array-typed annotation parameter values, in keeping with the Java Annotation API
final Class<?> annotationParameterValueClass = annotationParameterValue.getClass();
if (annotationParameterValueClass.isArray()) {
// Handle array types
if (annotationParameterValueClass == String[].class) {
return ((String[]) annotationParameterValue).clone();
} else if (annotationParameterValueClass == byte[].class) {
return ((byte[]) annotationParameterValue).clone();
} else if (annotationParameterValueClass == char[].class) {
return ((char[]) annotationParameterValue).clone();
} else if (annotationParameterValueClass == double[].class) {
return ((double[]) annotationParameterValue).clone();
} else if (annotationParameterValueClass == float[].class) {
return ((float[]) annotationParameterValue).clone();
} else if (annotationParameterValueClass == int[].class) {
return ((int[]) annotationParameterValue).clone();
} else if (annotationParameterValueClass == long[].class) {
return ((long[]) annotationParameterValue).clone();
} else if (annotationParameterValueClass == short[].class) {
return ((short[]) annotationParameterValue).clone();
} else if (annotationParameterValueClass == boolean[].class) {
return ((boolean[]) annotationParameterValue).clone();
} else {
// Handle arrays of nested annotation types
final Object[] arr = (Object[]) annotationParameterValue;
return arr.clone();
}
}
return annotationParameterValue;
}
}
/**
* Convert wrapper arrays to primitive arrays.
*/
void convertWrapperArraysToPrimitiveArrays() {
if (annotationParamValues != null) {
annotationParamValues.convertWrapperArraysToPrimitiveArrays(getClassInfo());
}
}
/* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
@Override
public int compareTo(final AnnotationInfo o) {
final int diff = getName().compareTo(o.getName());
if (diff != 0) {
return diff;
}
if (annotationParamValues == null && o.annotationParamValues == null) {
return 0;
} else if (annotationParamValues == null) {
return -1;
} else if (o.annotationParamValues == null) {
return 1;
} else {
for (int i = 0, max = Math.max(annotationParamValues.size(),
o.annotationParamValues.size()); i < max; i++) {
if (i >= annotationParamValues.size()) {
return -1;
} else if (i >= o.annotationParamValues.size()) {
return 1;
} else {
final int diff2 = annotationParamValues.get(i).compareTo(o.annotationParamValues.get(i));
if (diff2 != 0) {
return diff2;
}
}
}
}
return 0;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof AnnotationInfo)) {
return false;
}
final AnnotationInfo o = (AnnotationInfo) obj;
return this.compareTo(o) == 0;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
int h = getName().hashCode();
if (annotationParamValues != null) {
for (final AnnotationParameterValue e : annotationParamValues) {
h = h * 7 + e.getName().hashCode() * 3 + e.getValue().hashCode();
}
}
return h;
}
/**
* Render as a string, into a StringBuilder buffer.
*
* @param buf
* The buffer.
*/
void toString(final StringBuilder buf) {
buf.append('@').append(getName());
final AnnotationParameterValueList paramVals = getParameterValues();
if (!paramVals.isEmpty()) {
buf.append('(');
for (int i = 0; i < paramVals.size(); i++) {
if (i > 0) {
buf.append(", ");
}
final AnnotationParameterValue paramVal = paramVals.get(i);
if (paramVals.size() > 1 || !"value".equals(paramVal.getName())) {
paramVal.toString(buf);
} else {
paramVal.toStringParamValueOnly(buf);
}
}
buf.append(')');
}
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
final StringBuilder buf = new StringBuilder();
toString(buf);
return buf.toString();
}
} |
package io.hosuaby.restful;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
/**
* Simple CORS filter that autorizes all origins. Because Undertow don't have
* one.
*/
@Component
// TODO: check CORS filter of Spring MVC
public class SimpleCorsFilter implements Filter {
/** {@inheritDoc}} */
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
/** {@inheritDoc}} */
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
httpResponse.setHeader("Access-Control-Max-Age", "3600");
httpResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(request, response);
}
/** {@inheritDoc}} */
@Override
public void destroy() {}
} |
package io.luna.game.model.mob;
import io.luna.game.model.Direction;
import io.luna.game.model.EntityType;
import io.luna.game.model.Position;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Objects;
import java.util.Queue;
import static com.google.common.base.Preconditions.checkState;
public final class WalkingQueue {
// TODO Rewrite
/**
* A model representing a step in the walking queue.
*/
public static final class Step {
/**
* The x coordinate.
*/
private final int x;
/**
* The y coordinate.
*/
private final int y;
/**
* Creates a new {@link Step}.
*
* @param x The x coordinate.
* @param y The y coordinate.
*/
public Step(int x, int y) {
checkState(x >= 0, "x < 0");
checkState(y >= 0, "y < 0");
this.x = x;
this.y = y;
}
/**
* Creates a new {@link Step}.
*
* @param position The position.
*/
public Step(Position position) {
this(position.getX(), position.getY());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj instanceof Step) {
Step other = (Step) obj;
return x == other.x && y == other.y;
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
/**
* @return The x coordinate.
*/
public int getX() {
return x;
}
/**
* @return The y coordinate.
*/
public int getY() {
return y;
}
}
/**
* A deque of current steps.
*/
private final Deque<Step> current = new ArrayDeque<>();
/**
* A deque of previous steps.
*/
private final Deque<Step> previous = new ArrayDeque<>();
/**
* The mob.
*/
private final Mob mob;
/**
* If movement is locked.
*/
private boolean locked;
/**
* If the current path is a running path.
*/
private boolean runningPath;
/**
* Create a new {@link WalkingQueue}.
*
* @param mob The mob.
*/
public WalkingQueue(Mob mob) {
this.mob = mob;
}
/**
* A function that determines your next walking and running directions, as well as your new position after
* taking steps.
*/
public void process() {
// TODO clean up function
Step current = new Step(mob.getPosition());
Direction walkingDirection = Direction.NONE;
Direction runningDirection = Direction.NONE;
boolean restoreEnergy = true;
Step next = this.current.poll();
if (next != null) {
previous.add(next);
walkingDirection = Direction.between(current, next);
current = next;
if (mob.getType() == EntityType.PLAYER) {
Player player = mob.asPlr();
if (player.isRunning() || runningPath) {
next = decrementRunEnergy(player) ? this.current.poll() : null;
if (next != null) {
restoreEnergy = false;
previous.add(next);
runningDirection = Direction.between(current, next);
current = next;
}
}
}
Position newPosition = new Position(current.getX(), current.getY(), mob.getPosition().getZ());
mob.setPosition(newPosition);
}
if (restoreEnergy && mob.getType() == EntityType.PLAYER) {
incrementRunEnergy();
}
mob.setWalkingDirection(walkingDirection);
mob.setRunningDirection(runningDirection);
}
/**
* Walks to the specified offsets.
*
* @param offsetX The {@code x} offset.
* @param offsetY The {@code y} offset.
*/
public void walk(int offsetX, int offsetY) {
var newPosition = mob.getPosition().translate(offsetX, offsetY);
addFirst(new Step(newPosition));
}
/**
* Walks to the specified {@code firstPos} and then {@code otherPos}.
*
* @param firstPos The first position.
* @param otherPos The other positions.
*/
public void walk(Position firstPos, Position... otherPos) {
addFirst(new Step(firstPos));
for (var nextPos : otherPos) {
add(new Step(nextPos));
}
}
/**
* Adds an initial step to this walking queue.
*
* @param step The step to add.
*/
public void addFirst(Step step) {
current.clear();
runningPath = false;
Queue<Step> backtrack = new ArrayDeque<>();
for (; ; ) {
Step prev = previous.pollLast();
if (prev == null) {
break;
}
backtrack.add(prev);
if (prev.equals(step)) {
backtrack.forEach(this::add);
previous.clear();
return;
}
}
previous.clear();
add(step);
}
/**
* Adds a non-initial step to this walking queue.
*
* @param next The step to add.
*/
public void add(Step next) {
Step last = current.peekLast();
if (last == null) {
last = new Step(mob.getPosition());
}
int nextX = next.getX();
int nextY = next.getY();
int deltaX = nextX - last.getX();
int deltaY = nextY - last.getY();
int max = Math.max(Math.abs(deltaX), Math.abs(deltaY));
for (int count = 0; count < max; count++) {
if (deltaX < 0) {
deltaX++;
} else if (deltaX > 0) {
deltaX
}
if (deltaY < 0) {
deltaY++;
} else if (deltaY > 0) {
deltaY
}
current.add(new Step(nextX - deltaX, nextY - deltaY));
}
}
/**
* Clears the current and previous steps.
*/
public void clear() {
current.clear();
previous.clear();
}
/**
* A function that implements an algorithm to deplete run energy.
*
* @return {@code false} if the player can no longer run.
*/
private boolean decrementRunEnergy(Player player) {
double totalWeight = player.getWeight();
double energyReduction = 0.117 * 2 * Math
.pow(Math.E, 0.0027725887222397812376689284858327062723020005374410 * totalWeight);
double newValue = player.getRunEnergy() - energyReduction;
if (newValue <= 0.0) {
player.setRunEnergy(0.0, true);
player.setRunning(false);
runningPath = false;
return false;
}
player.setRunEnergy(newValue, true);
return true;
}
/**
* A function that implements an algorithm to restore run energy.
*/
private void incrementRunEnergy() {
Player player = mob.asPlr();
double runEnergy = player.getRunEnergy();
if (runEnergy >= 100.0) {
return;
}
double agilityLevel = player.skill(Skill.AGILITY).getLevel();
double energyRestoration = 0.096 * Math
.pow(Math.E, 0.0162569486104454583293005993255170468638949631744294 * agilityLevel);
double newValue = runEnergy + energyRestoration;
newValue = Math.min(newValue, 100.0);
player.setRunEnergy(newValue, true);
}
/**
* Returns the current size of the walking queue.
*
* @return The amount of remaining steps.
*/
public int getRemainingSteps() {
return current.size();
}
/**
* Returns whether or not there are remaining steps.
*
* @return {@code true} if this walking queue is empty.
*/
public boolean isEmpty() {
return getRemainingSteps() == 0;
}
/**
* Sets if the current path is a running path.
*
* @param runningPath The new value.
*/
public void setRunningPath(boolean runningPath) {
checkState(mob.getType() == EntityType.PLAYER, "cannot change running value for NPCs");
this.runningPath = runningPath;
}
/**
* @return {@code true} if movement is locked.
*/
public boolean isLocked() {
return locked;
}
/**
* Sets if movement is locked.
*
* @param locked The new value.
*/
public void setLocked(boolean locked) {
this.locked = locked;
}
} |
package scalac.util;
import scala.tools.util.debug.Debugger;
import scala.tools.util.debug.ToStringDebugger;
import scalac.Global;
import scalac.ast.Tree;
import scalac.symtab.Scope;
import scalac.symtab.Symbol;
import scalac.symtab.Type;
/**
* Debugging class, used e.g. to obtain string representations of
* compiler data structures that are not "pretty-printed" and thus
* easier to relate to the source code.
*
* All methods are static to be easily useable in any context.
*
* @author Michel Schinz
* @version 1.0
*/
public class Debug extends scala.tools.util.debug.Debug {
//
// Private Initialization
/**
* Forces the initialization of this class. Returns the boolean
* value true so that it can be invoked from an assert statement.
*/
public static boolean initialize() {
// nothing to do, everything is done in the static initializer
return true;
}
static {
addDebugger(new ToStringDebugger(Tree.class));
addDebugger(new ToStringDebugger(Type.class));
addDebugger(SymbolDebugger.object);
addDebugger(ScopeDebugger.object);
}
//
// Public Methods - Logging
public static boolean log(Object a) {
return logAll(new Object[] {a});
}
public static boolean log(Object a, Object b) {
return logAll(new Object[] {a, b});
}
public static boolean log(Object a, Object b, Object c) {
return logAll(new Object[] {a, b, c});
}
public static boolean log(Object a, Object b, Object c, Object d) {
return logAll(new Object[] {a, b, c, d});
}
public static boolean logAll(Object[] args) {
return Global.instance.log(showAll(args, null));
}
//
// Public Methods - Bootstrapping
// !!! all the following methods are only needed for bootstraping
// !!! remove them after next release (current is 1.2.0.0)
public static Error abort() {
return scala.tools.util.debug.Debug.abort();
}
public static Error abort(Throwable cause) {
return scala.tools.util.debug.Debug.abort(cause);
}
public static Error abort(Object object) {
return scala.tools.util.debug.Debug.abort(object);
}
public static Error abort(Object object, Throwable cause) {
return scala.tools.util.debug.Debug.abort(object, cause);
}
public static Error abort(String message) {
return scala.tools.util.debug.Debug.abort(message);
}
public static Error abort(String message, Throwable cause) {
return scala.tools.util.debug.Debug.abort(message, cause);
}
public static Error abort(String message, Object object) {
return scala.tools.util.debug.Debug.abort(message, object);
}
public static Error abort(String message, Object object, Throwable cause) {
return scala.tools.util.debug.Debug.abort(message, object, cause);
}
public static Error abortIllegalCase(int value) {
return scala.tools.util.debug.Debug.abortIllegalCase(value);
}
public static Error abortIllegalCase(Object object) {
return scala.tools.util.debug.Debug.abortIllegalCase(object);
}
public static String show(Object a) {
return scala.tools.util.debug.Debug.show(a);
}
public static String show(Object a, Object b) {
return scala.tools.util.debug.Debug.show(a, b);
}
public static String show(Object a, Object b, Object c) {
return scala.tools.util.debug.Debug.show(a, b, c);
}
public static String show(Object a, Object b, Object c, Object d) {
return scala.tools.util.debug.Debug.show(a, b, c, d);
}
public static String show(Object a, Object b, Object c, Object d, Object e)
{
return scala.tools.util.debug.Debug.show(a, b, c, d, e);
}
public static String show(Object a, Object b, Object c, Object d, Object e,
Object f)
{
return scala.tools.util.debug.Debug.show(a, b, c, d, e, f);
}
public static String show(Object a, Object b, Object c, Object d, Object e,
Object f, Object g)
{
return scala.tools.util.debug.Debug.show(a, b, c, d, e, f, g);
}
public static String show(Object a, Object b, Object c, Object d, Object e,
Object f, Object g, Object h)
{
return scala.tools.util.debug.Debug.show(a, b, c, d, e, f, g, h);
}
public static String show(Object a, Object b, Object c, Object d, Object e,
Object f, Object g, Object h, Object i)
{
return scala.tools.util.debug.Debug.show(a, b, c, d, e, f, g, h, i);
}
public static String show(Object a, Object b, Object c, Object d, Object e,
Object f, Object g, Object h, Object i, Object j)
{
return scala.tools.util.debug.Debug.show(a, b, c, d, e, f, g, h, i, j);
}
public static String show(Object a, Object b, Object c, Object d, Object e,
Object f, Object g, Object h, Object i, Object j, Object k)
{
return scala.tools.util.debug.Debug.show(a, b, c, d, e, f, g, h, i, j, k);
}
public static String show(Object a, Object b, Object c, Object d, Object e,
Object f, Object g, Object h, Object i, Object j, Object k, Object l)
{
return scala.tools.util.debug.Debug.show(a, b, c, d, e, f, g, h, i, j, k, l);
}
public static String showAll(Object[] objects) {
return scala.tools.util.debug.Debug.showAll(objects);
}
public static String showAll(Object[] objects, String separator) {
return scala.tools.util.debug.Debug.showAll(objects, separator);
}
//
}
/** This class implements a debugger for symbols. */
public class SymbolDebugger implements Debugger {
//
// Public Constants
/** The unique instance of this class. */
public static final SymbolDebugger object = new SymbolDebugger();
//
// Protected Constructors
/** Initializes this instance. */
protected SymbolDebugger() {}
//
// Public Methods
public boolean canAppend(Object object) {
return object instanceof Symbol;
}
public void append(StringBuffer buffer, Object object) {
Symbol symbol = (Symbol)object;
if (!symbol.isNone() && !symbol.owner().isRoot() && !symbol.isRoot()) {
Debug.append(buffer, symbol.owner());
buffer.append(".");
}
buffer.append(symbol.name);
if (Global.instance.uniqid) {
buffer.append('
buffer.append(Global.instance.uniqueID.id(symbol));
}
if (symbol.isConstructor()) {
buffer.append('(');
buffer.append(symbol.constructorClass().name);
buffer.append(')');
}
}
//
}
/** This class implements a debugger for scopes. */
public class ScopeDebugger implements Debugger {
//
// Public Constants
/** The unique instance of this class. */
public static final ScopeDebugger object = new ScopeDebugger();
//
// Protected Constructors
/** Initializes this instance. */
protected ScopeDebugger() {}
//
// Public Methods
public boolean canAppend(Object object) {
return object instanceof Scope;
}
public void append(StringBuffer buffer, Object object) {
Scope scope = (Scope)object;
buffer.append('{');
for (Scope.SymbolIterator i = scope.iterator(); i.hasNext();) {
Debug.append(buffer, i.next());
if (i.hasNext()) buffer.append(',');
}
buffer.append('}');
}
//
} |
package com.anupcowkur.reservoir;
import android.content.Context;
import android.os.AsyncTask;
import com.google.gson.Gson;
import java.io.File;
import java.io.IOException;
/**
* The main reservoir class.
*/
public class Reservoir {
private static SimpleDiskCache cache;
/**
* Initialize Reservoir
*
* @param context context.
* @param maxSize the maximum size in bytes.
*/
public static synchronized void init(Context context, long maxSize) throws Exception {
//Create a directory inside the application specific cache directory. This is where all
// the key-value pairs will be stored.
File cacheDir = new File(context.getCacheDir() + "/Reservoir");
boolean success = true;
if (!cacheDir.exists()) {
success = cacheDir.mkdir();
}
if (!success) {
throw new IOException("Failed to create cache directory!");
}
cache = SimpleDiskCache.open(cacheDir, 1, maxSize);
}
/**
* Check if an object with the given key exists in the Reservoir.
*
* @param key the key string.
* @return true if object with given key exists.
*/
public static boolean contains(String key) throws Exception {
return cache.contains(key);
}
/**
* Put an object into Reservoir with the given key. This a blocking IO operation. Previously
* stored object with the same
* key (if any) will be overwritten.
*
* @param key the key string.
* @param object the object to be stored.
*/
public static void put(String key, Object object) throws Exception {
String json = new Gson().toJson(object);
cache.put(key, json);
}
/**
* Put an object into Reservoir with the given key asynchronously. Previously
* stored object with the same
* key (if any) will be overwritten.
*
* @param key the key string.
* @param object the object to be stored.
* @param callback a callback of type {@link com.anupcowkur.reservoir.ReservoirPutCallback}
* which is called upon completion.
*/
public static void putAsync(String key, Object object,
ReservoirPutCallback callback) {
new PutTask(key, object, callback).execute();
}
/**
* Get an object from Reservoir with the given key. This a blocking IO operation.
*
* @param key the key string.
* @param classOfT the Class type of the expected return object.
* @return the object of the given type if it exists.
*/
public static <T> T get(String key, Class<T> classOfT) throws Exception {
String json = cache.getString(key).getString();
T value = new Gson().fromJson(json, classOfT);
if (value == null)
throw new NullPointerException();
return value;
}
/**
* Get an object from Reservoir with the given key asynchronously.
*
* @param key the key string.
* @param callback a callback of type {@link com.anupcowkur.reservoir.ReservoirGetCallback}
* which is called upon completion.
*/
public static <T> void getAsync(String key, Class<T> classOfT,
ReservoirGetCallback<T> callback) {
new GetTask<T>(key, classOfT, callback).execute();
}
/**
* Delete an object from Reservoir with the given key. This a blocking IO operation. Previously
* stored object with the same
* key (if any) will be deleted.
*
* @param key the key string.
*/
public static void delete(String key) throws Exception {
cache.delete(key);
}
/**
* Delete an object into Reservoir with the given key asynchronously. Previously
* stored object with the same
* key (if any) will be deleted.
*
* @param key the key string.
* @param callback a callback of type {@link com.anupcowkur.reservoir.ReservoirDeleteCallback}
* which is called upon completion.
*/
public static void deleteAsync(String key, ReservoirDeleteCallback callback) {
new DeleteTask(key, callback).execute();
}
/**
* AsyncTask to perform put operation in a background thread.
*/
private static class PutTask extends AsyncTask<Void, Void, Void> {
private final String key;
private Exception e;
private final ReservoirPutCallback callback;
final Object object;
private PutTask(String key, Object object, ReservoirPutCallback callback) {
this.key = key;
this.callback = callback;
this.object = object;
this.e = null;
}
@Override
protected Void doInBackground(Void... params) {
try {
String json = new Gson().toJson(object);
cache.put(key, json);
} catch (Exception e) {
this.e = e;
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
if (callback != null) {
if (e == null) {
callback.onSuccess();
} else {
callback.onFailure(e);
}
}
}
}
/**
* AsyncTask to perform get operation in a background thread.
*/
private static class GetTask<T> extends AsyncTask<Void, Void, T> {
private final String key;
private final ReservoirGetCallback callback;
private final Class<T> classOfT;
private Exception e;
private GetTask(String key, Class<T> classOfT, ReservoirGetCallback callback) {
this.key = key;
this.callback = callback;
this.classOfT = classOfT;
this.e = null;
}
@Override
protected T doInBackground(Void... params) {
try {
String json = cache.getString(key).getString();
T value = new Gson().fromJson(json, classOfT);
if (value == null)
throw new NullPointerException();
return value;
} catch (Exception e) {
this.e = e;
return null;
}
}
@Override
protected void onPostExecute(T object) {
if (callback != null) {
if (e == null) {
callback.onSuccess(object);
} else {
callback.onFailure(e);
}
}
}
}
/**
* AsyncTask to perform delete operation in a background thread.
*/
private static class DeleteTask extends AsyncTask<Void, Void, Void> {
private final String key;
private Exception e;
private final ReservoirDeleteCallback callback;
private DeleteTask(String key, ReservoirDeleteCallback callback) {
this.key = key;
this.callback = callback;
this.e = null;
}
@Override
protected Void doInBackground(Void... params) {
try {
cache.delete(key);
} catch (Exception e) {
this.e = e;
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
if (callback != null) {
if (e == null) {
callback.onSuccess();
} else {
callback.onFailure(e);
}
}
}
}
} |
package com.hida.dao;
import com.hida.configuration.HsqlDataTypeFactory;
import com.hida.model.TokenType;
import com.hida.model.UsedSetting;
import java.sql.Connection;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.operation.DatabaseOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
*
* @author lruffin
*/
public class UsedSettingDaoImplTest extends EntityDaoImplTest {
@Autowired
UsedSettingDao UsedSettingDao;
@Override
protected IDataSet getDataSet() throws Exception {
IDataSet dataSet = new FlatXmlDataSet(this.getClass().getClassLoader().
getResourceAsStream("UsedSetting.xml"));
return dataSet;
}
@Test
public void saveTest() {
UsedSettingDao.save(getSampleUsedSetting());
Assert.assertEquals(UsedSettingDao.findAllUsedSettings().size(), 3);
}
@Test
public void findUsedSettingByIdTest() {
UsedSetting entity = UsedSettingDao.findUsedSettingById(1);
Assert.assertNotNull(entity);
}
@Test
public void findAllUsedSettings() {
Assert.fail("unimplemented");
}
@Test
public void findUsedSetting() {
Assert.fail("unimplemented");
}
private UsedSetting getSampleUsedSetting() {
UsedSetting setting = new UsedSetting("",
TokenType.DIGIT,
"d",
1,
true,
1);
return setting;
}
} |
package movealarm.kmitl.net;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
public class Image extends Model
{
private String name = null;
private int imgData = 0;
private String description = null;
public Image() {
this.tableName = "image";
this.requiredFields = new ArrayList<>();
this.requiredFields.add("name");
this.requiredFields.add("imgData");
}
public static Model find(int id)
{
HashMap<String,Object> img_map = modelCollection.find("image",id);
if(img_map == null) {
return null;
}
Image model = new Image();
model.id = (int)img_map.get("id");
model.name = (String)img_map.get("name");
model.imgData = (int)img_map.get("imgData");
model.description = (String)img_map.get("description");
model.modifiedDate = (Date)img_map.get("modified_date");
return model;
}
public static Image[] where(String colName,String operator,String value)
{
ArrayList<HashMap<String, Object>> img_arr = modelCollection.where("image", colName, operator, value);
ArrayList<Image> collection = new ArrayList<>();
for(HashMap<String, Object> item : img_arr) {
Image model = new Image();
model.id = (int)item.get("id");
model.name = (String)item.get("name");
model.imgData = (int)item.get("imgData");
model.description = (String)item.get("description");
model.modifiedDate = (Date)item.get("modified_date");
collection.add(model);
}
return collection.toArray(new Image[collection.size()]);
}
public static Image[] where(String colName, String operator, String value,String extraCondition)
{
return where(colName, operator, value + " " + extraCondition);
}
public static Image[] all()
{
ArrayList<HashMap<String, Object>> img_arr = modelCollection.all("image");
ArrayList<Image> collection = new ArrayList<>();
for(HashMap<String, Object>item : img_arr) {
Image model = new Image();
model.id = (int)item.get("id");
model.name = (String)item.get("name");
model.imgData = (int)item.get("imgData");
model.description = (String)item.get("description");
model.modifiedDate = (Date)item.get("modified_date");
collection.add(model);
}
return collection.toArray(new Image[collection.size()]);
}
public HashMap<String, Object> changeImage(String name,int imgData,String description)
{
setName(name);
setImgData(imgData);
setDescription(description);
updateModifiedDate();
return save();
}
public HashMap<String,Object> getValues()
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
HashMap<String,Object> img_map = new HashMap<>();
img_map.put("name",this.name);
img_map.put("imgData",this.imgData);
if(this.modifiedDate == null) {
img_map.put("modified_date",null);
}
else {
img_map.put("modified_date",sdf.format(this.modifiedDate));
}
return img_map;
}
@Override
public HashMap<String, Object> getGeneralValue() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
HashMap<String,Object> img_map = new HashMap<>();
img_map.put("name",this.name);
img_map.put("imgData",this.imgData);
if(this.modifiedDate == null) {
img_map.put("modified_date",null);
}
else {
img_map.put("modified_date",sdf.format(this.modifiedDate));
}
return img_map;
}
public void setName(String name)
{
this.name = name;
updateModifiedDate();
}
public void setImgData(int imgData)
{
this.imgData = imgData;
updateModifiedDate();
}
public void setDescription(String description)
{
this.description = description;
updateModifiedDate();
}
public String getName()
{
return this.name;
}
public int getImgData()
{
return this.imgData;
}
public String getDescription() {
return this.description;
}
public Date getModifiedDate()
{
return modifiedDate;
}
public HashMap<String, Object> getGeneralValues()
{
return new HashMap<>();
}
@Override
public HashMap<String, Object> save()
{
HashMap<String, Object> requireFields = checkRequiredFields();
if(requireFields != null) {
return requireFields;
}
if(createdDate == null) {
HashMap<String, Object> temp = modelCollection.create(this);
if(temp == null) {
return StatusDescription.createProcessStatus(false,"Cannot save due to database error.");
}
}
return StatusDescription.createProcessStatus(modelCollection.save(this));
}
@Override
public HashMap<String, Object> delete()
{
return StatusDescription.createProcessStatus(modelCollection.delete(this));
}
} |
package umiker9.stardust2d.util.collision;
import umiker9.stardust2d.util.math.MathUtil;
import umiker9.stardust2d.util.math.Vec2;
import java.util.ArrayList;
import java.util.Collections;
public class Collision2D {
public static final double LIMIT_VALUE = 10000F;
public static final double ERROR_VALUE = 0.001F;
public static boolean checkAABBCollision(AABB2D aabb1, AABB2D aabb2) {
return aabb1.pMin.getX() <= aabb2.pMax.getX() &&
aabb1.pMax.getX() >= aabb2.pMin.getX() &&
aabb1.pMin.getY() <= aabb2.pMax.getY() &&
aabb1.pMax.getY() >= aabb2.pMin.getY();
}
public static boolean checkAABBInside(AABB2D aabb1, AABB2D aabb2) {
return aabb1.pMin.getX() > aabb2.pMin.getX() &&
aabb1.pMax.getX() < aabb2.pMax.getX() &&
aabb1.pMin.getY() > aabb2.pMin.getY() &&
aabb1.pMax.getY() < aabb2.pMax.getY();
}
public static boolean checkAABBInside(Vec2[] points) {
return points[0].getX() > points[4].getX() &&
points[2].getX() < points[6].getX() &&
points[0].getY() > points[4].getY() &&
points[2].getY() < points[6].getY();
}
public static Vec2[] getAABBCollision(Vec2[] points) {
Vec2 p;
Vec2 lp1;
Vec2 lp2;
ArrayList<Vec2> ret = new ArrayList<Vec2>();
if(checkAABBInside(points)) {
ret.add(new Vec2((points[0].getX() + points[2].getX())/2, (points[0].getY() + points[2].getY())/2));
ret.add(new Vec2((points[4].getX() + points[6].getX())/2, (points[4].getY() + points[6].getY())/2));
return ret.toArray(new Vec2[ret.size()]);
}
for(int i = 0; i < 4; i++) {
for(int k = 0; k < 2; k++) {
int i2 = i + 1;
if(i == 3) i2 = 0;
int n, m, p1, p2;
if(i % 2 == 0) {
if(k == 0) {
n = i; m = i2 + 4;
p1 = m; p2 = m + 1;
} else {
n = i; m = i + 4;
p1 = m; p2 = m - 1;
}
} else {
if(k == 0) {
n = i2 + 4; m = i;
p1 = n; p2 = n + 1;
} else {
n = i + 4; m = i;
p1 = n; p2 = n - 1;
}
}
if(p2 == -1) p2 = 7;
p = new Vec2(points[n].getX(), points[m].getY());
lp1 = new Vec2(points[i].getX(), points[i].getY());
lp2 = new Vec2(points[i2].getX(), points[i2].getY());
if (checkPointAtAABBLineSegment(p, lp1, lp2)) {
lp1 = new Vec2(points[p1].getX(), points[p1].getY());
lp2 = new Vec2(points[p2].getX(), points[p2].getY());
if(checkPointAtAABBLineSegment(p, lp1, lp2))
ret.add(new Vec2(p));
}
}
}
return ret.toArray(new Vec2[ret.size()]);
}
public static Vec2[] getAABBCollision(AABB2D aabb1, AABB2D aabb2) {
Vec2[] points = new Vec2[] {
aabb1.pMin,
new Vec2(aabb1.pMin.getX(), aabb1.pMax.getY()),
aabb1.pMax,
new Vec2(aabb1.pMax.getX(), aabb1.pMin.getY()),
aabb2.pMin,
new Vec2(aabb2.pMin.getX(), aabb2.pMax.getY()),
aabb2.pMax,
new Vec2(aabb2.pMax.getX(), aabb2.pMin.getY())
};
return getAABBCollision(points);
}
public static Vec2[] getShapesCollision(Vec2[] obj1, Vec2[] obj2) {
ArrayList<Vec2> points = new ArrayList<Vec2>();
Vec2 point;
int i1, i2, k1, k2;
for(int i = 0; i < obj1.length; i++) {
for(int k = 0; k < obj2.length; k++) {
i1 = i;
if(i + 1 >= obj1.length) i2 = 0;
else i2 = i + 1;
k1 = k;
if(k + 1 >= obj2.length) k2 = 0;
else k2 = k + 1;
if((point = getLineSegmentsCollisionPoint(obj1[i1], obj1[i2], obj2[k1], obj2[k2])) != null) {
points.add(point);
}
}
}
return points.toArray(new Vec2[points.size()]);
}
public static Vec2 getLineSegmentsCollisionPoint(Vec2 l1p1, Vec2 l1p2, Vec2 l2p1, Vec2 l2p2) {
double k1 = getLineK(l1p1, l1p2);
double k2 = getLineK(l2p1, l2p2);
double b1 = l1p1.getY() - l1p1.getX() * k1;
double b2 = l2p1.getY() - l2p1.getX() * k2;
double x = (b2 - b1) / (k1 - k2);
double y = k1 * x + b1;
Vec2 point = new Vec2(x, y);
if(checkPointAtLineSegment(point, l1p1, l1p2) && checkPointAtLineSegment(point, l2p1, l2p2)) {
return point;
}
return null;
}
public static boolean checkPointAtLineSegment(Vec2 p, Vec2 lp1, Vec2 lp2) {
double x1 = Math.min(lp1.getX(), lp2.getX());
double x2 = Math.max(lp1.getX(), lp2.getX());
double y1 = Math.min(lp1.getY(), lp2.getY());
double y2 = Math.max(lp1.getY(), lp2.getY());
return p.getX() >= x1 - ERROR_VALUE && p.getX() <= x2 + ERROR_VALUE && p.getY() >= y1 - ERROR_VALUE && p.getY() <= y2 + ERROR_VALUE;
}
public static boolean checkPointAtAABBLineSegment(Vec2 p, Vec2 lp1, Vec2 lp2) {
if(lp1.getX() == lp2.getX()) {
double x = lp1.getX();
double y1 = Math.min(lp1.getY(), lp2.getY());
double y2 = Math.max(lp1.getY(), lp2.getY());
if(p.getX() == x && p.getY() >= y1 && p.getY() <= y2) {
return true;
}
} else {
double x1 = Math.min(lp1.getX(), lp2.getX());
double x2 = Math.max(lp1.getX(), lp2.getX());
double y = lp1.getY();
if(p.getX() >= x1 && p.getX() <= x2 && p.getY() == y) {
return true;
}
}
return false;
}
public static double getSqDistanceFromLineToPoint(Vec2 lp1, Vec2 lp2, Vec2 p) {
double k1 = getLineK(lp1, lp2);
double b1 = lp1.getY() - lp1.getX() * k1;
double k2 = -1/k1;
double b2 = p.getY() - p.getX() * k2;
double x = (b2 - b1) / (k1 - k2);
double y = k1 * x + b1;
return (x - p.getX())*(x - p.getX()) + (y - p.getY())*(y - p.getY());
}
public static double getDistanceFromLineToPoint(Vec2 lp1, Vec2 lp2, Vec2 p) {
return Math.sqrt(getSqDistanceFromLineToPoint(lp1, lp2, p));
}
public static double getSqDistanceFromLineSegmentToPoint(Vec2 lp1, Vec2 lp2, Vec2 p) {
double k1 = getLineK(lp1, lp2);
double b1 = lp1.getY() - lp1.getX() * k1;
double k2 = -1/k1;
double b2 = p.getY() - p.getX() * k2;
double x = (b2 - b1) / (k1 - k2);
double y = k1 * x + b1;
if(checkPointAtLineSegment(new Vec2(x, y), lp1, lp2))
return (x - p.getX())*(x - p.getX()) + (y - p.getY())*(y - p.getY());
else
return Math.min((lp1.getX() - p.getX())*(lp1.getX() - p.getX()) + (lp1.getY() - p.getY())*(lp1.getY() - p.getY()),
(lp2.getX() - p.getX())*(lp2.getX() - p.getX()) + (lp2.getY() - p.getY())*(lp2.getY() - p.getY()));
}
public static double getDistanceFromLineSegmentToPoint(Vec2 lp1, Vec2 lp2, Vec2 p) {
return Math.sqrt(getSqDistanceFromLineSegmentToPoint(lp1, lp2, p));
}
public static boolean checkCirclesCollision(Vec2 o1, double r1, Vec2 o2, double r2) {
return (o1.getX() - o2.getX())*(o1.getX() - o2.getX()) + (o1.getY() - o2.getY())*(o1.getY() - o2.getY()) <= (r1 + r2)*(r1 + r2);
}
//not working properly
public static Vec2[] getCirclesCollision(Vec2 o1, double r1, Vec2 o2, double r2) {
double ox = o2.getX() - o1.getX();
double oy = o2.getY() - o1.getY();
double A = -2 * ox;
double B = -2 * oy;
double C = ox*ox + oy*oy + r1*r1 - r2*r2;
double lineK = - A / B;
double lineB = - C / B;
double a = lineK*lineK + 1;
double b = 2 * (lineK * (lineB - oy) - ox);
double c = ox*ox + (lineB - oy)*(lineB - oy) - r2*r2;
double D = b*b - 4 * a * c;
if(D < 0) {
return new Vec2[] {};
}
if(D == 0) {
double x, y;
x = - b / (2 * a) + o1.getX();
y = lineK * x + lineB + o1.getY();
Vec2 point = new Vec2(x, y);
return new Vec2[] {point};
}
double x1, x2, y1, y2;
x1 = - (b + Math.sqrt(D)) / (2 * a) + o1.getX();
y1 = lineK * x1 + lineB + o1.getY();
x2 = - (b - Math.sqrt(D)) / (2 * a) + o1.getX();
y2 = lineK * x2 + lineB + o1.getY();
Vec2 point1 = new Vec2(x1, y1);
Vec2 point2 = new Vec2(x2, y2);
return new Vec2[] {point1, point2};
}
public static boolean checkCircleWithLineSegmentCollision(Vec2 o, double r, Vec2 lp1, Vec2 lp2) {
return getSqDistanceFromLineSegmentToPoint(lp1, lp2, o) <= r*r;
}
public static Vec2[] getCircleWithLineSegmentCollision(Vec2 o, double r, Vec2 lp1, Vec2 lp2) {
double lineK = getLineK(lp1, lp2);
double lineB = lp1.getY() - lp1.getX() * lineK;
double a = lineK*lineK + 1;
double b = 2 * (lineK * (lineB - o.getY()) - o.getX());
double c = o.getX()*o.getX() + (lineB - o.getY())*(lineB - o.getY()) - r*r;
double D = b*b - 4 * a * c;
if(D < 0) {
return new Vec2[] {};
}
if(D == 0) {
double x, y;
x = - b / (2 * a);
y = lineK * x + lineB;
Vec2 point = new Vec2(x, y);
if(checkPointAtLineSegment(point, lp1, lp2)) {
return new Vec2[] {point};
}
return new Vec2[] {};
}
double x1, x2, y1, y2;
double sqrtD = Math.sqrt(D);
x1 = - (b + sqrtD) / (2 * a);
y1 = lineK * x1 + lineB;
x2 = - (b - sqrtD) / (2 * a);
y2 = lineK * x2 + lineB;
Vec2 point1 = new Vec2(x1, y1);
Vec2 point2 = new Vec2(x2, y2);
ArrayList<Vec2> points = new ArrayList<Vec2>();
int i = 0;
if(checkPointAtLineSegment(point1, lp1, lp2)) {
points.add(point1);
i++;
}
if(checkPointAtLineSegment(point2, lp1, lp2)) {
points.add(point2);
i++;
}
return points.toArray(new Vec2[i]);
}
public static double getLineK(Vec2 p1, Vec2 p2) {
return MathUtil.clamp(-LIMIT_VALUE, (p2.getY() - p1.getY()) / (p2.getX() - p1.getX()), LIMIT_VALUE);
}
public static Vec2[] getShapeWithCircleCollision(Vec2[] shape, Vec2 o, double r) {
ArrayList<Vec2> points = new ArrayList<Vec2>();
Vec2[] buffer;
for(int i = 0; i < shape.length; i++) {
if(i == shape.length - 1) {
buffer = getCircleWithLineSegmentCollision(o, r, shape[i], shape[0]);
} else {
buffer = getCircleWithLineSegmentCollision(o, r, shape[i], shape[i+1]);
}
Collections.addAll(points, buffer);
}
return points.toArray(new Vec2[points.size()]);
}
public static boolean isPointInsideShape(Vec2 point, Vec2 shift, Vec2... shape) {
int i = 1;
double A, B, C, f;
Vec2 p1, p2;
point = point.subtract(shift);
for(Vec2 shapePoint : shape) {
if(i == shape.length) i = 0;
p1 = shapePoint.subtract(shift);
p2 = shape[i].subtract(shift);
A = p1.getY() - p2.getY();
B = p2.getX() - p1.getX();
C = p1.getX() * p2.getY() - p2.getX() * p1.getY();
f = A*point.getX() + B*point.getY() + C;
if(f > 0) return false;
}
return true;
}
public static boolean isShapesIntersect(Vec2[] shape1, Vec2[] shape2, Vec2 shift) {
for(Vec2 point : shape1) {
if(isPointInsideShape(point, shift, shape2)) return true;
}
for(Vec2 point : shape2) {
if(isPointInsideShape(point, shift, shape1)) return true;
}
return false;
}
} |
package org.epics.pvmanager.data;
import java.text.NumberFormat;
/**
* Limit and unit information needed for display and control.
* <p>
* The numeric limits are given in double precision no matter which numeric
* type. The unit is a simple String, which can be empty if no unit information
* is provided. The number format can be used to convert the value to a String.
*
* @author carcassi
*/
public interface Display {
/**
* Lowest possible value to be displayed. Never null.
*
* @return lower display limit
*/
@Metadata
Double getLowerDisplayLimit();
/**
* Lowest possible value (included). Never null.
*
* @return lower limit
*/
@Metadata
Double getLowerCtrlLimit();
/**
* Lowest value before the alarm region. Never null.
*
* @return lower alarm limit
*/
@Metadata
Double getLowerAlarmLimit();
/**
* Lowest value before the warning region. Never null.
*
* @return lower warning limit
*/
@Metadata
Double getLowerWarningLimit();
/**
* String representation of the units using for all values.
* Never null. If not available, returns the empty String.
*
* @return units
*/
@Metadata
String getUnits();
/**
* Returns a NumberFormat that creates a String with just the value (no units).
* Format is locale independent and should be used for all values (values and
* lower/upper limits). Never null.
*
* @return the default format for all values
*/
@Metadata
NumberFormat getFormat();
/**
* Highest value before the warning region. Never null.
*
* @return upper warning limit
*/
@Metadata
Double getUpperWarningLimit();
/**
* Highest value before the alarm region. Never null.
*
* @return upper alarm limit
*/
@Metadata
Double getUpperAlarmLimit();
/**
* Highest possible value (included). Never null.
* @return upper limit
*/
@Metadata
Double getUpperCtrlLimit();
/**
* Highest possible value to be displayed. Never null.
*
* @return upper display limit
*/
@Metadata
Double getUpperDisplayLimit();
} |
package com.takwolf.digest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public final class Digest {
public enum Algorithm {
MD2("MD2"),
MD5("MD5"),
SHA1("SHA-1"),
SHA256("SHA-256"),
SHA384("SHA-384"),
SHA512("SHA-512");
private final String value;
Algorithm(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
private final Algorithm algorithm;
public Digest(Algorithm algorithm) {
this.algorithm = algorithm;
}
public byte[] getRaw(byte[] data) {
try {
return MessageDigest.getInstance(algorithm.getValue()).digest(data);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
public byte[] getRaw(String data) {
return getRaw(data.getBytes());
}
public String getHex(byte[] data) {
StringBuilder sb = new StringBuilder();
for (byte b : getRaw(data)) {
sb.append(String.format("%02x", b & 0xFF));
}
return sb.toString();
}
public String getHex(String data) {
return getHex(data.getBytes());
}
} |
package org.xdi.oxauth.service;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.gluu.persist.PersistenceEntryManager;
import org.gluu.persist.exception.EntryPersistenceException;
import org.gluu.persist.model.BatchOperation;
import org.gluu.persist.model.ProcessBatchOperation;
import org.gluu.persist.model.SearchScope;
import org.gluu.search.filter.Filter;
import org.slf4j.Logger;
import org.xdi.oxauth.audit.ApplicationAuditLogger;
import org.xdi.oxauth.model.audit.Action;
import org.xdi.oxauth.model.audit.OAuth2AuditLog;
import org.xdi.oxauth.model.common.AuthorizationGrant;
import org.xdi.oxauth.model.common.CacheGrant;
import org.xdi.oxauth.model.common.ClientTokens;
import org.xdi.oxauth.model.common.SessionTokens;
import org.xdi.oxauth.model.config.StaticConfiguration;
import org.xdi.oxauth.model.configuration.AppConfiguration;
import org.xdi.oxauth.model.ldap.Grant;
import org.xdi.oxauth.model.ldap.TokenLdap;
import org.xdi.oxauth.model.ldap.TokenType;
import org.xdi.oxauth.model.registration.Client;
import org.xdi.oxauth.util.TokenHashUtil;
import org.xdi.service.CacheService;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.inject.Named;
import java.util.*;
import static org.xdi.oxauth.util.ServerUtil.isTrue;
/**
* @author Yuriy Zabrovarnyy
* @author Javier Rojas Blum
* @version November 28, 2018
*/
@Stateless
@Named
public class GrantService {
@Inject
private Logger log;
@Inject
private PersistenceEntryManager ldapEntryManager;
@Inject
private ApplicationAuditLogger applicationAuditLogger;
@Inject
private ClientService clientService;
@Inject
private CacheService cacheService;
@Inject
private StaticConfiguration staticConfiguration;
@Inject
private AppConfiguration appConfiguration;
public static String generateGrantId() {
return UUID.randomUUID().toString();
}
public String buildDn(String p_uniqueIdentifier, String p_grantId, String p_clientId) {
final StringBuilder dn = new StringBuilder();
dn.append(String.format("uniqueIdentifier=%s,oxAuthGrantId=%s,", p_uniqueIdentifier, p_grantId));
dn.append(clientService.buildClientDn(p_clientId));
return dn.toString();
}
public String baseDn() {
return staticConfiguration.getBaseDn().getClients(); // ou=clients,o=@!1111,o=gluu
}
public void merge(TokenLdap p_token) {
ldapEntryManager.merge(p_token);
}
public void mergeSilently(TokenLdap p_token) {
try {
ldapEntryManager.merge(p_token);
} catch (Exception e) {
log.trace(e.getMessage(), e);
}
}
private boolean shouldPutInCache(TokenType tokenType, boolean isImplicitFlow) {
if (isImplicitFlow && BooleanUtils.isTrue(appConfiguration.getUseCacheForAllImplicitFlowObjects())) {
return true;
}
switch (tokenType) {
case ID_TOKEN:
if (!isTrue(appConfiguration.getPersistIdTokenInLdap())) {
return true;
}
case REFRESH_TOKEN:
if (!isTrue(appConfiguration.getPersistRefreshTokenInLdap())) {
return true;
}
}
return false;
}
public void persist(TokenLdap token) {
String hashedToken = TokenHashUtil.getHashedToken(token.getTokenCode());
token.setTokenCode(hashedToken);
if (shouldPutInCache(token.getTokenTypeEnum(), token.isImplicitFlow())) {
ClientTokens clientTokens = getCacheClientTokens(token.getClientId());
clientTokens.getTokenHashes().add(hashedToken);
String expiration = null;
switch (token.getTokenTypeEnum()) {
case ID_TOKEN:
expiration = Integer.toString(appConfiguration.getIdTokenLifetime());
break;
case REFRESH_TOKEN:
expiration = Integer.toString(appConfiguration.getRefreshTokenLifetime());
break;
case ACCESS_TOKEN:
int lifetime = appConfiguration.getAccessTokenLifetime();
Client client = clientService.getClient(token.getClientId());
// oxAuth #830 Client-specific access token expiration
if (client != null && client.getAccessTokenLifetime() != null && client.getAccessTokenLifetime() > 0) {
lifetime = client.getAccessTokenLifetime();
}
expiration = Integer.toString(lifetime);
break;
}
token.setIsFromCache(true);
cacheService.put(expiration, hashedToken, token);
cacheService.put(expiration, clientTokens.cacheKey(), clientTokens);
if (StringUtils.isNotBlank(token.getSessionDn())) {
SessionTokens sessionTokens = getCacheSessionTokens(token.getSessionDn());
sessionTokens.getTokenHashes().add(hashedToken);
cacheService.put(expiration, sessionTokens.cacheKey(), sessionTokens);
}
return;
}
prepareGrantBranch(token.getGrantId(), token.getClientId());
try {
ldapEntryManager.persist(token);
} catch (EntryPersistenceException ex) {
// Cover case when cleaner removed sub-entry in parallel with this
if (ex.getCause() instanceof LDAPException) {
LDAPException ldapException = (LDAPException) ex.getCause();
if (com.unboundid.ldap.sdk.ResultCode.NO_SUCH_OBJECT.equals(ldapException.getResultCode())) {
prepareGrantBranch(token.getGrantId(), token.getClientId());
ldapEntryManager.persist(token);
}
} else {
throw ex;
}
}
}
public ClientTokens getCacheClientTokens(String clientId) {
ClientTokens clientTokens = new ClientTokens(clientId);
Object o = cacheService.get(null, clientTokens.cacheKey());
if (o instanceof ClientTokens) {
return (ClientTokens) o;
} else {
return clientTokens;
}
}
public SessionTokens getCacheSessionTokens(String sessionDn) {
SessionTokens sessionTokens = new SessionTokens(sessionDn);
Object o = cacheService.get(null, sessionTokens.cacheKey());
if (o instanceof SessionTokens) {
return (SessionTokens) o;
} else {
return sessionTokens;
}
}
public void remove(Grant grant) {
ldapEntryManager.remove(grant);
log.trace("Removed grant, id: " + grant.getId());
}
public void remove(TokenLdap p_token) {
if (p_token.isFromCache()) {
cacheService.remove(null, TokenHashUtil.getHashedToken(p_token.getTokenCode()));
log.trace("Removed token from cache, code: " + p_token.getTokenCode());
} else {
ldapEntryManager.remove(p_token);
log.trace("Removed token from LDAP, code: " + p_token.getTokenCode());
}
}
public void removeSilently(TokenLdap token) {
try {
remove(token);
if (StringUtils.isNotBlank(token.getAuthorizationCode())) {
cacheService.remove(null, CacheGrant.cacheKey(token.getClientId(), token.getAuthorizationCode(), token.getGrantId()));
}
} catch (Exception e) {
log.trace(e.getMessage(), e);
}
}
public void removeGrants(List<Grant> entries) {
if (entries != null && !entries.isEmpty()) {
for (Grant g : entries) {
try {
remove(g);
} catch (Exception e) {
log.error("Failed to remove entry", e);
}
}
}
}
public void remove(List<TokenLdap> p_entries) {
if (p_entries != null && !p_entries.isEmpty()) {
for (TokenLdap t : p_entries) {
try {
remove(t);
} catch (Exception e) {
log.error("Failed to remove entry", e);
}
}
}
}
public void removeSilently(List<TokenLdap> p_entries) {
if (p_entries != null && !p_entries.isEmpty()) {
for (TokenLdap t : p_entries) {
removeSilently(t);
}
}
}
public void remove(AuthorizationGrant p_grant) {
if (p_grant != null && p_grant.getTokenLdap() != null) {
try {
remove(p_grant.getTokenLdap());
} catch (Exception e) {
log.trace(e.getMessage(), e);
}
}
}
public List<TokenLdap> getGrantsOfClient(String p_clientId) {
try {
final String baseDn = clientService.buildClientDn(p_clientId);
return ldapEntryManager.findEntries(baseDn, TokenLdap.class, Filter.create("oxAuthTokenCode=*"));
} catch (Exception e) {
log.trace(e.getMessage(), e);
}
return Collections.emptyList();
}
public TokenLdap getGrantsByCodeAndClient(String p_code, String p_clientId) {
return load(clientService.buildClientDn(p_clientId), p_code);
}
public TokenLdap getGrantsByCode(String p_code) {
return getGrantsByCode(p_code, false);
}
public TokenLdap getGrantsByCode(String p_code, boolean onlyFromCache) {
Object grant = cacheService.get(null, TokenHashUtil.getHashedToken(p_code));
if (grant instanceof TokenLdap) {
return (TokenLdap) grant;
} else {
if (onlyFromCache) {
return null;
}
return load(baseDn(), p_code);
}
}
private TokenLdap load(String p_baseDn, String p_code) {
try {
final List<TokenLdap> entries = ldapEntryManager.findEntries(p_baseDn, TokenLdap.class, Filter.createEqualityFilter("oxAuthTokenCode", TokenHashUtil.getHashedToken(p_code)));
if (entries != null && !entries.isEmpty()) {
return entries.get(0);
}
} catch (Exception e) {
log.trace(e.getMessage(), e);
}
return null;
}
public List<TokenLdap> getGrantsByGrantId(String p_grantId) {
try {
return ldapEntryManager.findEntries(baseDn(), TokenLdap.class, Filter.createEqualityFilter("oxAuthGrantId", p_grantId));
} catch (Exception e) {
log.trace(e.getMessage(), e);
}
return Collections.emptyList();
}
public List<TokenLdap> getGrantsByAuthorizationCode(String p_authorizationCode) {
try {
return ldapEntryManager.findEntries(baseDn(), TokenLdap.class, Filter.createEqualityFilter("oxAuthAuthorizationCode", TokenHashUtil.getHashedToken(p_authorizationCode)));
} catch (Exception e) {
log.trace(e.getMessage(), e);
}
return Collections.emptyList();
}
public List<TokenLdap> getGrantsBySessionDn(String sessionDn) {
List<TokenLdap> grants = new ArrayList<TokenLdap>();
try {
List<TokenLdap> ldapGrants = ldapEntryManager.findEntries(baseDn(), TokenLdap.class, Filter.create(String.format("oxAuthSessionDn=%s", sessionDn)));
if (ldapGrants != null) {
grants.addAll(ldapGrants);
}
grants.addAll(getGrantsFromCacheBySessionDn(sessionDn));
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return grants;
}
public List<TokenLdap> getGrantsFromCacheBySessionDn(String sessionDn) {
if (StringUtils.isBlank(sessionDn)) {
return Collections.emptyList();
}
return getCacheTokensEntries(getCacheSessionTokens(sessionDn).getTokenHashes());
}
public List<TokenLdap> getCacheClientTokensEntries(String clientId) {
Object o = cacheService.get(null, new ClientTokens(clientId).cacheKey());
if (o instanceof ClientTokens) {
return getCacheTokensEntries(((ClientTokens) o).getTokenHashes());
}
return Collections.emptyList();
}
public List<TokenLdap> getCacheTokensEntries(Set<String> tokenHashes) {
List<TokenLdap> tokens = new ArrayList<TokenLdap>();
for (String tokenHash : tokenHashes) {
Object o1 = cacheService.get(null, tokenHash);
if (o1 instanceof TokenLdap) {
TokenLdap token = (TokenLdap) o1;
token.setIsFromCache(true);
tokens.add(token);
}
}
return tokens;
}
public void removeAllTokensBySession(String sessionDn) {
removeSilently(getGrantsBySessionDn(sessionDn));
}
/**
* Removes grant with particular code.
*
* @param p_code code
*/
public void removeByCode(String p_code, String p_clientId) {
final TokenLdap t = getGrantsByCodeAndClient(p_code, p_clientId);
if (t != null) {
removeSilently(t);
}
cacheService.remove(null, CacheGrant.cacheKey(p_clientId, p_code, null));
}
public void removeAllByAuthorizationCode(String p_authorizationCode) {
removeSilently(getGrantsByAuthorizationCode(p_authorizationCode));
}
public void removeAllByGrantId(String p_grantId) {
removeSilently(getGrantsByGrantId(p_grantId));
}
public void cleanUp() {
try {
cleanUpImpl();
} catch (EntryPersistenceException ex) {
log.error("Failed to process grant clean up properly", ex);
}
}
private void cleanUpImpl() {
// Cleaning oxAuthToken
BatchOperation<TokenLdap> tokenBatchService = new ProcessBatchOperation<TokenLdap>() {
@Override
public void performAction(List<TokenLdap> entries) {
auditLogging(entries);
remove(entries);
}
};
ldapEntryManager.findEntries(baseDn(), TokenLdap.class, getExpiredTokenFilter(), SearchScope.SUB, new String[]{"oxAuthTokenCode", "oxAuthClientId", "oxAuthScope", "oxAuthUserId"}, tokenBatchService, 0, 0, CleanerTimer.BATCH_SIZE);
// Cleaning oxAuthGrant
BatchOperation<Grant> grantBatchService = new ProcessBatchOperation<Grant>() {
@Override
public void performAction(List<Grant> entries) {
removeGrants(entries);
}
};
ldapEntryManager.findEntries(baseDn(), Grant.class, getExpiredGrantFilter(), SearchScope.SUB, new String[]{""}, grantBatchService, 0, 0, CleanerTimer.BATCH_SIZE);
// Cleaning old oxAuthGrant
// Note: This block should be removed, it is used only to delete old legacy data.
BatchOperation<Grant> oldGrantBatchService = new ProcessBatchOperation<Grant>() {
@Override
public void performAction(List<Grant> entries) {
removeGrants(entries);
}
};
ldapEntryManager.findEntries(baseDn(), Grant.class, getExpiredOldGrantFilter(), SearchScope.SUB, new String[]{""}, oldGrantBatchService, 0, 0, CleanerTimer.BATCH_SIZE);
}
private Filter getExpiredTokenFilter() {
return Filter.createLessOrEqualFilter("oxAuthExpiration", ldapEntryManager.encodeTime(new Date()));
}
private Filter getExpiredGrantFilter() {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND, 60);
Filter hasSubordinates = Filter.createORFilter(Filter.createEqualityFilter("numsubordinates", "0"),
Filter.createEqualityFilter("hasSubordinates", "FALSE"));
Filter creationDate = Filter.createLessOrEqualFilter("oxAuthCreation", ldapEntryManager.encodeTime(calendar.getTime()));
Filter filter = Filter.createANDFilter(creationDate, hasSubordinates);
return filter;
}
private Filter getExpiredOldGrantFilter() {
Filter hasSubordinatesFilter = Filter.createORFilter(Filter.createEqualityFilter("numsubordinates", "0"),
Filter.createEqualityFilter("hasSubordinates", "FALSE"));
Filter noCreationDate = Filter.createNOTFilter(Filter.createPresenceFilter("oxAuthCreation"));
Filter filter = Filter.createANDFilter(noCreationDate, hasSubordinatesFilter);
return filter;
}
private void addGrantBranch(final String p_grantId, final String p_clientId) {
Grant grant = new Grant();
grant.setDn(getBaseDnForGrant(p_grantId, p_clientId));
grant.setId(p_grantId);
grant.setCreationDate(new Date());
ldapEntryManager.persist(grant);
}
private void prepareGrantBranch(final String p_grantId, final String p_clientId) {
// Create ocAuthGrant branch if needed
if (!containsGrantBranch(p_grantId, p_clientId)) {
addGrantBranch(p_grantId, p_clientId);
}
}
private boolean containsGrantBranch(final String p_grantId, final String p_clientId) {
return ldapEntryManager.contains(Grant.class, getBaseDnForGrant(p_grantId, p_clientId));
}
private String getBaseDnForGrant(final String p_grantId, final String p_clientId) {
final StringBuilder dn = new StringBuilder();
dn.append(String.format("oxAuthGrantId=%s,", p_grantId));
dn.append(clientService.buildClientDn(p_clientId));
return dn.toString();
}
private void auditLogging(Collection<TokenLdap> entries) {
for (TokenLdap tokenLdap : entries) {
OAuth2AuditLog oAuth2AuditLog = new OAuth2AuditLog(null, Action.SESSION_DESTROYED);
oAuth2AuditLog.setSuccess(true);
oAuth2AuditLog.setClientId(tokenLdap.getClientId());
oAuth2AuditLog.setScope(tokenLdap.getScope());
oAuth2AuditLog.setUsername(tokenLdap.getUserId());
applicationAuditLogger.sendMessage(oAuth2AuditLog);
}
}
} |
package invtweaks.api;
import net.minecraft.item.ItemStack;
/**
* Interface to access functions exposed by Inventory Tweaks
*
* The main @Mod instance of the mod implements this interface, so a refernce to it can
* be obtained via @Instance("inventorytweaks") or methods in cpw.mods.fml.common.Loader
*
* All of these functions currently have no effect if called on a dedicated server.
*/
public interface InvTweaksAPI {
/**
* Add a listener for ItemTree load events
*
* @param listener
*/
void addOnLoadListener(IItemTreeListener listener);
/**
* Remove a listener for ItemTree load events
*
* @param listener
* @return true if the listener was previously added
*/
boolean removeOnLoadListener(IItemTreeListener listener);
/**
* Toggle sorting shortcut state.
*
* @param enabled
*/
void setSortKeyEnabled(boolean enabled);
/**
* Toggle sorting shortcut supression.
* Unlike setSortKeyEnabled, this flag is automatically cleared when GUIs are closed.
*
* @param enabled
*/
void setTextboxMode(boolean enabled);
/**
* Compare two items using the default (non-rule based) algorithm,
* sutable for an implementation of Comparator<ItemStack>.
*
* @param i
* @param j
* @return A value with a sign representing the relative order of the item stacks
*/
int compareItems(ItemStack i, ItemStack j);
} |
package ljdp.minechem.common;
import java.util.ArrayList;
import java.util.List;
import ljdp.minechem.api.core.EnumMolecule;
import ljdp.minechem.api.util.Constants;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.DamageSource;
import net.minecraft.world.World;
public class Pharm {
public static void triggerPlayerEffect(EnumMolecule molecule, EntityPlayer entityPlayer) {
World world = entityPlayer.worldObj;
// Mandrake's Realm
switch (molecule) {
case water:
entityPlayer.getFoodStats().addStats(1, .1F);
break;
case starch:
entityPlayer.getFoodStats().addStats(2, .2F);
break;
case stevenk:
entityPlayer.getFoodStats().addStats(2, .2F);
break;
case sucrose:
entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), Constants.TICKS_PER_SECOND * 5, 0));
entityPlayer.getFoodStats().addStats(1, .1F);
break;
case psilocybin:
entityPlayer.addPotionEffect(new PotionEffect(Potion.confusion.getId(), Constants.TICKS_PER_SECOND * 30, 5));
entityPlayer.attackEntityFrom(DamageSource.generic, 2);
entityPlayer.addPotionEffect(new PotionEffect(Potion.nightVision.getId(), Constants.TICKS_PER_SECOND * 30, 5));
break;
case amphetamine:
entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), Constants.TICKS_PER_SECOND * 20, 7));
break;
case methamphetamine:
entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), Constants.TICKS_PER_SECOND * 30, 7));
break;
case poison:
entityPlayer.addPotionEffect(new PotionEffect(Potion.wither.getId(), Constants.TICKS_PER_SECOND * 60, 2));
break;
case ethanol:
entityPlayer.addPotionEffect(new PotionEffect(Potion.confusion.getId(), Constants.TICKS_PER_SECOND * 10, 1));
entityPlayer.getFoodStats().addStats(3, .1F);
break;
case cyanide:
entityPlayer.addPotionEffect(new PotionEffect(Potion.wither.getId(), Constants.TICKS_PER_SECOND * 60, 5));
break;
case penicillin:
cureAllPotions(world, entityPlayer);
entityPlayer.addPotionEffect(new PotionEffect(Potion.regeneration.getId(), Constants.TICKS_PER_MINUTE * 2, 1));
break;
case testosterone:
entityPlayer.addPotionEffect(new PotionEffect(Potion.damageBoost.getId(), Constants.TICKS_PER_MINUTE * 5, 2));
entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), Constants.TICKS_PER_MINUTE * 5, 0));
entityPlayer.addPotionEffect(new PotionEffect(Potion.damageBoost.getId(), Constants.TICKS_PER_MINUTE * 5, 2));
break;
case xanax:
cureAllPotions(world, entityPlayer);
entityPlayer.addPotionEffect(new PotionEffect(Potion.confusion.getId(), Constants.TICKS_PER_SECOND * 30, 5));
entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSlowdown.getId(), Constants.TICKS_PER_SECOND * 30, 2));
break;
case pantherine:
entityPlayer.addPotionEffect(new PotionEffect(Potion.confusion.getId(), Constants.TICKS_PER_SECOND * 30, 5));
entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSlowdown.getId(), Constants.TICKS_PER_SECOND * 30, 2));
break;
case mescaline:
entityPlayer.attackEntityFrom(DamageSource.generic, 2);
entityPlayer.addPotionEffect(new PotionEffect(Potion.confusion.getId(), Constants.TICKS_PER_SECOND * 60, 2));
entityPlayer.addPotionEffect(new PotionEffect(Potion.blindness.getId(), Constants.TICKS_PER_SECOND * 30, 2));
break;
case asprin:
cureAllPotions(world, entityPlayer);
entityPlayer.addPotionEffect(new PotionEffect(Potion.regeneration.getId(), Constants.TICKS_PER_MINUTE * 1, 1));
break;
case shikimicAcid:
case salt:
// No effect.
break;
case phosgene:// all of these cause tons of damage to human flesh!!!!!
case aalc:
case sulfuricAcid:
case buli:
entityPlayer.attackEntityFrom(DamageSource.generic, 2);
entityPlayer.setFire(100);
break;
case ttx:
entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSlowdown.getId(), Constants.TICKS_PER_SECOND * 60, 10));
entityPlayer.addPotionEffect(new PotionEffect(Potion.wither.getId(), Constants.TICKS_PER_SECOND * 60, 1));
break;
case nicotine:
entityPlayer.attackEntityFrom(DamageSource.generic, 4);
entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSlowdown.getId(), Constants.TICKS_PER_SECOND * 60, 10));
break;
case fingolimod:
entityPlayer.addPotionEffect(new PotionEffect(Potion.damageBoost.getId(), Constants.TICKS_PER_MINUTE * 5, 2));
entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), Constants.TICKS_PER_MINUTE * 5, 2));
entityPlayer.addPotionEffect(new PotionEffect(Potion.regeneration.getId(), Constants.TICKS_PER_MINUTE * 5, 2));
entityPlayer.addPotionEffect(new PotionEffect(Potion.hunger.getId(), Constants.TICKS_PER_SECOND * 80, 1));
break;
case afroman: // CANNBINOID PAINKLLERS WOO!
cureAllPotions(world, entityPlayer);
entityPlayer.addPotionEffect(new PotionEffect(Potion.confusion.getId(), Constants.TICKS_PER_SECOND * 60, 5));
entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSlowdown.getId(), Constants.TICKS_PER_SECOND * 60, 4));
entityPlayer.addPotionEffect(new PotionEffect(Potion.hunger.getId(), Constants.TICKS_PER_SECOND * 120, 5));
break;
case nod:
entityPlayer.addPotionEffect(new PotionEffect(Potion.hunger.getId(), Constants.TICKS_PER_MINUTE * 8, 1));
break;
case hist:
cureAllPotions(world, entityPlayer);
entityPlayer.addPotionEffect(new PotionEffect(Potion.confusion.getId(), Constants.TICKS_PER_SECOND * 20, 5));
entityPlayer.getFoodStats().addStats(2, .2F);
break;
case pal2: // this sh*t is real nasty
entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSlowdown.getId(), Constants.TICKS_PER_SECOND * 60, 20));
entityPlayer.addPotionEffect(new PotionEffect(Potion.wither.getId(), Constants.TICKS_PER_SECOND * 60, 2));
entityPlayer.addPotionEffect(new PotionEffect(Potion.confusion.getId(), Constants.TICKS_PER_SECOND * 60, 2));
break;
case theobromine: // Speed boost
entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), Constants.TICKS_PER_MINUTE * 5, 1));
break;
case ret:
entityPlayer.addPotionEffect(new PotionEffect(Potion.nightVision.getId(), Constants.TICKS_PER_SECOND * 120, 1));
entityPlayer.getFoodStats().addStats(3, .1F);
break;
case glycine:
case alinine:
case serine:
case arginine:
entityPlayer.addPotionEffect(new PotionEffect(Potion.digSpeed.getId(), Constants.TICKS_PER_SECOND * 120, 1));
entityPlayer.addPotionEffect(new PotionEffect(Potion.jump.getId(), Constants.TICKS_PER_SECOND * 120, 1));
break;
case redrocks:
entityPlayer.addPotionEffect(new PotionEffect(Potion.confusion.getId(), Constants.TICKS_PER_SECOND * 120, 5));
entityPlayer.attackEntityFrom(DamageSource.generic, 2);
entityPlayer.addPotionEffect(new PotionEffect(Potion.nightVision.getId(), Constants.TICKS_PER_SECOND * 120, 5));
entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), Constants.TICKS_PER_SECOND * 120, 7));
break;
case coke:
entityPlayer.addPotionEffect(new PotionEffect(Potion.confusion.getId(), Constants.TICKS_PER_SECOND * 60, 5));
entityPlayer.attackEntityFrom(DamageSource.generic, 2);
entityPlayer.addPotionEffect(new PotionEffect(Potion.nightVision.getId(), Constants.TICKS_PER_SECOND * 60, 5));
entityPlayer.addPotionEffect(new PotionEffect(Potion.moveSpeed.getId(), Constants.TICKS_PER_SECOND * 60, 10));
break;
case metblue:
cureAllPotions(world, entityPlayer);
entityPlayer.addPotionEffect(new PotionEffect(Potion.regeneration.getId(), Constants.TICKS_PER_SECOND * 30, 2));
entityPlayer.addPotionEffect(new PotionEffect(Potion.weakness.getId(), Constants.TICKS_PER_SECOND * 30, 2));
break;
case meoh:
entityPlayer.addPotionEffect(new PotionEffect(Potion.blindness.getId(), Constants.TICKS_PER_SECOND * 60, 4));
entityPlayer.addPotionEffect(new PotionEffect(Potion.wither.getId(), Constants.TICKS_PER_SECOND * 60, 4));
break;
default:
entityPlayer.attackEntityFrom(DamageSource.generic, 5);
break;
}
}
public static void cureAllPotions(World world, EntityPlayer entityPlayer) {
List<PotionEffect> activePotions = new ArrayList<PotionEffect>(entityPlayer.getActivePotionEffects());
for (PotionEffect potionEffect : activePotions) {
entityPlayer.removePotionEffect(potionEffect.getPotionID());
}
}
} |
package multicast.search;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import multicast.ParameterSearch;
import multicast.ParameterSearchListener;
import multicast.search.message.GeneralizeSearchMessage;
import multicast.search.message.RemoteMessage;
import multicast.search.message.RemoteMulticastMessage;
import multicast.search.message.RemoveParametersMessage;
import multicast.search.message.RemoveRouteMessage;
import multicast.search.message.SearchMessage;
import multicast.search.message.SearchMessage.SearchType;
import multicast.search.message.SearchResponseMessage;
import multicast.search.unicastTable.UnicastTable;
import peer.BasicPeer;
import peer.CommunicationLayer;
import peer.Peer;
import peer.RegisterCommunicationLayerException;
import peer.conditionregister.ConditionRegister;
import peer.message.BroadcastMessage;
import peer.message.MessageID;
import peer.message.PayloadMessage;
import peer.peerid.PeerID;
import peer.peerid.PeerIDSet;
import taxonomy.parameter.Parameter;
import util.logger.Logger;
import config.Configuration;
import detection.NeighborEventsListener;
import dissemination.DistanceChange;
import dissemination.ParameterDisseminator;
import dissemination.TableChangedListener;
import dissemination.newProtocol.ParameterTableUpdater;
/**
* This class implements the parameter search layer. It includes methods for
* parameter search, remote messages sending unicast and multicast.
*
* @author Unai Aguilera (unai.aguilera@gmail.com)
*
*/
public class ParameterSearchImpl implements CommunicationLayer, NeighborEventsListener, TableChangedListener, ParameterSearch {
// reference to the lower layer
private final ParameterDisseminator pDisseminator;
// the communication peer
private final Peer peer;
// listener for parameter search events
private final ParameterSearchListener searchListener;
// delegated listener for parameter table changes
private final TableChangedListener tableChangedListener;
// A reference to the route table
private UnicastTable uTable;
// Configuration properties
private int MAX_TTL = 5; // Default value
private static class ReceivedMessageID {
private final MessageID remoteMessageID;
private final PeerID sender;
public ReceivedMessageID(final MessageID remoteMessageID, final PeerID sender) {
this.remoteMessageID = remoteMessageID;
this.sender = sender;
}
public PeerID getSender() {
return sender;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof ReceivedMessageID))
return false;
ReceivedMessageID receivedMessageID = (ReceivedMessageID)o;
return this.remoteMessageID.equals(receivedMessageID.remoteMessageID);
}
@Override
public int hashCode() {
return remoteMessageID.hashCode();
}
}
private final ConditionRegister<ReceivedMessageID> receivedMessages = new ConditionRegister<ReceivedMessageID>(BasicPeer.CLEAN_REC_MSGS);
private boolean enabled = true;
private final Logger logger = Logger.getLogger(ParameterSearchImpl.class);
/**
* Constructor of the parameter search.
*
* @param peer
* the communication peer
* @param searchListener
* the listener for search events
* @param tableChangedListener
* the listener for events related to table changes
*/
public ParameterSearchImpl(final Peer peer, final ParameterSearchListener searchListener, final TableChangedListener tableChangedListener) {
this.peer = peer;
this.tableChangedListener = tableChangedListener;
this.pDisseminator = new ParameterTableUpdater(peer, this, this);
this.searchListener = searchListener;
final Set<Class<? extends BroadcastMessage>> messageClasses = new HashSet<Class<? extends BroadcastMessage>>();
messageClasses.add(SearchMessage.class);
messageClasses.add(RemoteMulticastMessage.class);
messageClasses.add(SearchResponseMessage.class);
messageClasses.add(RemoveParametersMessage.class);
messageClasses.add(RemoveRouteMessage.class);
messageClasses.add(GeneralizeSearchMessage.class);
try {
peer.addCommunicationLayer(this, messageClasses);
} catch (final RegisterCommunicationLayerException rce) {
logger.error("Peer " + peer.getPeerID() + " had problem registering communication layer: " + rce.getMessage());
}
}
public void setDisabled() {
enabled = false;
}
/*
* (non-Javadoc)
*
* @see
* multicast.search.PSearch#addLocalParameter(taxonomy.parameter.Parameter)
*/
@Override
public boolean addLocalParameter(final Parameter parameter) {
return pDisseminator.addLocalParameter(parameter);
}
/*
* (non-Javadoc)
*
* @see
* multicast.search.PSearch#removeLocalParameter(taxonomy.parameter.Parameter
* )
*/
@Override
public boolean removeLocalParameter(final Parameter parameter) {
return pDisseminator.removeLocalParameter(parameter);
}
/*
* (non-Javadoc)
*
* @see multicast.search.PSearch#commit()
*/
@Override
public void commit() {
pDisseminator.commit();
}
@Override
public void appearedNeighbors(final PeerIDSet neighbors) {
repropagateSearches(neighbors);
}
@Override
public void dissapearedNeighbors(final PeerIDSet neighbors) {
for (ReceivedMessageID receivedMessageID : receivedMessages.getEntries()) {
if (neighbors.contains(receivedMessageID.getSender())) {
logger.trace("Peer " + peer.getPeerID() + " removing all messages received from neighbor " + receivedMessageID.getSender());
receivedMessages.remove(receivedMessageID);
}
}
final Set<MessageID> lostRoutes = new HashSet<MessageID>();
synchronized (uTable) {
for (final PeerID neighbor : neighbors)
lostRoutes.addAll(uTable.getRoutesThrough(neighbor));
}
sendRemoveRouteMessage(lostRoutes);
}
private void repropagateSearches(final PeerIDSet neighbors) {
// Active searches are resent to new nodes
logger.trace("Peer " + peer.getPeerID() + " propagating searches for new neighbors " + neighbors);
synchronized (uTable) {
for (final SearchMessage searchMessage : uTable.getActiveSearches())
propagateSearchMessage(searchMessage);
}
}
@Override
public PayloadMessage parametersChanged(final PeerID neighbor, final Set<Parameter> addedParameters, final Set<Parameter> removedParameters, final Set<Parameter> removedLocalParameters, final Map<Parameter, DistanceChange> changedParameters, final PayloadMessage payload) {
// Check if the added parameters are local
final Set<Parameter> localAddedParameters = new HashSet<Parameter>();
final Set<Parameter> nonLocalAddedParameters = new HashSet<Parameter>();
for (final Parameter addedParameter : addedParameters)
// Check if parameter is local
if (pDisseminator.isLocalParameter(addedParameter))
localAddedParameters.add(addedParameter);
else
nonLocalAddedParameters.add(addedParameter);
if (!localAddedParameters.isEmpty())
processLocalAddedParameters(localAddedParameters);
if (!nonLocalAddedParameters.isEmpty())
processNonLocalAddedParameters(nonLocalAddedParameters);
if (!removedLocalParameters.isEmpty())
processLocalRemovedParameters(removedLocalParameters);
return tableChangedListener.parametersChanged(neighbor, addedParameters, removedParameters, removedLocalParameters, changedParameters, payload);
}
/*
* (non-Javadoc)
*
* @see multicast.search.PSearch#sendCancelSearchMessage(java.util.Set)
*/
@Override
public void sendCancelSearchMessage(final Set<Parameter> parameters) {
if (!enabled)
return;
logger.debug("Peer " + peer.getPeerID() + " canceling searches for parameters " + parameters);
final Map<MessageID, Set<Parameter>> removedParameters = new HashMap<MessageID, Set<Parameter>>();
synchronized (uTable) {
for (final Parameter removedParameter : parameters) {
final Set<SearchMessage> activeSearches = uTable.getActiveSearches(removedParameter, peer.getPeerID());
if (!activeSearches.isEmpty()) {
for (SearchMessage searchMessage : activeSearches) {
MessageID routeID = searchMessage.getRemoteMessageID();
if (!removedParameters.containsKey(routeID))
removedParameters.put(routeID, new HashSet<Parameter>());
removedParameters.get(routeID).add(removedParameter);
}
}
}
}
sendRemoveParametersMessage(removedParameters);
}
/*
* (non-Javadoc)
*
* @see multicast.search.PSearch#sendGeneralizeSearchMessage(java.util.Set)
*/
@Override
public void sendGeneralizeSearchMessage(final Set<Parameter> generalizedParameters) {
if (!enabled)
return;
logger.debug("Peer " + peer.getPeerID() + " enqueuing generalize search for parameters " + generalizedParameters);
final Set<MessageID> routeIDs = new HashSet<MessageID>();
synchronized (uTable) {
for (final Parameter generalizedParameter : generalizedParameters) {
final Set<SearchMessage> activeSearches = uTable.getSubsumedActiveSearches(generalizedParameter, peer.getPeerID(), pDisseminator.getTaxonomy());
for (final SearchMessage activeSearch : activeSearches) {
if (activeSearch.getSearchType().equals(SearchType.Generic))
routeIDs.add(activeSearch.getRemoteMessageID());
}
}
}
logger.trace("Peer " + peer.getPeerID() + " generalizing searches " + routeIDs + " with parameters " + generalizedParameters);
sendGeneralizeSearchMessage(generalizedParameters, routeIDs);
}
private void processLocalRemovedParameters(final Set<Parameter> localRemovedParameters) {
final Map<MessageID, Set<Parameter>> removedParameters = new HashMap<MessageID, Set<Parameter>>();
synchronized (uTable) {
for (final Parameter removedParameter : localRemovedParameters) {
Set<MessageID> affectedRoutes = uTable.getLocalParameterRoutes(removedParameter);
if (!affectedRoutes.isEmpty()) {
for (MessageID routeID : affectedRoutes) {
if (!removedParameters.containsKey(routeID))
removedParameters.put(routeID, new HashSet<Parameter>());
removedParameters.get(routeID).add(removedParameter);
}
}
}
}
sendRemoveParametersMessage(removedParameters);
}
private void processLocalAddedParameters(final Set<Parameter> localAddedParameters) {
final Map<SearchMessage, Set<Parameter>> parametersTable = new HashMap<SearchMessage, Set<Parameter>>();
synchronized (uTable) {
for (final Parameter localParameter : localAddedParameters) {
// Get active searches searching for this parameter
final Set<SearchMessage> activeSearches = uTable.getActiveSearches(localParameter);
for (final SearchMessage activeSearch : activeSearches) {
if (!parametersTable.containsKey(activeSearch))
parametersTable.put(activeSearch, new HashSet<Parameter>());
parametersTable.get(activeSearch).add(localParameter);
}
}
}
// Notify peers with search response messages
for (final Entry<SearchMessage, Set<Parameter>> entry : parametersTable.entrySet()) {
final SearchMessage searchMessage = entry.getKey();
logger.trace("Peer " + peer.getPeerID() + " enqueued search message action" + searchMessage);
sendSearchResponseMessage(searchMessage.getSource(), entry.getValue(), null, searchMessage.getRemoteMessageID());
}
}
private void processNonLocalAddedParameters(final Set<Parameter> nonLocalAddedParameters) {
final Set<SearchMessage> propagatedSearches = new HashSet<SearchMessage>();
// Find all active searches containing the added parameters
List<SearchMessage> searchMessages = new ArrayList<SearchMessage>();
synchronized (uTable) {
searchMessages.addAll(uTable.getActiveSearches());
}
for (final SearchMessage searchMessage : searchMessages) {
final Set<Parameter> searchedParameters = new HashSet<Parameter>(searchMessage.getSearchedParameters());
// Get the intersection
searchedParameters.retainAll(nonLocalAddedParameters);
if (!searchedParameters.isEmpty())
propagatedSearches.add(searchMessage);
}
// Propagate all searches
for (final SearchMessage searchMessage : propagatedSearches)
propagateSearchMessage(searchMessage);
}
/*
* (non-Javadoc)
*
* @see multicast.search.PSearch#getDisseminationLayer()
*/
@Override
public ParameterDisseminator getDisseminationLayer() {
return pDisseminator;
}
@Override
public void init() {
try {
// Configure internal properties
final String maxTTL = Configuration.getInstance().getProperty("parameterSearch.searchMessageTTL");
MAX_TTL = Integer.parseInt(maxTTL);
logger.info("Peer " + peer.getPeerID() + " set MAX_TTL " + MAX_TTL);
} catch (final Exception e) {
logger.error("Peer " + peer.getPeerID() + " had problem loading configuration: " + e.getMessage());
}
uTable = new UnicastTable(peer.getPeerID());
receivedMessages.start();
}
@Override
public void messageReceived(final BroadcastMessage message, final long receptionTime) {
if (!enabled)
return;
// check that message was not previously received
RemoteMessage remoteMessage = ((RemoteMessage) message);
if (receivedMessages.contains(new ReceivedMessageID(remoteMessage.getRemoteMessageID(), remoteMessage.getSender())))
return;
receivedMessages.addEntry((new ReceivedMessageID(remoteMessage.getRemoteMessageID(), remoteMessage.getSender())));
if (message instanceof SearchMessage)
processSearchMessage((SearchMessage) message);
else if (message instanceof RemoteMulticastMessage) {
processMulticastMessage((RemoteMulticastMessage) message);
} else if (message instanceof RemoveRouteMessage)
processRemoveRouteMessage((RemoveRouteMessage) message);
else if (message instanceof RemoveParametersMessage)
processRemoveParametersMessage((RemoveParametersMessage) message);
else if (message instanceof GeneralizeSearchMessage)
processGeneralizeSearchMessage((GeneralizeSearchMessage) message);
}
// sends a remote multicast message. This message is routed to multiple
// remote destinations.
/*
* (non-Javadoc)
*
* @see multicast.search.PSearch#sendMulticastMessage(peer.PeerIDSet,
* message.BroadcastMessage)
*/
@Override
public void sendMulticastMessage(final PeerIDSet destinations, final PayloadMessage payload) {
if (!enabled)
return;
final RemoteMulticastMessage msg = new RemoteMulticastMessage(destinations, payload, peer.getPeerID());
final String payloadType = (payload == null)?"null":payload.getType();
logger.debug("Peer " + peer.getPeerID() + " sending remote multicast message " + msg + " with payload type of " + payloadType + " to " + destinations);
messageReceived(msg, System.currentTimeMillis());
}
/*
* (non-Javadoc)
*
* @see multicast.search.PSearch#sendUnicastMessage(peer.PeerID,
* message.BroadcastMessage)
*/
@Override
public void sendUnicastMessage(final PeerID destination, final PayloadMessage payload) {
if (!enabled)
return;
final RemoteMulticastMessage msg = new RemoteMulticastMessage(new PeerIDSet(Collections.singleton(destination)), payload, peer.getPeerID());
logger.debug("Peer " + peer.getPeerID() + " sending remote unicast message " + msg + " to " + destination);
messageReceived(msg, System.currentTimeMillis());
}
/*
* (non-Javadoc)
*
* @see multicast.search.PSearch#knowsSearchRouteTo(peer.PeerID)
*/
@Override
public boolean knowsSearchRouteTo(final PeerID dest) {
synchronized (uTable) {
return uTable.knowsSearchRouteTo(dest);
}
}
@Override
public boolean knowsRouteTo(final PeerID dest) {
synchronized (uTable) {
return uTable.knowsRouteTo(dest);
}
}
@Override
public int getDistanceTo(final PeerID peerID) {
synchronized (uTable) {
return uTable.getDistanceTo(peerID);
}
}
@Override
public void stop() {
receivedMessages.stopAndWait();
}
private void acceptMulticastMessage(final RemoteMulticastMessage multicastMessage) {
logger.trace("Peer " + peer.getPeerID() + " accepted multicast message " + multicastMessage);
final PayloadMessage payload = multicastMessage.getPayload();
searchListener.multicastMessageAccepted(multicastMessage.getSource(), payload.copy(), multicastMessage.getDistance());
}
// this method is called when a search message is accepted by the current
// node
private void acceptSearchMessage(final SearchMessage searchMessage, final Set<Parameter> foundParameters) {
logger.trace("Peer " + peer.getPeerID() + " accepted search message " + searchMessage);
logger.debug("Peer " + peer.getPeerID() + " accepted " + searchMessage.getType() + " " + searchMessage.getMessageID());
// Call listener and get user response payload
final PayloadMessage response = searchListener.searchMessageReceived(searchMessage);
// Send response to source node including payload
sendSearchResponseMessage(searchMessage.getSource(), foundParameters, response, searchMessage.getRemoteMessageID());
}
private void acceptSearchResponseMessage(final SearchResponseMessage searchResponseMessage) {
logger.debug("Peer " + peer.getPeerID() + " found parameters " + searchResponseMessage.getParameters() + " in node " + searchResponseMessage.getSource() + " searchID " + searchResponseMessage.getRespondedRouteID());
searchListener.parametersFound(searchResponseMessage);
}
private int getNewDistance(final RemoteMessage remoteMessage) {
return remoteMessage.getDistance() + 1;
}
// process the multicast messages in the current node
private void processMulticastMessage(final RemoteMulticastMessage multicastMessage) {
logger.trace("Peer " + peer.getPeerID() + " processing multicast message " + multicastMessage);
// Check if the current peer is valid to pass through the multicast
// message
if (!multicastMessage.getThroughPeers().contains(peer.getPeerID()))
return;
synchronized (uTable) {
// Update route table if message contains route information
if (multicastMessage instanceof SearchResponseMessage)
uTable.updateUnicastTable((SearchResponseMessage) multicastMessage);
}
// Check if message must be accepted
boolean messageAccepted = false;
if (multicastMessage.getRemoteDestinations().contains(peer.getPeerID())) {
messageAccepted = true;
if (multicastMessage instanceof SearchResponseMessage) {
acceptSearchResponseMessage((SearchResponseMessage) multicastMessage);
return;
}
// Remove current destination from destination list
multicastMessage.removeRemoteDestination(peer.getPeerID());
}
// Remove invalid destinations. A destination is invalid if cannot be
// reached from current peer according to route table
synchronized (uTable) {
for (final PeerID destination : multicastMessage.getRemoteDestinations())
if (!uTable.knowsRouteTo(destination))
multicastMessage.removeRemoteDestination(destination);
}
// Check if more destinations are available after purging invalid ones
if (!multicastMessage.getRemoteDestinations().isEmpty()) {
// Get the new list of neighbors used to send the message
final PeerIDSet throughPeers = new PeerIDSet();
synchronized (uTable) {
for (final PeerID destination : multicastMessage.getRemoteDestinations()) {
final PeerID through = uTable.getNeighbor(destination);
throughPeers.addPeer(through);
}
}
if (multicastMessage instanceof SearchResponseMessage) {
final SearchResponseMessage newSearchResponseMessage = new SearchResponseMessage((SearchResponseMessage) multicastMessage, peer.getPeerID(), throughPeers.iterator().next(), getNewDistance(multicastMessage));
logger.trace("Peer " + peer.getPeerID() + " multicasting search response " + newSearchResponseMessage);
peer.enqueueBroadcast(newSearchResponseMessage);
} else {
final RemoteMulticastMessage newRemoteMulticastMessage = new RemoteMulticastMessage(multicastMessage, peer.getPeerID(), throughPeers, getNewDistance(multicastMessage));
logger.trace("Peer " + peer.getPeerID() + " multicasting message " + newRemoteMulticastMessage);
peer.enqueueBroadcast(newRemoteMulticastMessage);
}
} else
logger.trace("Peer " + peer.getPeerID() + " discarded multicast message " + multicastMessage + ". No more valid destinations.");
// Finally accept message by current node if needed
if (messageAccepted)
acceptMulticastMessage(multicastMessage);
}
private void processRemoveParametersMessage(final RemoveParametersMessage removeParametersMessage) {
logger.trace("Peer " + peer.getPeerID() + " processing remove parameters message " + removeParametersMessage);
final Set<MessageID> removedSearchRoutes = new HashSet<MessageID>();
final Set<MessageID> removedParameterRoutes = new HashSet<MessageID>();
final Map<MessageID, Set<Parameter>> lostParameters = new HashMap<MessageID, Set<Parameter>>();
final Map<MessageID, Set<Parameter>> canceledParameterSearch = new HashMap<MessageID, Set<Parameter>>();
boolean notify = false;
synchronized (uTable) {
Map<MessageID, Set<Parameter>> removedParameters = removeParametersMessage.getRemovedParameters();
for (final Iterator<MessageID> it = removedParameters.keySet().iterator(); it.hasNext(); ) {
final MessageID routeID = it.next();
final boolean searchRoute = uTable.isSearchRoute(routeID);
final boolean existed = uTable.isRoute(routeID);
final Set<Parameter> reallyRemovedParameters = uTable.removeParameters(removedParameters.get(routeID), routeID);
logger.trace("Peer " + peer.getPeerID() + " removed parameters " + reallyRemovedParameters + " from route " + routeID);
// If parameters were removed notify listeners and neighbors
if (!reallyRemovedParameters.isEmpty()) {
if (searchRoute)
canceledParameterSearch.put(routeID, reallyRemovedParameters);
else {
// notify only parameters which are currently searched
reallyRemovedParameters.retainAll(uTable.getSearchedParameters());
if (!reallyRemovedParameters.isEmpty())
lostParameters.put(routeID, reallyRemovedParameters);
}
// Check if route was completely removed
if (existed && !uTable.isRoute(routeID)) {
if (searchRoute)
removedSearchRoutes.add(routeID);
else
removedParameterRoutes.add(routeID);
}
notify = true;
} else {
//remove route
it.remove();
}
}
}
if (notify) {
notifyRouteListeners(removeParametersMessage.getSource(), removedSearchRoutes, removedParameterRoutes, lostParameters, canceledParameterSearch);
final RemoveParametersMessage newRemoveParametersMessage = new RemoveParametersMessage(removeParametersMessage, peer.getPeerID(), getNewDistance(removeParametersMessage));
logger.trace("Peer " + peer.getPeerID() + " sending remove parameters message " + newRemoveParametersMessage);
peer.enqueueBroadcast(newRemoveParametersMessage);
}
}
private void notifyRouteListeners(final PeerID source, final Set<MessageID> removedSearchRoutes, final Set<MessageID> removedParameterRoutes, final Map<MessageID, Set<Parameter>> lostParameters, final Map<MessageID, Set<Parameter>> canceledParameterSearch) {
if (!lostParameters.isEmpty()) {
logger.debug("Peer " + peer.getPeerID() + " lost parameters " + lostParameters + " in node " + source);
logger.trace("Peer " + peer.getPeerID() + " removedParameterRoutes " + removedParameterRoutes);
searchListener.changedParameterRoutes(lostParameters, removedParameterRoutes);
}
if (!canceledParameterSearch.isEmpty()) {
logger.trace("Peer " + peer.getPeerID() + " canceledParameterSearch " + canceledParameterSearch);
logger.trace("Peer " + peer.getPeerID() + " removedSearchRoutes " + removedSearchRoutes);
searchListener.changedSearchRoutes(canceledParameterSearch, removedSearchRoutes);
}
}
private void processGeneralizeSearchMessage(final GeneralizeSearchMessage generalizeSearchMessage) {
logger.trace("Peer " + peer.getPeerID() + " processing generalize search message " + generalizeSearchMessage);
boolean notifyNeighbors = false;
synchronized (uTable) {
for (final MessageID routeID : generalizeSearchMessage.getRouteIDs()) {
final Map<Parameter, Parameter> generalizations = uTable.generalizeSearch(generalizeSearchMessage.getParameters(), routeID, pDisseminator.getTaxonomy());
// If parameters were affected, propagate message
if (!generalizations.isEmpty()) {
notifyNeighbors = true;
// Send response messages for those parameters not previously
// responded
// Check if the peer provides any of the new searched parameters
final Set<Parameter> foundParameters = new HashSet<Parameter>();
for (final Parameter p : generalizations.values()) {
final Set<Parameter> subsumedParameters = pDisseminator.subsumesLocalParameter(p);
foundParameters.addAll(subsumedParameters);
}
// However remove all those parameters which already found with
// the previous parameter values
for (final Parameter p : generalizations.keySet()) {
final Set<Parameter> subsumedParameters = pDisseminator.subsumesLocalParameter(p);
foundParameters.removeAll(subsumedParameters);
}
// Notify new found parameters
if (!foundParameters.isEmpty()) {
final SearchMessage searchMessage = uTable.getActiveSearch(routeID);
acceptSearchMessage(searchMessage, foundParameters);
}
}
}
}
if (notifyNeighbors) {
final GeneralizeSearchMessage newGeneralizeSearchMessage = new GeneralizeSearchMessage(generalizeSearchMessage, peer.getPeerID(), getNewDistance(generalizeSearchMessage));
logger.trace("Peer " + peer.getPeerID() + " sending generalize search message " + newGeneralizeSearchMessage);
peer.enqueueBroadcast(newGeneralizeSearchMessage);
logger.trace("Peer " + peer.getPeerID() + " sent generalize search message " + newGeneralizeSearchMessage);
}
}
// Processes a remove route message
private void processRemoveRouteMessage(final RemoveRouteMessage removeRouteMessage) {
logger.trace("Peer " + peer.getPeerID() + " processing remove route message " + removeRouteMessage);
final Map<MessageID, Set<Parameter>> lostParameters = new HashMap<MessageID, Set<Parameter>>();
final Map<MessageID, Set<Parameter>> canceledParameterSearch = new HashMap<MessageID, Set<Parameter>>();
final Set<MessageID> removedParameterRoutes = new HashSet<MessageID>();
final Set<MessageID> removedSearchRoutes = new HashSet<MessageID>();
boolean notify = false;
boolean repropagateSearches = false;
logger.trace("Peer " + peer.getPeerID() + " unicast table before removal: " + uTable);
synchronized (uTable) {
for (final MessageID routeID : removeRouteMessage.getLostRoutes()) {
if (uTable.isSearchRoute(routeID)) {
final Set<Parameter> canceledParameters = uTable.getSearchedParameters(routeID);
final PeerID lostDestination = uTable.removeRoute(routeID, removeRouteMessage.getSender());
if (!lostDestination.equals(PeerID.VOID_PEERID)) {
//removing of search parameters produces
canceledParameterSearch.put(routeID, canceledParameters);
removedSearchRoutes.add(routeID);
notify = true;
repropagateSearches = true;
}
} else {
final Set<Parameter> removedParameters = uTable.getParameters(routeID);
final PeerID lostDestination = uTable.removeRoute(routeID, removeRouteMessage.getSender());
if (!lostDestination.equals(PeerID.VOID_PEERID)) {
removedParameters.retainAll(uTable.getSearchedParameters());
// get the search route associated with this route
if (!removedParameters.isEmpty())
lostParameters.put(routeID, removedParameters);
removedParameterRoutes.add(routeID);
notify = true;
}
}
}
}
logger.trace("Peer " + peer.getPeerID() + " unicast table after removal: " + uTable);
if (removeRouteMessage.mustRepropagateSearches()) {
// Propagate current active searches
repropagateSearches(peer.getDetector().getCurrentNeighbors());
}
if (notify)
notifyRouteListeners(removeRouteMessage.getSource(), removedSearchRoutes, removedParameterRoutes, lostParameters, canceledParameterSearch);
if (notify || repropagateSearches) {
final Set<MessageID> lostRoutes = new HashSet<MessageID>();
lostRoutes.addAll(removedSearchRoutes);
lostRoutes.addAll(removedParameterRoutes);
final RemoveRouteMessage newRemoveRouteMessage = new RemoveRouteMessage(removeRouteMessage, peer.getPeerID(), lostRoutes, repropagateSearches, getNewDistance(removeRouteMessage));
logger.trace("Peer " + peer.getPeerID() + " sending remove route message " + newRemoveRouteMessage);
peer.enqueueBroadcast(newRemoveRouteMessage);
}
}
private void processSearchMessage(final SearchMessage searchMessage) {
logger.trace("Peer " + peer.getPeerID() + " processing search message " + searchMessage);
// Update route table with the information contained in the message
boolean updated;
synchronized (uTable) {
updated = uTable.updateUnicastTable(searchMessage);
}
if (updated) {
// If the current peer provides any of the searched parameters
// accept the message
final Set<Parameter> foundParameters = new HashSet<Parameter>();
for (final Parameter p : searchMessage.getSearchedParameters())
if (searchMessage.getSearchType().equals(SearchType.Exact)) {
if (pDisseminator.isLocalParameter(p))
foundParameters.add(p);
} else if (searchMessage.getSearchType().equals(SearchType.Generic)) {
final Set<Parameter> subsumedParameters = pDisseminator.subsumesLocalParameter(p);
foundParameters.addAll(subsumedParameters);
}
if (!foundParameters.isEmpty())
acceptSearchMessage(searchMessage, foundParameters);
propagateSearchMessage(searchMessage);
}
}
// Sends a message which searches for specified parameters
/*
* (non-Javadoc)
*
* @see multicast.search.PSearch#sendSearchMessage(java.util.Set,
* message.BroadcastMessage,
* multicast.search.message.SearchMessage.SearchType)
*/
@Override
public void sendSearchMessage(final Set<Parameter> parameters, final PayloadMessage payload, final SearchType searchType) {
if (!enabled)
return;
final SearchMessage searchMessage = new SearchMessage(parameters, payload, peer.getPeerID(), MAX_TTL, 0, searchType);
final String payloadType = (payload == null)?"null":payload.getType();
logger.debug("Peer " + peer.getPeerID() + " started search for parameters " + parameters + " searchID " + searchMessage.getRemoteMessageID() + " with payload type of " + payloadType);
logger.trace("Peer " + peer.getPeerID() + " searching parameters with message " + searchMessage);
messageReceived(searchMessage, System.currentTimeMillis());
}
// Sends a message which generalizes the specified parameters
private void sendRemoveParametersMessage(final Map<MessageID, Set<Parameter>> removedParameters) {
if (!enabled)
return;
final RemoveParametersMessage removeParametersMessage = new RemoveParametersMessage(removedParameters, peer.getPeerID());
messageReceived(removeParametersMessage, System.currentTimeMillis());
}
private void sendGeneralizeSearchMessage(final Set<Parameter> parameters, final Set<MessageID> routeIDs) {
if (!enabled)
return;
final GeneralizeSearchMessage generalizeSearchMessage = new GeneralizeSearchMessage(parameters, routeIDs, peer.getPeerID());
messageReceived(generalizeSearchMessage, System.currentTimeMillis());
}
// sends a search response message to a the specified destination,
// indicating that the following parameters have been found
private void sendSearchResponseMessage(final PeerID destination, final Set<Parameter> parameters, final PayloadMessage payload, final MessageID respondedRouteID) {
if (!enabled)
return;
final SearchResponseMessage searchResponseMessage = new SearchResponseMessage(destination, parameters, payload, peer.getPeerID(), respondedRouteID);
logger.trace("Peer " + peer.getPeerID() + " sending search response message " + searchResponseMessage);
final String payloadType = (payload == null)?"null":payload.getType();
logger.debug("Peer " + peer.getPeerID() + " sending response message to search " + searchResponseMessage.getRespondedRouteID() + " with payload type of " + payloadType);
messageReceived(searchResponseMessage, System.currentTimeMillis());
}
// sends a remove route message
private void sendRemoveRouteMessage(final Set<MessageID> lostRoutes) {
if (!enabled)
return;
final RemoveRouteMessage removeRouteMessage = new RemoveRouteMessage(peer.getPeerID(), lostRoutes, false);
messageReceived(removeRouteMessage, System.currentTimeMillis());
}
// Called when search is a propagated search
private void propagateSearchMessage(final SearchMessage searchMessage) {
logger.trace("Peer " + peer.getPeerID() + " propagating search " + searchMessage);
// Create a copy of the message for broadcasting using the current node
// as the new sender. This message responds to the received one
final SearchMessage newMsg = new SearchMessage(searchMessage, peer.getPeerID(), getNewDistance(searchMessage));
for (final Parameter p : searchMessage.getSearchedParameters()) {
final int tableDistance = pDisseminator.getEstimatedDistance(p);
final int previousDistance = searchMessage.getPreviousDistance(p);
if (previousDistance <= tableDistance && !(previousDistance == 0 && tableDistance == 0)) {
// The message is getting closer to a parameter. TTL is restored
newMsg.restoreTTL(p, MAX_TTL);
logger.trace("Peer " + peer.getPeerID() + " restored message " + newMsg + " TTL. Parameter " + p + " going from " + previousDistance + " to " + tableDistance);
} else // The message is getting farer (or there is no information)
// from the parameter and the message was not received from the
// current node
if (!searchMessage.getSource().equals(peer.getPeerID())) {
newMsg.decTTL(p);
logger.trace("Peer " + peer.getPeerID() + " decremented TTL of message " + newMsg + " to " + newMsg.getTTL(p) + ". Parameter " + p + " going from " + previousDistance + " to " + tableDistance);
}
// Set the message parameter distance as known by the current node
// table.
newMsg.setCurrentDistance(p, tableDistance);
}
// If the message TTL is greater than zero message is sent, else it is
// thrown
if (newMsg.hasTTL()) {
peer.enqueueBroadcast(newMsg);
logger.trace("Peer " + peer.getPeerID() + " enqueued search message " + newMsg);
return;
}
logger.trace("Peer " + peer.getPeerID() + " has thrown message " + newMsg + " due TTL");
}
@Override
public void saveToXML(final OutputStream os) throws IOException {
synchronized (uTable) {
uTable.saveToXML(os);
}
}
@Override
public void readFromXML(final InputStream is) throws IOException {
}
} |
package net.AllGamer.AGBS;
import java.util.logging.Logger;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.player.PlayerEvent;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.util.config.Configuration;
/*
* Handle events for all Player related events
* @author AllGamer
*/
public class AGBSPlayerListener extends PlayerListener
{
@SuppressWarnings("unused")
private final AGBS plugin;
private final Logger log = Logger.getLogger("Minecraft");
public AGBSPlayerListener(AGBS instance)
{
plugin = instance;
}
//ONLY ADD LOGIN STUFF HERE
public void onPlayerLogin(PlayerLoginEvent event)
{
Player player = event.getPlayer();
AGBS.configBan.load();
String[] x = AGBS.configBan.getString("banned").split(",");
String bannedPlayers = AGBS.make(x, 0);
if (bannedPlayers.contains(player.getDisplayName().toLowerCase()))
{
event.disallow(PlayerLoginEvent.Result.KICK_FULL, "You are banned from this server!");
}
}
} |
/*
* TOPMUtils
*/
package net.maizegenetics.gbs.maps;
import java.io.File;
import net.maizegenetics.util.Utils;
/**
*
* @author terry
*/
public class TOPMUtils {
private TOPMUtils() {
// Utility
}
/**
* This reads in a TOPM file. It can be .topm.txt, .topm.bin, or .topm.h5.
*
* @param filename filename
*
* @return TOPM
*/
public static TOPMInterface readTOPM(String filename) {
String temp = filename.trim().toLowerCase();
if (temp.endsWith(".topm.txt")) {
return new TagsOnPhysicalMap(filename, false);
} else if (temp.endsWith(".topm.bin")) {
return new TagsOnPhysicalMap(filename, true);
} else if (temp.endsWith(".topm.h5")) {
return new TagsOnPhysMapHDF5(filename);
} else {
throw new IllegalArgumentException("TOPMUtils: readTOPM: Unknown file extension: " + filename);
}
}
public static void writeTOPM(TOPMInterface topm, String filename) {
filename = Utils.addSuffixIfNeeded(filename, ".topm.h5", new String[]{".topm.bin", ".topm.txt", ".topm.h5"});
String temp = filename.trim().toLowerCase();
if ((topm instanceof TagsOnPhysicalMap) && (temp.endsWith(".topm.bin"))) {
((TagsOnPhysicalMap) topm).writeBinaryFile(new File(filename));
} else if ((topm instanceof TagsOnPhysicalMap) && (temp.endsWith(".topm.txt"))) {
((TagsOnPhysicalMap) topm).writeTextFile(new File(filename));
} else if ((topm instanceof TagsOnPhysicalMap) && (temp.endsWith(".topm.h5"))) {
TagsOnPhysMapHDF5.createFile((TagsOnPhysicalMap) topm, filename, 1, topm.getMaxNumVariants());
} else {
// TBD
}
}
} |
package net.maizegenetics.gwas.NAM;
import java.io.File;
public class FileNames {
public File snps = null;
public File chrmodel = null;
public File chrsteps = null;
public File model = null;
public File steps = null;
public File residuals = null;
public File agpmap = null;
public File namMarkersByChr = null;
public File namMarkers = null;
public File phenotypes = null;
public File projectedFile = null;
public double enterlimit = 1e-6;
public double exitlimit = 2e-6;
public double[] limits = null;
public int traitnumber = -1;
public int iterations = 100;
public String replacement;
public String analysis = "";
public int maxsnps = 1000;
public boolean threaded = false;
public boolean permute = false;
public boolean bootstrapPermutation = false;
public boolean randomizeSnpOrder = false;
public boolean fullModel = false;
public int startIteration = 1;
public int chromosome = 0;
} |
package nodes.modifiers;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.util.ArrayList;
import java.util.Set;
import processing.core.PApplet;
import controlP5.CallbackEvent;
import controlP5.CallbackListener;
import controlP5.ControlKey;
import controlP5.ControlP5;
import controlP5.Textfield;
import nodes.Graph;
import nodes.Modifier;
import nodes.Node;
import nodes.Selection;
/**
* @author Karim
*
* Modifier for selecting a list of nodes that share a common number of nodes specified by the user
* via a popup window
*/
public class NeighbourNodesFinder extends Modifier {
/**
* @param graph
*/
public NeighbourNodesFinder(Graph graph) {
super(graph);
}
@Override
public boolean isCompatible() {
return graph.nodeCount() > 0;
}
@Override
public String getTitle() {
return "Find nodes with common neighbours";
}
@Override
public void modify() {
FinderFrame f = new FinderFrame(this);
try {
synchronized (this) {
this.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
int num = f.getNeighboursSelection();
f.close();
if (num <= 0)
return;
Selection sele = graph.getSelection();
sele.clearBuffer();
sele.clear();
Set<Node> nodes = graph.getNodes();
for (Node i : nodes) {
for (Node j : nodes) {
if (i == j)
continue;
ArrayList<Node> nbrs = graph.getCommonNbrs(i, j);
if (nbrs.size() == num) {
if (!sele.contains(i))
sele.addToBuffer(i);
if (!sele.contains(j))
sele.addToBuffer(j);
}
}
}
sele.commitBuffer();
}
/*
* Mostly taken from TripleChoserFrame by kdbanman
*/
private class FinderFrame extends Frame {
private static final long serialVersionUID = -5963247227145726367L;
int neighbours;
int frameW, frameH;
Object waiting;
FinderWindow finder;
public FinderFrame(Object waitingObj) {
super("choose a number");
frameW = 300;
frameH = 80;
waiting = waitingObj;
setLayout(new BorderLayout());
setSize(frameW, frameH);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
finder = new FinderWindow();
add(finder, BorderLayout.CENTER);
validate();
finder.init();
}
public int getNeighboursSelection() {
return neighbours;
}
public void setNeighboursSelection(int neighbours) {
this.neighbours = neighbours;
}
public void close() {
finder.stop();
dispose();
}
private class FinderWindow extends PApplet {
private static final long serialVersionUID = 982758246505135143L;
ControlP5 cp5;
Textfield nBox;
public FinderWindow() {}
@Override
public void setup() {
size(frameW, frameH);
cp5 = new ControlP5(this);
nBox = cp5.addTextfield("number of neighbours")
.setPosition(20, 20).setSize(100, 14)
.setInputFilter(ControlP5.INTEGER).setText("1");
setNeighboursSelection(1);
cp5.addButton("FIND NODES").setPosition(200, 20)
.setSize(70, 14).addCallback(new CallbackListener() {
@Override
public void controlEvent(CallbackEvent event) {
if (event.getAction() == ControlP5.ACTION_RELEASED) {
ParseAndExit();
}
}
});
cp5.mapKeyFor(new ControlKey() {
@Override
public void keyEvent() {
ParseAndExit();
}
}, ENTER);
}
@Override
public void draw() {
background(0);
}
private void ParseAndExit() {
String text = nBox.getText();
if (text == null || text.isEmpty())
return;
setNeighboursSelection(Integer.parseInt(text));
synchronized (waiting) {
waiting.notify();
}
}
}
}
} |
package nyc.c4q.ac21.romancalc;
/**
* Code to convert to and from Roman numerals.
*/
public class RomanNumerals {
/**
* Formats a number in Roman numerals.
* @param value
* The value to format.
* @return
* The value in Roman numerals.
*/
static String format(int value) {
// TODO: Group 1: Write this function!
return "???";
}
/**
* Parses a number in Roman numerals.
* @param number
* The number to parse.
* @return
* The value, or -1 if the number isn't in Roman numerals.
*/
public static int parse(String number) {
// TODO: Group 2: Write this function!
// You will need:
// `number.length()` gives you the length of the string
// `number.charAt(i)` gives you the character at position `i`
return -1;
}
public static void main(String[] argv) {
// TODO: Group 3: Write this function!
// It should test that format() and parse() work correctly.
}
} |
package orbitSimulator;
import java.awt.Font;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Array;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JLabel;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.Color;
public class EllipticalOrbitInputs extends JPanel implements ActionListener {
// input text fields - NB need to add each new tf to getUserInputs() and a private parameter below
private JTextField tfArgOfPeri;
private JTextField tfPeriapsis;
private JTextField tfApoapsis;
private JTextField tfSemimajorAxis;
private JTextField tfEccentricity;
private JTextField tfPeriod;
private JTextField tfRAAN;
private double ArgOfPeri;
private double Periapsis;
private double Apoapsis;
private double SemimajorAxis;
private double Eccentricity;
private double OrbitalPeriod;
private double RAAN;
private double Period;
private boolean ArgOfPeriAdded;
private boolean PeriapsisAdded;
private boolean ApoapsisAdded;
private boolean SemimajorAxisAdded;
private boolean EccentricityAdded;
private boolean OrbitalPeriodAdded;
private boolean RAANAdded;
private boolean PeriodAdded;
private JButton btnCalculateEllipticalOrbit;
private MainFrameListenerElliptical newGraphicsListener;
private JTextField tfSME;
private JTextField tfVelocity;
private JTextField tfInclination;
private DocumentListener tfListener;
EllipticalOrbitInputs()
{
setLayout(new MigLayout("", "[22.00][18.00][29.00][83.00][59.00][73.00][81.00]", "[][][][12.00][][14.00][][center][][][][]"));
JLabel lblEllipticalOrbitInputs = new JLabel("Elliptical Orbit Inputs");
lblEllipticalOrbitInputs.setFont(new Font("Lucida Grande", Font.BOLD, 13));
add(lblEllipticalOrbitInputs, "cell 0 0 4 1");
JLabel lblArgumentOfPeriapsis = new JLabel("Arg of Periapsis");
lblArgumentOfPeriapsis.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(lblArgumentOfPeriapsis, "cell 1 1 2 1");
tfArgOfPeri = new JTextField();
tfArgOfPeri.setBackground(Color.WHITE);
tfArgOfPeri.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(tfArgOfPeri, "cell 3 1,growx");
tfArgOfPeri.setColumns(10);
JLabel lblRadius = new JLabel("Radius");
lblRadius.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(lblRadius, "cell 1 2 2 1");
JLabel lblPeriapsis = new JLabel("Periapsis");
lblPeriapsis.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(lblPeriapsis, "cell 2 3,alignx left");
tfPeriapsis = new JTextField();
tfPeriapsis.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(tfPeriapsis, "cell 3 3,growx");
tfPeriapsis.setColumns(10);
JLabel lblApoapsis = new JLabel("Apoapsis");
lblApoapsis.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(lblApoapsis, "cell 4 3,alignx left");
tfApoapsis = new JTextField();
tfApoapsis.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(tfApoapsis, "cell 5 3,growx");
tfApoapsis.setColumns(10);
JLabel lblSemimajorAxis = new JLabel("Semimajor Axis");
lblSemimajorAxis.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(lblSemimajorAxis, "cell 1 4 2 1");
tfSemimajorAxis = new JTextField();
tfSemimajorAxis.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(tfSemimajorAxis, "cell 3 4,growx");
tfSemimajorAxis.setColumns(10);
JLabel lblEccentricity = new JLabel("Eccentricity");
lblEccentricity.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(lblEccentricity, "cell 1 5 2 1");
tfEccentricity = new JTextField();
tfEccentricity.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(tfEccentricity, "cell 3 5,growx");
tfEccentricity.setColumns(10);
JLabel lblInclination = new JLabel("Inclination");
lblInclination.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(lblInclination, "cell 1 6 2 1,alignx left");
tfInclination = new JTextField();
tfInclination.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(tfInclination, "cell 3 6,growx,aligny top");
tfInclination.setColumns(10);
JLabel lblVelecity = new JLabel("Velocity @");
lblVelecity.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(lblVelecity, "cell 1 7 2 1,alignx left");
JComboBox comboBox = new JComboBox();
comboBox.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(comboBox, "cell 3 7,growx");
tfVelocity = new JTextField();
tfVelocity.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(tfVelocity, "cell 4 7 2 1,growx");
tfVelocity.setColumns(10);
JLabel lblSME = new JLabel("SME");
lblSME.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(lblSME, "cell 1 8 2 1");
tfSME = new JTextField();
tfSME.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(tfSME, "cell 3 8,growx");
tfSME.setColumns(10);
JLabel lblRaan = new JLabel("RAAN");
lblRaan.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(lblRaan, "cell 1 9 2 1");
tfRAAN = new JTextField();
tfRAAN.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(tfRAAN, "cell 3 9,growx");
tfRAAN.setColumns(10);
JLabel lblOrbitalPeriod = new JLabel("Orbital Period");
lblOrbitalPeriod.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(lblOrbitalPeriod, "cell 1 10 2 1,alignx left");
tfPeriod = new JTextField();
tfPeriod.setFont(new Font("Lucida Grande", Font.PLAIN, 11));
add(tfPeriod, "cell 3 10,growx,aligny top");
tfPeriod.setColumns(10);
btnCalculateEllipticalOrbit = new JButton("Calculate Orbit");
btnCalculateEllipticalOrbit.addActionListener(this);
add(btnCalculateEllipticalOrbit, "cell 4 11 3 1");
// Listen for changes to textFields
tfArgOfPeri.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
}
});
tfPeriapsis.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
System.out.println("tf edited");
}
});
tfApoapsis.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
System.out.println("tf edited");
}
});
tfSemimajorAxis.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
System.out.println("tf edited");
}
});
tfEccentricity.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
System.out.println("tf edited");
}
});
tfInclination.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
System.out.println("tf edited");
}
});
tfVelocity.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
System.out.println("tf edited");
}
});
tfSME.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
System.out.println("tf edited");
}
});
tfPeriod.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
System.out.println("tf edited");
}
});
tfRAAN.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
warn();
}
public void removeUpdate(DocumentEvent e) {
warn();
}
public void insertUpdate(DocumentEvent e) {
warn();
}
public void warn() {
System.out.println("tf edited");
}
});
} // END CONSTRUCTOR
// listener model view controller architecture
public void setNewGraphics(MainFrameListenerElliptical listener)
{
System.out.println("setNewGraphics()");
this.newGraphicsListener = listener;
}
/*@Override - I'm not sure why this isnt required as it is in CircularOrbitInputs using the same architecture.
The only possibility I can think of is that circularPanel has a button which may mean that it needs
overriding.*/
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("in actionPerformed(ActionEvent e)");
//getOrbitRenderScale();
calculateEllipticalOrbit();
newGraphicsListener.setNewGraphics();
}
private void getOrbitRenderScale() {
// TODO Auto-generated method stub
}
private void calculateEllipticalOrbit() {
System.out.println("in calculateEllipticalOrbit()");
// get all the inputs and set them to private parameters
getUserInputs();
// calculations (multiple methods)
// write calculated values to relevant text fields
}
private void getUserInputs() {
if (isNumeric(tfArgOfPeri.getText()) == true) {
ArgOfPeri = Double.parseDouble(tfArgOfPeri.getText());
ArgOfPeriAdded = true;
}
else {
ArgOfPeriAdded = false;
}
//System.out.println("ArgOfPeri = " + ArgOfPeri);
if (isNumeric(tfPeriapsis.getText()) == true) {
Periapsis = Double.parseDouble(tfPeriapsis.getText());
PeriapsisAdded = true;
}
else {
PeriapsisAdded = false;
}
//System.out.println("Periapsis = " + Periapsis);
if (isNumeric(tfApoapsis.getText()) == true) {
Apoapsis = Double.parseDouble(tfApoapsis.getText());
ApoapsisAdded = true;
}
else {
ApoapsisAdded = false;
}
//System.out.println("Apoapsis = " + Apoapsis);
if (isNumeric(tfSemimajorAxis.getText()) == true) {
SemimajorAxis = Double.parseDouble(tfSemimajorAxis.getText());
SemimajorAxisAdded = true;
}
else {
SemimajorAxisAdded = false;
}
//System.out.println("SemimajorAxis = " + SemimajorAxis);
if (isNumeric(tfEccentricity.getText()) == true) {
Eccentricity = Double.parseDouble(tfEccentricity.getText());
EccentricityAdded = true;
}
else {
EccentricityAdded = false;
}
//System.out.println("Eccentricity = " + Eccentricity);
if (isNumeric(tfPeriod.getText()) == true) {
OrbitalPeriod = Double.parseDouble(tfPeriod.getText());
OrbitalPeriodAdded = true;
}
else {
OrbitalPeriodAdded = false;
}
//System.out.println("OrbitalPeriod = " + OrbitalPeriod);
if (isNumeric(tfRAAN.getText()) == true) {
RAAN = Double.parseDouble(tfRAAN.getText());
RAANAdded = true;
}
else {
RAANAdded = false;
}
//System.out.println("RANN = " + RAAN);
if (isNumeric(tfPeriod.getText()) == true) {
Period = Double.parseDouble(tfPeriod.getText());
PeriodAdded = true;
}
else {
PeriodAdded = false;
}
//System.out.println("Period = " + Period);
}
public static void resetEllipticalPanel() {
// TODO Auto-generated method stub
}
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
} |
/* -*- mode: Java; c-basic-offset: 4; -*- */
package org.openlaszlo.compiler;
import java.io.*;
import java.text.ChoiceFormat;
import java.util.*;
import java.util.regex.*;
import org.openlaszlo.compiler.ViewSchema.ColorFormatException;
import org.openlaszlo.css.CSSParser;
import org.openlaszlo.sc.Function;
import org.openlaszlo.sc.ScriptCompiler;
import org.openlaszlo.server.*;
import org.openlaszlo.utils.ChainedException;
import org.openlaszlo.utils.ListFormat;
import org.openlaszlo.xml.internal.MissingAttributeException;
import org.openlaszlo.xml.internal.Schema;
import org.openlaszlo.xml.internal.XMLUtils;
import org.apache.commons.collections.CollectionUtils;
import org.jdom.Attribute;
import org.jdom.Element;
import org.jdom.Text;
import org.jdom.Content;
import org.jdom.Namespace;
/** Models a runtime LzNode. */
public class NodeModel implements Cloneable {
public static final String FONTSTYLE_ATTRIBUTE = "fontstyle";
public static final String WHEN_IMMEDIATELY = "immediately";
public static final String WHEN_ONCE = "once";
public static final String WHEN_ALWAYS = "always";
public static final String WHEN_PATH = "path";
public static final String WHEN_STYLE = "style";
public static final String ALLOCATION_INSTANCE = "instance";
public static final String ALLOCATION_CLASS = "class";
private static final String SOURCE_LOCATION_ATTRIBUTE_NAME = "__LZsourceLocation";
final ViewSchema schema;
final Element element;
String className;
String id = null;
LinkedHashMap attrs = new LinkedHashMap();
List children = new Vector();
/** A set {eventName: String -> True) of names of event handlers
* declared with <handler name="xxx"/>. */
LinkedHashMap delegates = new LinkedHashMap();
/* Unused */
LinkedHashMap events = new LinkedHashMap();
LinkedHashMap references = new LinkedHashMap();
LinkedHashMap classAttrs = new LinkedHashMap();
LinkedHashMap setters = new LinkedHashMap();
LinkedHashMap styles = new LinkedHashMap();
NodeModel datapath = null;
/** [eventName: String, methodName: String, Function] */
List delegateList = new Vector();
ClassModel parentClassModel;
String initstage = null;
int totalSubnodes = 1;
final CompilationEnvironment env;
protected boolean emitClassDecl = false;
public Object clone() {
NodeModel copy;
try {
copy = (NodeModel) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
copy.attrs = new LinkedHashMap(copy.attrs);
copy.delegates = new LinkedHashMap(copy.delegates);
copy.events = new LinkedHashMap(copy.events);
copy.references = new LinkedHashMap(copy.references);
copy.classAttrs = new LinkedHashMap(copy.classAttrs);
copy.setters = new LinkedHashMap(copy.setters);
copy.styles = new LinkedHashMap(copy.styles);
copy.delegateList = new Vector(copy.delegateList);
copy.children = new Vector();
for (Iterator iter = children.iterator(); iter.hasNext(); ) {
copy.children.add(((NodeModel) iter.next()).clone());
}
return copy;
}
NodeModel(Element element, ViewSchema schema, CompilationEnvironment env) {
this.element = element;
this.schema = schema;
this.env = env;
this.className = element.getName();
// Cache ClassModel for parent
this.parentClassModel = this.getParentClassModel();
this.initstage =
this.element.getAttributeValue("initstage");
if (this.initstage != null) {
this.initstage = this.initstage.intern();
}
// Get initial node count from superclass
// TODO: [2003-05-04] Extend this mechanism to cache/model
// all relevant superclass info
// TODO: [2003-05-04 ptw] How can we get this info for
// instances of built-in classes?
if (this.parentClassModel != null) {
ElementWithLocationInfo parentElement =
(ElementWithLocationInfo) this.parentClassModel.definition;
// TODO: [2003-05-04 ptw] As above, but a class
// that extends a built-in class
if (parentElement != null) {
// TODO: [2003-05-04 ptw] An instantiation of
// a class that has not been modelled yet --
// do enough modelling to get what is needed.
if (parentElement.model != null) {
this.totalSubnodes =
parentElement.model.classSubnodes();
if (this.initstage == null) {
this.initstage =
parentElement.model.initstage;
}
}
}
}
}
private static final String DEPRECATED_METHODS_PROPERTY_FILE = (
LPS.getMiscDirectory() + File.separator + "lzx-deprecated-methods.properties"
);
private static final Properties sDeprecatedMethods = new Properties();
static {
try {
InputStream is = new FileInputStream(DEPRECATED_METHODS_PROPERTY_FILE);
try {
sDeprecatedMethods.load(is);
} finally {
is.close();
}
} catch (java.io.IOException e) {
throw new ChainedException(e);
}
}
/* List of flash builtins to warn about if the user tries to redefine them */
private static final String FLASH6_BUILTINS_PROPERTY_FILE = (
LPS.getMiscDirectory() + File.separator + "flash6-builtins.properties"
);
private static final String FLASH7_BUILTINS_PROPERTY_FILE = (
LPS.getMiscDirectory() + File.separator + "flash7-builtins.properties"
);
public static final Properties sFlash6Builtins = new Properties();
public static final Properties sFlash7Builtins = new Properties();
static {
try {
InputStream is6 = new FileInputStream(FLASH6_BUILTINS_PROPERTY_FILE);
try {
sFlash6Builtins.load(is6);
} finally {
is6.close();
}
InputStream is7 = new FileInputStream(FLASH7_BUILTINS_PROPERTY_FILE);
try {
sFlash7Builtins.load(is7);
} finally {
is7.close();
}
} catch (java.io.IOException e) {
throw new ChainedException(e);
}
}
static class BindingExpr {
String expr;
BindingExpr(String expr) { this.expr = expr; }
String getExpr() { return this.expr; }
}
static class CompiledAttribute {
String name;
Schema.Type type;
private String value;
String when;
Element source;
CompilationEnvironment env;
String srcloc;
String bindername;
String dependenciesname;
static org.openlaszlo.sc.Compiler compiler;
org.openlaszlo.sc.Compiler getCompiler() {
if (compiler != null) { return compiler; }
return compiler = new org.openlaszlo.sc.Compiler();
}
public CompiledAttribute (String name, Schema.Type type, String value, String when, Element source, CompilationEnvironment env) {
this.name = name;
this.type = type;
this.value = value;
this.when = when;
this.source = source;
this.env = env;
this.srcloc = CompilerUtils.sourceLocationDirective(source, true);
String parent_name = source.getAttributeValue("id");
if (parent_name == null) {
parent_name = CompilerUtils.attributeUniqueName(source, "binder");
}
String unique = "$" + parent_name + "_" + env.methodNameGenerator.next();
if (when.equals(WHEN_PATH) || (when.equals(WHEN_STYLE)) || when.equals(WHEN_ONCE) || when.equals(WHEN_ALWAYS)) {
this.bindername = "$lzc$bind_" + name + unique;
}
if (when.equals(WHEN_ALWAYS)) {
this.dependenciesname = "$lzc$dependencies_" + name + unique;
}
}
public Function getBinderMethod() {
if (! (when.equals(WHEN_PATH) || (when.equals(WHEN_STYLE)) || when.equals(WHEN_ONCE) || when.equals(WHEN_ALWAYS))) {
return null;
}
String installer = "setAttribute";
String body = "\n#beginAttribute\n" + srcloc + value + "\n#endAttribute\n)";
String pragmas =
"\n#pragma 'withThis'\n";
if (when.equals(WHEN_ONCE) || when.equals(WHEN_ALWAYS)) {
// default
} else if (when.equals(WHEN_PATH)) {
installer = "dataBindAttribute";
} else if (when.equals(WHEN_STYLE)) {
// Styles are processed as constraints, although
// they are not compiled as constraints. Whether
// a style results in a constraint or not cannot
// be determined until the style property value is
// derived (at run time)
installer = "__LZstyleBindAttribute";
}
Function binder = new Function(
bindername,
// Binders are called by LzDelegate.execute, which passes the
// value sent by sendEvent, so we have to accept it, but we
// ignore it
"$lzc$ignore=null",
pragmas,
"this." + installer + "(" +
ScriptCompiler.quote(name) + "," +
body,
srcloc);
return binder;
}
public Function getDependenciesMethod() {
if (! when.equals(WHEN_ALWAYS)) {
return null;
}
String preface = "\n#pragma 'withThis'\n";
String body = "return " + getCompiler().dependenciesForExpression(value);
Function dependencies = new Function(
dependenciesname,
"",
preface,
body,
srcloc);
return dependencies;
}
public Object getInitialValue () {
// A null value indicates an attribute that was declared only
if (value == null) { return null; }
// Handle when cases
// N.B., $path and $style are not really when values, but
// there you go...
if (when.equals(WHEN_PATH) || (when.equals(WHEN_STYLE)) || when.equals(WHEN_ONCE) || when.equals(WHEN_ALWAYS)) {
String kind = "LzOnceExpr";
if (when.equals(WHEN_ONCE) || when.equals(WHEN_PATH)) {
// default
} else if (when.equals(WHEN_STYLE)) {
// Styles are processed as constraints, although
// they are not compiled as constraints. Whether
// a style results in a constraint or not cannot
// be determined until the style property value is
// derived (at run time)
kind = "LzConstraintExpr";
} else if (when.equals(WHEN_ALWAYS)) {
kind = "LzConstraintExpr";
// Always constraints have a second value, the dependencies method
return new BindingExpr("new " + kind + "(" +
ScriptCompiler.quote(bindername) + ", " +
ScriptCompiler.quote(dependenciesname) + ")");
}
// Return an initExpr as the 'value' of the attribute
return new BindingExpr("new " + kind + "(" + ScriptCompiler.quote(bindername) +")");
} else if (when.equals(WHEN_IMMEDIATELY)) {
if (CanvasCompiler.isElement(source) &&
("width".equals(name) || "height".equals(name))) {
// The Canvas compiler depends on seeing width/height
// unadulterated <sigh />.
// TODO: [2007-05-05 ptw] (LPP-3949) The
// #beginAttribute directives for the parser should
// be added when the attribute is written, not
// here...
return value;
} else {
return "\n#beginAttribute\n" + srcloc + value + "\n#endAttribute\n";
}
} else {
throw new CompilationError("invalid when value '" +
when + "'", source);
}
}
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("{NodeModel class=" + className);
if (!attrs.isEmpty())
buffer.append(" attrs=" + attrs.keySet());
if (!delegates.isEmpty())
buffer.append(" delegates=" + delegates.keySet());
if (!events.isEmpty())
buffer.append(" events=" + events.keySet());
if (!references.isEmpty())
buffer.append(" references=" + references.keySet());
if (!classAttrs.isEmpty())
buffer.append(" classAttrs=" + classAttrs.keySet());
if (!setters.isEmpty())
buffer.append(" setters=" + setters.keySet());
if (!styles.isEmpty())
buffer.append(" styles=" + styles.keySet());
if (!delegateList.isEmpty())
buffer.append(" delegateList=" + delegateList);
if (!children.isEmpty())
buffer.append(" children=" + children);
buffer.append("}");
return buffer.toString();
}
List getChildren() {
return children;
}
public static boolean isPropertyElement(Element elt) {
String name = elt.getName();
return name.equals("attribute") || name.equals("method")
|| name.equals("handler")
|| name.equals("event");
}
/** Returns a name that is used to report this element in warning
* messages. */
String getMessageName() {
return "element " + element.getName();
}
/**
* Returns a script that creates a runtime representation of a
* model. The format of this representation is specified <a
* href="../../../../doc/compiler/views.html">here</a>.
*
*/
public String asJavascript() {
try {
java.io.Writer writer = new java.io.StringWriter();
ScriptCompiler.writeObject(this.asMap(), writer);
return writer.toString();
} catch (java.io.IOException e) {
throw new ChainedException(e);
}
}
/** Returns true iff clickable should default to true. */
private static boolean computeDefaultClickable(ViewSchema schema,
Map attrs,
Map events,
Map delegates) {
if ("true".equals(attrs.get("cursor"))) {
return true;
}
for (Iterator iter = events.keySet().iterator(); iter.hasNext();) {
String eventName = (String) iter.next();
if (schema.isMouseEventAttribute(eventName)) {
return true;
}
}
for (Iterator iter = delegates.keySet().iterator(); iter.hasNext();) {
String eventName = (String) iter.next();
if (schema.isMouseEventAttribute(eventName)) {
return true;
}
}
return false;
}
/**
* Returns a NodeModel that represents an Element, including the
* element's children
*
* @param elt an element
* @param schema a schema, used to encode attribute values
* @param env the CompilationEnvironment
*/
public static NodeModel elementAsModel(Element elt, ViewSchema schema,
CompilationEnvironment env) {
return elementAsModelInternal(elt, schema, true, env);
}
/**
* Returns a NodeModel that represents an Element, excluding the
* element's children
*
* @param elt an element
* @param schema a schema, used to encode attribute values
* @param env the CompilationEnvironment
*/
public static NodeModel elementOnlyAsModel(Element elt, ViewSchema schema,
CompilationEnvironment env) {
return elementAsModelInternal(elt, schema, false, env);
}
/** Returns a NodeModel that represents an Element
*
* @param elt an element
* @param schema a schema, used to encode attribute values
* @param includeChildren whether or not to include children
* @param env the CompilationEnvironment
*/
private static NodeModel elementAsModelInternal(
Element elt, ViewSchema schema,
boolean includeChildren, CompilationEnvironment env)
{
NodeModel model = new NodeModel(elt, schema, env);
LinkedHashMap attrs = model.attrs;
Map events = model.events;
Map delegates = model.delegates;
model.addAttributes(env);
// This emits a local dataset node, so only process
// <dataset> tags that are not top level datasets.
if (elt.getName().equals("dataset")) {
boolean contentIsLiteralXMLData = true;
String datafromchild = elt.getAttributeValue("datafromchild");
String src = elt.getAttributeValue("src");
String type = elt.getAttributeValue("type");
if ((type != null && (type.equals("soap") || type.equals("http")))
|| (src != null && XMLUtils.isURL(src))
|| "true".equals(datafromchild)) {
contentIsLiteralXMLData = false;
}
if (contentIsLiteralXMLData) {
// Default to legacy behavior, treat all children as XML literal data.
attrs.put("initialdata", getDatasetContent(elt, env));
includeChildren = false;
}
}
if (includeChildren) {
model.addChildren(env);
model.addText();
if (!attrs.containsKey("clickable")
&& computeDefaultClickable(schema, attrs, events, delegates)) {
attrs.put("clickable", "true");
}
}
// Record the model in the element for classes
((ElementWithLocationInfo) elt).model = model;
return model;
}
// Calculate how many nodes this object will put on the
// instantiation queue.
int totalSubnodes() {
// A class does not instantiate its subnodes.
// States override LzNode.thaw to delay subnodes.
// FIXME [2004-06-3 ows]: This won't work for subclasses
// of state.
if (ClassCompiler.isElement(element) ||
className.equals("state")) {
return 1;
}
// initstage late, defer delay subnodes
if (this.initstage != null &&
(this.initstage == "late" ||
this.initstage == "defer")) {
return 0;
}
return this.totalSubnodes;
}
// How many nodes will be inherited from this class
int classSubnodes() {
if (ClassCompiler.isElement(element)) {
return this.totalSubnodes;
}
return 0;
}
ClassModel getClassModel() {
return schema.getClassModel(this.className);
}
/** Gets the ClassModel for this element's parent class. If this
* element is a <class> definition, the superclass; otherwise the
* class of the tag of this element. */
ClassModel getParentClassModel() {
String parentName = this.className;
return
("class".equals(parentName) || "interface".equals(parentName))?
schema.getClassModel(element.getAttributeValue("extends", ClassCompiler.DEFAULT_SUPERCLASS_NAME)):
schema.getClassModel(parentName);
}
// TODO: [2008-03-26 ptw] Need to integrate mixins into the search
// for inherited attributes
ClassModel[] mixinModels;
ClassModel[] getMixinModels() {
String parentName = this.className;
if (! "class".equals(parentName)) { return null; }
if (mixinModels != null) { return mixinModels; }
String mixinSpec = element.getAttributeValue("with");
String mixins[];
if (mixinSpec != null) {
mixins = mixinSpec.split("\\s+,\\s+");
mixinModels = new ClassModel[mixins.length];
for (int i = 0; i < mixins.length; i++) {
ClassModel mm = schema.getClassModel(mixins[i]);
if (mm == null) {
throw new CompilationError(
"No model for mixin: " + mixins[i],
element);
}
mixinModels[i] = mm;
}
}
return mixinModels;
}
void setClassName(String name) {
this.className = name;
this.parentClassModel = getParentClassModel();
}
ViewSchema.Type getAttributeTypeInfoFromParent(
Element elt, String attrname)
throws UnknownAttributeException
{
Element parent = elt.getParentElement();
return schema.getAttributeType(parent, attrname);
}
// Should only be called on a <class> or <interface> definition element.
ViewSchema.Type getAttributeTypeInfoFromSuperclass(
Element classDefElement, String attrname)
throws UnknownAttributeException
{
String superclassname = classDefElement.getAttributeValue("extends", ClassCompiler.DEFAULT_SUPERCLASS_NAME);
ClassModel superclassModel = schema.getClassModel(superclassname);
if (superclassModel == null) {
throw new CompilationError(
/* (non-Javadoc)
* @i18n.test
* @org-mes="Could not find superclass info for class " + p[0]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
NodeModel.class.getName(),"051018-411", new Object[] {superclassname, classDefElement})
);
}
// Check if this attribute is defined on the parent class, if
// so, return that type
AttributeSpec attr = superclassModel.getAttribute(attrname);
if (attr != null) {
return attr.type;
}
// Otherwise, check if it's defined on the "class" element
// (e.g., 'name', 'extends', or 'with')
superclassModel = schema.getClassModel("class");
return superclassModel.getAttributeTypeOrException(attrname);
}
// Get an attribute value, defaulting to the
// inherited value, or ultimately the supplied default
String getAttributeValueDefault(String attribute,
String name,
String defaultValue) {
// Look for an inherited value
if (this.parentClassModel != null) {
AttributeSpec attrSpec =
this.parentClassModel.getAttribute(attribute);
if (attrSpec != null) {
Element source = attrSpec.source;
if (source != null) {
return XMLUtils.getAttributeValue(source, name, defaultValue);
}
}
}
return defaultValue;
}
/** Is this element a direct child of the canvas? */
// FIXME [2004-06-03 ows]: Use CompilerUtils.isTopLevel instead.
// This implementation misses children of <library> and <switch>.
// Since it's only used for compiler warnings about duplicate
// names this doesn't break program compilation.
boolean topLevelDeclaration() {
Element parent = element.getParentElement();
if (parent == null) {
return false;
}
return ("canvas".equals(parent.getName()));
}
void addAttributes(CompilationEnvironment env) {
// Add source locators, if requested. Added here because it
// is not in the schema
if (env.getBooleanProperty(env.SOURCELOCATOR_PROPERTY)) {
String location = "document(" +
ScriptCompiler.quote(Parser.getSourceMessagePathname(element)) +
")" +
XMLUtils.getXPathTo(element);
CompiledAttribute cattr = compileAttribute(
element, SOURCE_LOCATION_ATTRIBUTE_NAME,
location, ViewSchema.STRING_TYPE,
WHEN_IMMEDIATELY);
addAttribute(cattr, SOURCE_LOCATION_ATTRIBUTE_NAME,
attrs, events, references, classAttrs, styles);
}
// Add file/line information if debugging
if (env.getBooleanProperty(env.DEBUG_PROPERTY)) {
// File/line stored separately for string sharing
String name = "_dbg_filename";
String filename = Parser.getSourceMessagePathname(element);
CompiledAttribute cattr =
compileAttribute(element, name, filename, ViewSchema.STRING_TYPE, WHEN_IMMEDIATELY);
addAttribute(cattr, name, attrs, events, references, classAttrs, styles);
name = "_dbg_lineno";
Integer lineno = Parser.getSourceLocation(element, Parser.LINENO);
cattr = compileAttribute(element, name, lineno.toString(), ViewSchema.NUMBER_TYPE, WHEN_IMMEDIATELY);
addAttribute(cattr, name, attrs, events, references, classAttrs, styles);
}
ClassModel classModel = getClassModel();
if (classModel == null) {
throw new CompilationError("Could not find class definition for tag `" + className + "`", element);
}
// Encode the attributes
for (Iterator iter = element.getAttributes().iterator(); iter.hasNext(); ) {
Attribute attr = (Attribute) iter.next();
Namespace ns = attr.getNamespace();
String name = attr.getName();
String value = element.getAttributeValue(name, ns);
if (name.equals(FONTSTYLE_ATTRIBUTE)) {
// "bold italic", "italic bold" -> "bolditalic"
value = FontInfo.normalizeStyleString(value, false);
}
if (name.toLowerCase().equals("defaultplacement")) {
if (value != null && value.matches("\\s*['\"]\\S*['\"]\\s*")) {
String oldValue = value;
// strip off start and ending quotes;
value = value.trim();
value = value.substring(1, value.length()-1);
env.warn(
/* (non-Javadoc)
* @i18n.test
* @org-mes="Replacing defaultPlacement=\"" + p[0] + "\" by \"" + p[1] + "\". For future compatibility" + ", you should make this change to your source code."
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
NodeModel.class.getName(),"051018-513", new Object[] {oldValue, value})
,element);
}
}
// Special case for compiling a class, the class
// attributes are really 'meta' attributes, not
// attributes of the class -- they will be processed by
// the ClassModel or ClassCompiler
if ("class".equals(className) || "interface".equals(className) || "mixin".equals(className)) {
// TODO: [2008-03-22 ptw] This should somehow be
// derived from the schema, but this does not work, so
// we hard-code the meta-attributes here
// if (superclassModel.getAttribute(name) != null) {
if ("name".equals(name) || "extends".equals(name) || "with".equals(name)) {
continue;
}
}
// Warn for redefine of a flash builtin
// TODO: [2006-01-23 ptw] What about colliding with DHTML globals?
if ((name.equals("id") || name.equals("name")) &&
(value != null &&
(env.getRuntime().indexOf("swf") == 0) &&
("swf6".equals(env.getRuntime()) ?
sFlash6Builtins.containsKey(value.toLowerCase()) :
sFlash7Builtins.containsKey(value)))) {
env.warn(
/* (non-Javadoc)
* @i18n.test
* @org-mes="You have given the " + p[0] + " an attribute " + p[1] + "=\"" + p[2] + "\", " + "which may overwrite the Flash builtin class named \"" + p[3] + "\"."
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
NodeModel.class.getName(),"051018-532", new Object[] {getMessageName(), name, value, value})
,element);
}
// Catch duplicated id/name attributes which may shadow
// each other or overwrite each other. An id/name will be
// global there is "id='foo'" or if "name='foo'" at the
// top level (immediate child of the canvas).
if ((name.equals("id")) ||
(name.equals("name") &&
topLevelDeclaration() &&
(! ("class".equals(className) || "interface".equals(className) || "mixin".equals(className))))) {
ElementWithLocationInfo dup =
(ElementWithLocationInfo) env.getId(value);
// we don't want to give a warning in the case
// where the id and name are on the same element,
// i.e., <view id="foo" name="foo"/>
if (dup != null && dup != element) {
String locstring =
CompilerUtils.sourceLocationPrettyString(dup);
env.warn(
/* (non-Javadoc)
* @i18n.test
* @org-mes="Duplicate id attribute \"" + p[0] + "\" at " + p[1]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
NodeModel.class.getName(),"051018-576", new Object[] {value, locstring})
,
element);
} else {
// TODO: [07-18-03 hqm] We will canonicalize
// all id's to lowercase, because actionscript
// is not case sensitive. but in the future,
// we should preserve case.
env.addId(value, element);
}
}
// Check that the view name is a valid javascript identifier
if ((name.equals("name") || name.equals("id")) &&
(value == null || !ScriptCompiler.isIdentifier(value))) {
CompilationError cerr = new CompilationError(
"The "+name+" attribute of this node, "+ "\"" + value + "\", is not a valid javascript identifier " , element);
throw(cerr);
}
Schema.Type type;
try {
if ("class".equals(className) || "interface".equals(className) || "mixin".equals(className)) {
// Special case, if we are compiling a "class"
// tag, then get the type of attributes from the
// superclass.
type = getAttributeTypeInfoFromSuperclass(element, name);
} else if (className.equals("state")) {
// Special case for "state", it can have any attribute
// which belongs to the parent.
try {
type = schema.getAttributeType(element, name);
} catch (UnknownAttributeException e) {
type = getAttributeTypeInfoFromParent(element, name);
}
} else {
// NOTE [2007-06-14 ptw]: Querying the classModel
// directly will NOT work, because the schema
// method has some special kludges in it for canvas
// width and height!
type = schema.getAttributeType(element, name);
}
} catch (UnknownAttributeException e) {
String solution;
AttributeSpec alt = schema.findSimilarAttribute(className, name);
if (alt != null) {
String classmessage = "";
if (alt.source != null) {
classmessage = " on class "+alt.source.getName()+"\"";
} else {
classmessage = " on class "+getMessageName();
}
solution =
/* (non-Javadoc)
* @i18n.test
* @org-mes="found an unknown attribute named \"" + p[0] + "\" on " + p[1] + ", however there is an attribute named \"" + p[2] + "\"" + p[3] + ", did you mean to use that?"
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
NodeModel.class.getName(),"051018-616", new Object[] {name, getMessageName(), alt.name, classmessage});
} else {
solution =
/* (non-Javadoc)
* @i18n.test
* @org-mes="found an unknown attribute named \"" + p[0] + "\" on " + p[1] + ", check the spelling of this attribute name"
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
NodeModel.class.getName(),"051018-624", new Object[] {name, getMessageName()});
}
env.warn(solution, element);
type = ViewSchema.EXPRESSION_TYPE;
}
if (type == schema.EVENT_HANDLER_TYPE) {
addHandlerFromAttribute(element, name, value);
} else {
// NOTE: [2008-04-01 ptw] May be obsolete?
if (type == schema.ID_TYPE) {
this.id = value;
}
String when = this.getAttributeValueDefault(
name, "when", WHEN_IMMEDIATELY);
// NYI
String allocation = this.getAttributeValueDefault(
name, "allocation", ALLOCATION_INSTANCE);
try {
CompiledAttribute cattr = compileAttribute(
element, name, value, type, when);
addAttribute(cattr, name, attrs, events,
references, classAttrs, styles);
// Check if we are aliasing another 'name'
// attribute of a sibling
if (name.equals("name")) {
Element parent = element.getParentElement();
if (parent != null) {
for (Iterator iter2 = parent.getChildren().iterator(); iter2.hasNext(); ) {
Element e = (Element) iter2.next();
if (!e.getName().equals("resource") && !e.getName().equals("font")
&& e != element && value.equals(e.getAttributeValue("name"))) {
String dup_location =
CompilerUtils.sourceLocationPrettyString(e);
env.warn(
/* (non-Javadoc)
* @i18n.test
* @org-mes=p[0] + " has the same name=\"" + p[1] + "\" attribute as a sibling element at " + p[2]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
NodeModel.class.getName(),"051018-658", new Object[] {getMessageName(), value, dup_location})
,element);
}
}
}
}
} catch (CompilationError e) {
env.warn(e);
}
}
}
}
void addAttribute(CompiledAttribute cattr, String name,
LinkedHashMap attrs, LinkedHashMap events,
LinkedHashMap references, LinkedHashMap classAttrs,
LinkedHashMap styles) {
if (attrs.containsKey(name)) {
env.warn(
/* (non-Javadoc)
* @i18n.test
* @org-mes="an attribute or method named '" + p[0] + "' already is defined on " + p[1]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
NodeModel.class.getName(),"051018-682", new Object[] {name, getMessageName()})
,element);
}
if (cattr.bindername != null) {
attrs.put(cattr.bindername, cattr.getBinderMethod());
}
if (cattr.dependenciesname != null) {
attrs.put(cattr.dependenciesname, cattr.getDependenciesMethod());
}
attrs.put(name, cattr.getInitialValue());
}
static String getDatasetContent(Element element, CompilationEnvironment env) {
return getDatasetContent(element, env, false);
}
// For a dataset (well really for any Element), writes out the
// child literal content as an escaped string, which could be used
// to initialize the dataset at runtime.
static String getDatasetContent(Element element, CompilationEnvironment env, boolean trimwhitespace) {
String srcloc =
CompilerUtils.sourceLocationDirective(element, true);
// If type='http' or the path starts with http: or https:,
// then don't attempt to include the data at compile
// time. The runtime will have to recognize it as runtime
// loaded URL data.
if ("http".equals(element.getAttributeValue("type"))) {
return "null";
}
boolean nsprefix = false;
if ("true".equals(element.getAttributeValue("nsprefix"))) {
nsprefix = true;
}
Element content = new Element("data");
String src = element.getAttributeValue("src");
// If 'src' attribute is a URL or null, don't try to expand it now,
// just return. The LFC will have to interpret it as a runtime
// loadable data URL.
if ( (src != null) &&
(src.startsWith("http:") ||
src.startsWith("https:")) ) {
return "null";
} else if (src != null) {
// Expands the src file content inline
File file = env.resolveReference(element);
try {
Element literaldata = new org.jdom.input.SAXBuilder(false)
.build(file)
.getRootElement();
if (literaldata == null) {
return "null";
}
literaldata.detach();
// add the expanded file contents as child node
content.addContent(literaldata);
} catch (org.jdom.JDOMException e) {
throw new CompilationError(e);
} catch (IOException e) {
throw new CompilationError(e);
} catch (java.lang.OutOfMemoryError e) {
// The runtime gc is necessary in order for subsequent
// compiles to succeed. The System gc is for good
// luck.
throw new CompilationError(
/* (non-Javadoc)
* @i18n.test
* @org-mes="out of memory"
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
NodeModel.class.getName(),"051018-761")
, element);
}
} else {
// no 'src' attribute, use element inline content
content.addContent(element.cloneContent());
}
// Serialize the child elements, as the local data
org.jdom.output.XMLOutputter xmloutputter =
new org.jdom.output.XMLOutputter();
// strip the <dataset> wrapper
// If nsprefix is false, remove namespace from elements before
// serializing, or XMLOutputter puts a "xmlns" attribute on
// the top element in the serialized string.
if (!nsprefix) {
removeNamespaces(content);
}
if (trimwhitespace) {
trimWhitespace(content);
}
String body = null;
if (content != null) {
body = xmloutputter.outputString(content);
return ScriptCompiler.quote(body);
} else {
return "null";
}
}
// Recursively null out the namespace on elt and children
static void removeNamespaces(Element elt) {
elt.setNamespace(null);
for (Iterator iter = elt.getChildren().iterator(); iter.hasNext(); ) {
Element child = (Element) iter.next();
removeNamespaces(child);
}
}
// Recursively trim out the whitespace on text nodes
static void trimWhitespace(Content elt) {
if (elt instanceof Text) {
((Text) elt).setText(((Text)elt).getTextTrim());
} else if (elt instanceof Element) {
for (Iterator iter = ((Element) elt).getContent().iterator(); iter.hasNext(); ) {
Content child = (Content) iter.next();
trimWhitespace(child);
}
}
}
boolean isDatapathElement(Element child) {
return (child.getName().equals("datapath"));
}
/** Warn if named child tag conflicts with a declared attribute in the parent class.
*/
void checkChildNameConflict(String parentName, Element child, CompilationEnvironment env) {
String attrName = child.getAttributeValue("name");
if (attrName != null) {
AttributeSpec attrSpec = schema.getClassAttribute ( parentName, attrName) ;
// Only warn if the attribute we are shadowing has a declared initial value.
if (attrSpec != null && attrSpec.defaultValue != null) {
// TODO [2007-09-26 hqm] i18n this
env.warn(
"Child tag '" + child.getName() +
"' with attribute '"+attrName +
"' conflicts with attribute named '"+attrName+"' of type '" + attrSpec.type +
"' on parent tag '"+element.getName()+"'.",
element);
}
}
}
void addChildren(CompilationEnvironment env) {
// Encode the children
for (Iterator iter = element.getChildren().iterator(); iter.hasNext(); ) {
ElementWithLocationInfo child = (ElementWithLocationInfo) iter.next();
if (!schema.canContainElement(element.getName(), child.getName())) {
// If this element is allowed to contain HTML content, then
// we don't want to warn about encountering an HTML child element.
if (!( schema.hasTextContent(element) && schema.isHTMLElement(child))) {
env.warn(
// TODO [2007-09-26 hqm] i18n this
"The tag '" + child.getName() +
"' cannot be used as a child of " + element.getName(),
element);
}
}
try {
if (child.getName().equals("data")) {
checkChildNameConflict(element.getName(), child, env);
// literal data
addLiteralDataElement(child);
} else if (isPropertyElement(child)) {
addPropertyElement(child);
} else if (schema.isHTMLElement(child)) {
; // ignore; the text compiler wiil handle this
} else if (schema.isDocElement(child)) {
; // ignore doc nodes.
} else if (isDatapathElement(child)) {
checkChildNameConflict(element.getName(), child, env);
NodeModel dpnode = elementAsModel(child, schema, env);
this.datapath = dpnode;
} else {
checkChildNameConflict(element.getName(), child, env);
NodeModel childModel = elementAsModel(child, schema, env);
children.add(childModel);
// Declare the child name (if any) as a property
// of the node so that references to it from
// methods can be resolved at compile-time
String childName = child.getAttributeValue("name");
if (childName != null) {
attrs.put(childName, null);
}
totalSubnodes += childModel.totalSubnodes();
}
} catch (CompilationError e) {
env.warn(e);
}
}
}
void addPropertyElement(Element element) {
String tagName = element.getName();
if (tagName.equals("method")) {
addMethodElement(element);
} else if (tagName.equals("handler")) {
addHandlerElement(element);
} else if (tagName.equals("event")) {
addEventElement(element);
} else if (tagName.equals("attribute")) {
addAttributeElement(element);
}
}
/** Defines an event handler.
*
* <handler name="eventname" [method="methodname"]>
* [function body]
* </handler>
*
* This can do a compile time check to see if eventname is declared or
* if there is an attribute FOO such that name="onFOO".
*/
void addHandlerElement(Element element) {
String method = element.getAttributeValue("method");
// event name
String event = element.getAttributeValue("name");
String args = CompilerUtils.attributeLocationDirective(element, "args") +
// Handlers get called with one argument, default to
// ignoring that
XMLUtils.getAttributeValue(element, "args", "$lzc$ignore=null");
if ((event == null || !ScriptCompiler.isIdentifier(event))) {
env.warn("handler needs a non-null name attribute");
return;
}
String parent_name =
element.getParentElement().getAttributeValue("id");
String reference = element.getAttributeValue("reference");
if (reference != null) {
reference = CompilerUtils.attributeLocationDirective(element, "reference") + reference;
}
String body = element.getText();
if (body.trim().length() == 0) { body = null; }
// If non-empty body AND method name are specified, flag an error
// If non-empty body, pack it up as a function definition
if (body != null) {
if (method != null) {
env.warn("you cannot declare both a 'method' attribute " +
"*and* a function body on a handler element",
element);
}
body = CompilerUtils.attributeLocationDirective(element, "text") + body;
}
addHandlerInternal(element, parent_name, event, method, args, body, reference);
}
/**
* An event handler defined in the open tag
*/
void addHandlerFromAttribute(Element element, String event, String body) {
String parent_name = element.getAttributeValue("id");
// Handlers get called with one argument, default to ignoring
// that
addHandlerInternal(element, parent_name, event, null, "$lzc$ignore=null", body, null);
}
/**
* Adds a handler for `event` to be handled by `method`. If
* `body` is non-null, adds the method too. If `reference` is
* non-null, adds a method to compute the sender.
*
* @devnote: For backwards-compatibility, you are allowed to pass
* in both a `method` (name) and a `body`. This supports the old
* method syntax where you were allowed to specify the event to be
* handled and the name of the method for the body of the handler.
*/
void addHandlerInternal(Element element, String parent_name, String event, String method, String args, String body, String reference) {
if (body == null && method == null) {
env.warn("Refusing to compile an empty handler, you should declare the event instead", element);
return;
}
String src_loc = CompilerUtils.sourceLocationDirective(element, true);
if (parent_name == null) {
parent_name = CompilerUtils.attributeUniqueName(element, "handler");
}
// Anonymous handler names have to be unique, so append a
// gensym; but they also have to be unique across binary
// libraries, so append parent (class) name
String unique = "$" + parent_name + "_" + env.methodNameGenerator.next();
String referencename = null;
// delegates is only used to determine whether to
// default clickable to true. Clickable should only
// default to true if the event handler is attached to
// this view.
if (reference == null) {
delegates.put(event, Boolean.TRUE);
} else {
referencename = "$lzc$" + "handle_" + event + "_reference" + unique;
Object referencefn = new Function(
referencename,
"",
"\n#pragma 'withThis'\n" +
"return (" +
"#beginAttribute\n" +
reference + "\n#endAttribute\n)");
// Add reference computation as a method (so it can have
// 'this' references work)
attrs.put(referencename, referencefn);
}
if (body != null) {
if (method == null) {
method = "$lzc$" + "handle_" + event + unique;
}
Function fndef = new
Function(method,
//"#beginAttribute\n" +
args,
"\n#beginContent\n" +
"\n#pragma 'methodName=" + method + "'\n" +
"\n#pragma 'withThis'\n",
body + "\n#endContent",
src_loc);
// Add hander as a method
attrs.put(method, fndef);
}
// Put everything into the delegate list
delegateList.add(ScriptCompiler.quote(event));
delegateList.add(ScriptCompiler.quote(method));
if (reference != null) {
delegateList.add(ScriptCompiler.quote(referencename));
} else {
delegateList.add("null");
}
}
void addMethodElement(Element element) {
String name = element.getAttributeValue("name");
String event = element.getAttributeValue("event");
String args = CompilerUtils.attributeLocationDirective(element, "args") +
XMLUtils.getAttributeValue(element, "args", "");
String body = element.getText();
if ((name == null || !ScriptCompiler.isIdentifier(name)) &&
(event == null || !ScriptCompiler.isIdentifier(event))) {
env.warn(
/* (non-Javadoc)
* @i18n.test
* @org-mes="method needs a non-null name or event attribute"
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
NodeModel.class.getName(),"051018-832")
);
return;
}
if (name != null && sDeprecatedMethods.containsKey(name)) {
String oldName = name;
String newName = (String) sDeprecatedMethods.get(name);
name = newName;
env.warn(
/* (non-Javadoc)
* @i18n.test
* @org-mes=p[0] + " is deprecated. " + "This method will be compiled as <method name='" + p[1] + "' instead. " + "Please update your sources."
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
NodeModel.class.getName(),"051018-846", new Object[] {oldName, newName})
,element);
}
// TODO: Remove after 4.2
if (event != null) {
env.warn("The `event` property of methods is deprecated. Please update your source to use the `<handler>` tag.",
element);
String parent_name =
element.getParentElement().getAttributeValue("id");
if (parent_name == null) {
parent_name =
(name == null ?
CompilerUtils.attributeUniqueName(element, "handler") :
CompilerUtils.attributeUniqueName(element, "name"));
}
String reference = element.getAttributeValue("reference");
if (reference != null) {
reference = CompilerUtils.attributeLocationDirective(element, "reference") + reference;
}
addHandlerInternal(element, parent_name, event, name, args, body, reference);
return;
}
addMethodInternal(name, args, body, element);
}
void addMethodInternal(String name, String args, String body, Element element) {
String srcloc = CompilerUtils.sourceLocationDirective(element, true);
ClassModel superclassModel = getParentClassModel();
// Override will be required if there is an inherited method
// of the same name
boolean override =
// This gets methods from the schema, in particular, the
// LFC interface
superclassModel.getAttribute(name) != null ||
// This gets methods the compiler has added, in
// particular, setter methods
superclassModel.getMergedMethods().containsKey(name) ||
// And the user may know better than any of us
"true".equals(element.getAttributeValue("override"));
boolean isfinal = "true".equals(element.getAttributeValue("final"));
if (attrs.containsKey(name)) {
env.warn(
/* (non-Javadoc)
* @i18n.test
* @org-mes="an attribute or method named '" + p[0] + "' already is defined on " + p[1]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
NodeModel.class.getName(),"051018-922", new Object[] {name, getMessageName()})
,element);
}
boolean isclassdecl = ("class".equals(className) || "interface".equals(className) || "mixin".equals(className));
if (!override) {
// Just check method declarations on regular node.
// Method declarations inside of class definitions will be already checked elsewhere,
// in the call from ClassCompiler.updateSchema to schema.addElement
if (!isclassdecl) {
schema.checkInstanceMethodDeclaration(element, className, name, env);
}
}
String name_loc =
(name == null ?
CompilerUtils.attributeLocationDirective(element, "handler") :
CompilerUtils.attributeLocationDirective(element, "name"));
String adjectives = "";
// TODO [hqm 2008-03] we currently cannot put "override" or
// "final" on methods unless they are in a class
// declaration. We don't want to put them on instance method
if (override && isclassdecl) {
adjectives += " override";
}
if (isfinal && isclassdecl) {
adjectives += " final";
}
Function fndef = new
Function(name,
//"#beginAttribute\n" +
args,
"\n#beginContent\n" +
"\n#pragma 'methodName=" + name + "'\n" +
"\n#pragma 'withThis'\n",
body + "\n#endContent",
name_loc,
adjectives);
attrs.put(name, fndef);
}
// Pattern matcher for '$once{...}' style constraints
Pattern constraintPat = Pattern.compile("^\\s*\\$(\\w*)\\s*\\{(.*)\\}\\s*");
CompiledAttribute compileAttribute(
Element source, String name,
String value, Schema.Type type,
String when)
{
String parent_name = source.getAttributeValue("id");
if (parent_name == null) {
parent_name = CompilerUtils.attributeUniqueName(source, name);
}
String canonicalValue = null;
boolean warnOnDeprecatedConstraints = true;
if (value == null) {
throw new RuntimeException(
/* (non-Javadoc)
* @i18n.test
* @org-mes="value is null in " + p[0]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
NodeModel.class.getName(),"051018-956", new Object[] {source})
);
}
Matcher m = constraintPat.matcher(value);
// value.matches("\\s*['\"]\\S*['\"]\\s*")
if (value.matches("\\s*\\$\\s*\\(")) {
env.warn(
"The syntax '$(...)' is not valid, "
+ "you probably meant to use curly-braces instead '${...}'",
source);
} else if (m.matches()) {
// extract out $when{value}
when = m.group(1);
value = m.group(2);
// Expressions override any when value, default is
// constraint
if (when.equals("")) {
when = WHEN_ALWAYS;
}
} else if (type == ViewSchema.XML_LITERAL) {
value = "LzDataNode.stringToLzData("+value+")";
} else if (type == ViewSchema.COLOR_TYPE) {
if (when.equals(WHEN_IMMEDIATELY)) {
try {
value = "0x" +
Integer.toHexString(ViewSchema.parseColor(value));
} catch (ColorFormatException e) {
// Or just set when to WHEN_ONCE and fall
// through to TODO?
throw new CompilationError(source, name, e);
}
}
// TODO: [2003-05-02 ptw] Wrap non-constant colors in
// runtime parser
} else if (type == ViewSchema.CSS_TYPE) {
if (when.equals(WHEN_IMMEDIATELY)) {
try {
Map cssProperties = new CSSParser
(new AttributeStream(source, name, value)).Parse();
for (Iterator i2 = cssProperties.entrySet().iterator(); i2.hasNext(); ) {
Map.Entry entry = (Map.Entry) i2.next();
Object mv = entry.getValue();
if (mv instanceof String) {
entry.setValue(ScriptCompiler.quote((String) mv));
}
}
canonicalValue = ScriptCompiler.objectAsJavascript(cssProperties);
} catch (org.openlaszlo.css.ParseException e) {
// Or just set when to WHEN_ONCE and fall
// through to TODO?
throw new CompilationError(e);
} catch (org.openlaszlo.css.TokenMgrError e) {
// Or just set when to WHEN_ONCE and fall
// through to TODO?
throw new CompilationError(e);
}
}
// TODO: [2003-05-02 ptw] Wrap non-constant styles in
// runtime parser
} else if (type == ViewSchema.STRING_TYPE
|| type == ViewSchema.TOKEN_TYPE
|| type == ViewSchema.ID_TYPE
) {
// Immediate string attributes are auto-quoted
if (when.equals(WHEN_IMMEDIATELY)) {
value = ScriptCompiler.quote(value);
}
} else if ((type == ViewSchema.EXPRESSION_TYPE) || (type == ViewSchema.BOOLEAN_TYPE)) {
// No change currently, possibly analyze expressions
// and default non-constant to when="once" in the
// future
} else if (type == ViewSchema.INHERITABLE_BOOLEAN_TYPE) {
// change "inherit" to null and pass true/false through as expression
if ("inherit".equals(value)) {
value = "null";
} else if ("true".equals(value)) {
value = "true";
} else if ("false".equals(value)) {
value = "false";
} else {
// TODO [hqm 2007-0] i8nalize this message
env.warn("attribute '"+name+"' must have the value 'true', 'false', or 'inherit'",
element);
}
} else if (type == ViewSchema.NUMBER_TYPE) {
// No change currently, possibly analyze expressions
// and default non-constant to when="once" in the
// future
} else if (type == ViewSchema.NUMBER_EXPRESSION_TYPE ||
type == ViewSchema.SIZE_EXPRESSION_TYPE) {
// if it's a number that ends in percent:
if (value.trim().endsWith("%")) {
String numstr = value.trim();
numstr = numstr.substring(0, numstr.length() - 1);
try {
double scale = new Float(numstr).floatValue() / 100.0;
warnOnDeprecatedConstraints = false;
String referenceAttribute = name;
if (name.equals("x")) {
referenceAttribute = "width";
} else if (name.equals("y")) {
referenceAttribute = "height";
}
value = "immediateparent." + referenceAttribute;
if (scale != 1.0) {
// This special case doesn't change the
// semantics, but it generates shorter (since
// the sc doesn't fold constants) and more
// debuggable code
value += "\n * " + scale;
}
// fall through to the reference case
} catch (NumberFormatException e) {
// fall through
}
}
// if it's a literal, treat it the same as a number
try {
new Float(value); // for effect, to generate the exception
when = WHEN_IMMEDIATELY;
} catch (NumberFormatException e) {
// It's not a constant, unless when has been
// specified, default to a constraint
if (when.equals(WHEN_IMMEDIATELY)) {
if (warnOnDeprecatedConstraints) {
env.warn(
"Use " + name + "=\"${" + value + "}\" instead.",
element);
}
when = WHEN_ALWAYS;
}
}
} else if (type == ViewSchema.EVENT_HANDLER_TYPE) {
// Someone said <attribute name="..." ... /> instead of
// <event name="..." />
throw new CompilationError(element, name,
new Throwable ("'" + name + "' is an event and may not be redeclared as an attribute"));
} else if (type == ViewSchema.REFERENCE_TYPE) {
// type="reference" is defined to imply when="once"
// since reference expressions are unlikely to
// evaluate correctly at when="immediate" time
if (when.equals(WHEN_IMMEDIATELY)) {
when = WHEN_ONCE;
}
} else if (type == ViewSchema.METHOD_TYPE) {
// methods are emitted elsewhere
} else {
throw new RuntimeException("unknown schema datatype " + type);
}
if (canonicalValue == null)
canonicalValue = value;
return new CompiledAttribute(name, type, canonicalValue, when, source, env);
}
static final Schema.Type EVENT_TYPE = Schema.newType("LzEvent");
/* Handle the <event> tag
* example: <event name="onfoobar"/>
*/
void addEventElement(Element element) {
String name;
try {
name = ElementCompiler.requireIdentifierAttributeValue(element, "name");
} catch (MissingAttributeException e) {
throw new CompilationError(
/* (non-Javadoc)
* @i18n.test
* @org-mes="'name' is a required attribute of <" + p[0] + "> and must be a valid identifier"
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
NodeModel.class.getName(),"051018-1157", new Object[] {element.getName()})
, element);
}
if (events.containsKey(name)) {
env.warn(
/* (non-Javadoc)
* @i18n.test
* @org-mes="redefining event '" + p[0] + "' which has already been defined on " + p[1]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
NodeModel.class.getName(),"051018-694", new Object[] {name, getMessageName()})
,element);
}
// An event is really just an attribute with an implicit
// default (sentinal) value
CompiledAttribute cattr =
new CompiledAttribute(name, EVENT_TYPE, "LzDeclaredEvent", WHEN_IMMEDIATELY, element, env);
addAttribute(cattr, name, attrs, events, references, classAttrs, styles);
}
void addAttributeElement(Element element) {
String name;
try {
name = ElementCompiler.requireIdentifierAttributeValue(element, "name");
} catch (MissingAttributeException e) {
throw new CompilationError(
/* (non-Javadoc)
* @i18n.test
* @org-mes="'name' is a required attribute of <" + p[0] + "> and must be a valid identifier"
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
NodeModel.class.getName(),"051018-1157", new Object[] {element.getName()})
, element);
}
String value = element.getAttributeValue("value");
String when = element.getAttributeValue("when");
String typestr = element.getAttributeValue("type");
Element parent = element.getParentElement();
String parent_name = parent.getAttributeValue("id");
if (parent_name == null) {
parent_name = CompilerUtils.attributeUniqueName(element, name);
}
// Default when according to parent
if (when == null) {
when = this.getAttributeValueDefault(
name, "when", WHEN_IMMEDIATELY);
}
Schema.Type type = null;
Schema.Type parenttype = null;
AttributeSpec parentAttrSpec = schema.getAttributeSpec(parent.getName(), name);
boolean forceOverride = parentAttrSpec != null && "false".equals(parentAttrSpec.isfinal);
try {
if ("class".equals(className) || "interface".equals(className)) {
parenttype = getAttributeTypeInfoFromSuperclass(parent, name);
} else {
parenttype = schema.getAttributeType(parent, name);
}
} catch (UnknownAttributeException e) {
// If attribute type is not defined on parent, leave
// parenttype null. The user can define it however they
// like.
}
if (typestr == null) {
// Did user supply an explicit attribute type?
// No. Default to parent type if there is one, else
// EXPRESSION type.
if (parenttype == null) {
type = ViewSchema.EXPRESSION_TYPE;
} else {
type = parenttype;
}
} else {
// parse attribute type and compare to parent type
type = schema.getTypeForName(typestr);
if (type == null) {
throw new CompilationError(
/* (non-Javadoc)
* @i18n.test
* @org-mes="unknown attribute type: " + p[0]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
NodeModel.class.getName(),"051018-1211", new Object[] {typestr})
, element);
}
// If we are trying to declare the attribute with a
// conflicting type to the parent, throw an error
if (!forceOverride && parenttype != null && type != parenttype) {
env.warn(
new CompilationError(
element,
name,
new Throwable(
/* (non-Javadoc)
* @i18n.test
* @org-mes="In element '" + p[0] + "' attribute '" + p[1] + "' with type '" + p[2] + "' is overriding parent class attribute with same name but different type: " + p[3]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
NodeModel.class.getName(),"051018-1227", new Object[] {parent.getName(), name, type.toString(), parenttype.toString()}))
)
);
}
}
// Warn if we are overidding a method, handler, or other function
if (!forceOverride &&
(parenttype == schema.METHOD_TYPE ||
parenttype == schema.EVENT_HANDLER_TYPE ||
parenttype == schema.SETTER_TYPE ||
parenttype == schema.REFERENCE_TYPE)) {
env.warn( "In element '" + parent.getName()
+ "' attribute '" + name
+ "' is overriding parent class attribute which has the same name but type: "
+ parenttype.toString(),
element);
}
CompiledAttribute cattr;
// Value may be null if attribute is only declared
if (value != null) {
cattr = compileAttribute(element, name, value, type, when);
} else {
String srcloc = CompilerUtils.sourceLocationDirective(element, true);
cattr = new CompiledAttribute(name, type, null, WHEN_IMMEDIATELY, element, env);
}
addAttribute(cattr, name, attrs, events, references, classAttrs, styles);
// Add entry for attribute setter function
String setter = element.getAttributeValue("setter");
if (setter != null) {
// By convention 'anonymous' setters are put in the 'lzc'
// namespace with the name set_<property name>
// NOTE: LzNode#applyArgs and #setAttribute depend on this
// convention to find setters
String settername = "$lzc$" + "set_" + name;
addMethodInternal(
settername,
// the lone argument to a setter is named after the
// attribute
name,
// The body of the setter method
setter,
element);
// This is just for nice error messages
if (setters.get(name) != null) {
env.warn(
"a setter for attribute named '"+name+
"' is already defined on "+getMessageName(),
element);
}
setters.put(name, ScriptCompiler.quote(settername));
}
}
/* Handle a <data> tag.
* If there is more than one immediate child data node at the top level, signal a warning.
*/
void addLiteralDataElement(Element element) {
String name = element.getAttributeValue("name");
if (name == null) {
name = "initialdata";
}
boolean trimWhitespace = "true".equals(element.getAttributeValue("trimwhitespace"));
String xmlcontent = getDatasetContent(element, env, trimWhitespace);
Element parent = element.getParentElement();
CompiledAttribute cattr = compileAttribute(element,
name,
xmlcontent,
ViewSchema.XML_LITERAL,
WHEN_IMMEDIATELY);
addAttribute(cattr, name, attrs, events, references, classAttrs, styles);
}
boolean hasAttribute(String name) {
return attrs.containsKey(name);
}
void removeAttribute(String name) {
attrs.remove(name);
}
void setAttribute(String name, Object value) {
attrs.put(name, value);
}
boolean hasClassAttribute(String name) {
return classAttrs.containsKey(name);
}
void removeClassAttribute(String name) {
classAttrs.remove(name);
}
void setClassAttribute(String name, Object value) {
classAttrs.put(name, value);
}
void addText() {
if (schema.hasHTMLContent(element)) {
String text = TextCompiler.getHTMLContent(element);
if (text.length() != 0) {
if (!attrs.containsKey("text")) {
attrs.put("text", ScriptCompiler.quote(text));
}
}
} else if (schema.hasTextContent(element)) {
String text;
// The current inputtext component doesn't understand
// HTML, but we'd like to have some way to enter
// linebreaks in the source.
text = TextCompiler.getInputText(element);
if (text.length() != 0) {
if (!attrs.containsKey("text")) {
attrs.put("text", ScriptCompiler.quote(text));
}
}
}
}
void updateAttrs() {
// Only used for checking multiple definitions now
// if (!setters.isEmpty()) {
// attrs.put("$setters", setters);
if (!delegateList.isEmpty()) {
attrs.put("$delegates", delegateList);
}
if (!references.isEmpty()) {
assert false : "There should not be any $refs";
}
if (datapath != null) {
attrs.put("$datapath", datapath.asMap());
// If we've got an explicit datapath value, we have to
// null out the "datapath" attribute with the magic
// LzNode._ignoreAttribute value, so it doesn't get
// overridden by an inherited value from the class.
attrs.put("datapath", "LzNode._ignoreAttribute");
}
if (!styles.isEmpty()) {
assert false : "There should not be any $styles";
}
}
Map getAttrs() {
updateAttrs();
return attrs;
}
boolean hasMethods() {
for (Iterator i = attrs.values().iterator(); i.hasNext(); ) {
if (i.next() instanceof Function) { return true; }
}
return false;
}
Map getClassAttrs() {
return classAttrs;
}
Map getSetters() {
return setters;
}
Map asMap() {
updateAttrs();
assert classAttrs.isEmpty();
Map map = new LinkedHashMap();
String tagName = className;
if (hasMethods()) {
// If there are methods, make a class
String name = id;
if (name == null) {
name = CompilerUtils.attributeUniqueName(element, "class");
}
// Update tagname to our custom class
tagName = className + "_" + name;
ClassModel classModel = new ClassModel(tagName, parentClassModel, schema, element);
classModel.setNodeModel(this);
classModel.emitClassDeclaration(env);
} else {
// Node as map just wants to see all the attrs, so clean out
// the binding markers
Map inits = new LinkedHashMap();
for (Iterator i = attrs.entrySet().iterator(); i.hasNext(); ) {
Map.Entry entry = (Map.Entry) i.next();
String key = (String) entry.getKey();
Object value = entry.getValue();
if (! (value instanceof NodeModel.BindingExpr)) {
inits.put(key, value);
} else {
inits.put(key, ((NodeModel.BindingExpr)value).getExpr());
}
}
if (!inits.isEmpty()) {
map.put("attrs", inits);
}
if (!children.isEmpty()) {
map.put("children", childrenMaps());
}
}
// The tag to instantiate
// TODO: [2008-04-01 ptw] we could have a flag day and put the
// class here, eliminating having to go through the
// constructor map...
map.put("name", ScriptCompiler.quote(tagName));
if (id != null) {
// NOTE: [2008-04-01 ptw] May be obsolete?
map.put("id", ScriptCompiler.quote(id));
}
return map;
}
void assignClassRoot(int depth) {
if (! parentClassModel.isSubclassOf(schema.getClassModel("state"))) { depth++; }
Integer d = new Integer(depth);
for (Iterator i = children.iterator(); i.hasNext(); ) {
NodeModel child = (NodeModel)i.next();
child.attrs.put("$classrootdepth", d);
child.assignClassRoot(depth);
}
}
List childrenMaps() {
List childMaps = new Vector(children.size());
for (Iterator iter = children.iterator(); iter.hasNext(); )
childMaps.add(((NodeModel) iter.next()).asMap());
// TODO: [2006-09-28 ptw] There must be a better way. See
// comment in LFC where __LZUserClassPlacementObject is
// inserted in ConstructorMap regarding the wart this is. You
// need some way to not set defaultplacement until the
// class-defined children are instantiated, only the
// instance-defined children should get default placement.
// For now this is done by inserting this sentinel in the
// child nodes...
if (className.equals("class") && hasAttribute("defaultplacement")) {
LinkedHashMap dummy = new LinkedHashMap();
dummy.put("name", ScriptCompiler.quote("__LZUserClassPlacementObject"));
dummy.put("attrs", attrs.get("defaultplacement"));
removeAttribute("defaultplacement");
childMaps.add(dummy);
}
return childMaps;
}
/** Expand eligible instances by replacing the instance by the
* merge of its class definition with the instance content
* (attributes and children). An eligible instance is an instance
* of a compile-time class, that doesn't contain any merge
* stoppers. If the class and the instance contain a member with
* the same name, this is a merge stopper. In the future, this
* restriction may be relaxed, but will probably always include
* the case where a class and instance have a member with the same
* name and the instance name calls a superclass method. */
NodeModel expandClassDefinitions() {
NodeModel model = this;
while (true) {
ClassModel classModel = schema.getClassModel(model.className);
if (classModel == null)
break;
if (classModel.getSuperclassName() == null)
break;
if (!classModel.getInline())
break;
model = classModel.applyClass(model);
// Iterate to allow for the original classes superclass to
// be expanded as well.
}
// Recurse. Make a copy so we can replace the child list.
// TODO [2004-0604]: As an optimization, only do this if one
// of the children changed.
model = (NodeModel) model.clone();
for (ListIterator iter = model.children.listIterator();
iter.hasNext(); ) {
NodeModel child = (NodeModel) iter.next();
iter.set(child.expandClassDefinitions());
}
return model;
}
/** Replace members of this with like-named members of source. */
void updateMembers(NodeModel source) {
final String OPTIONS_ATTR_NAME = "options";
// FIXME [2004-06-04]: only compare events with the same reference
if (CollectionUtils.containsAny(
events.keySet(), source.events.keySet())) {
Collection sharedEvents = CollectionUtils.intersection(
events.keySet(), source.events.keySet());
throw new CompilationError(
/* (non-Javadoc)
* @i18n.test
* @org-mes="Both the class and the instance or subclass define the " + p[0] + p[1]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
NodeModel.class.getName(),"051018-1388", new Object[] {new ChoiceFormat("1#event |1<events ").format(sharedEvents.size()), new ListFormat("and").format(sharedEvents)})
);
}
// Check for duplicate methods. Collect all the keys that name
// a Function in both the source and target.
List sharedMethods = new Vector();
for (Iterator iter = attrs.keySet().iterator();
iter.hasNext(); ) {
String key = (String) iter.next();
if (attrs.get(key) instanceof Function &&
source.attrs.get(key) instanceof Function)
sharedMethods.add(key);
}
if (!sharedMethods.isEmpty())
throw new CompilationError(
/* (non-Javadoc)
* @i18n.test
* @org-mes="Both the class and the instance or subclass define the method" + p[0] + p[1]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
NodeModel.class.getName(),"051018-1409", new Object[] {new ChoiceFormat("1# |1<s ").format(sharedMethods.size()), new ListFormat("and").format(sharedMethods)})
);
// Check for attributes that have a value in this and
// a setter in the source. These can't be merged.
Collection overriddenAttributes = CollectionUtils.intersection(
attrs.keySet(), source.setters.keySet());
if (!overriddenAttributes.isEmpty())
throw new CompilationError(
/* (non-Javadoc)
* @i18n.test
* @org-mes="A class that defines a value can't be inlined against a " + "subclass or instance that defines a setter. The following " + p[0] + " this condition: " + p[1]
*/
org.openlaszlo.i18n.LaszloMessages.getMessage(
NodeModel.class.getName(),"051018-1422", new Object[] {new ChoiceFormat("1#attribute violates|1<attributes violate").format(overriddenAttributes.size()), new ListFormat("and").format(overriddenAttributes)})
);
// Do the actual merge.
id = source.id;
if (source.initstage != null)
initstage = source.initstage;
Object options = attrs.get(OPTIONS_ATTR_NAME);
Object sourceOptions = source.attrs.get(OPTIONS_ATTR_NAME);
attrs.putAll(source.attrs);
if (options instanceof Map && sourceOptions instanceof Map) {
// System.err.println(options);
// System.err.println(sourceOptions);
Map newOptions = new HashMap((Map) options);
newOptions.putAll((Map) sourceOptions);
attrs.put(OPTIONS_ATTR_NAME, newOptions);
}
delegates.putAll(source.delegates);
events.putAll(source.events);
references.putAll(source.references);
classAttrs.putAll(source.classAttrs);
setters.putAll(source.setters);
styles.putAll(source.styles);
delegateList.addAll(source.delegateList);
// TBD: warn on children that share a name?
// TBD: update the node count
children.addAll(source.children);
}
} |
package edu.wustl.catissuecore.bizlogic;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import org.hibernate.Session;
import edu.common.dynamicextensions.util.global.Variables;
import edu.wustl.catissuecore.domain.CancerResearchGroup;
import edu.wustl.catissuecore.domain.CollectionProtocol;
import edu.wustl.catissuecore.domain.Department;
import edu.wustl.catissuecore.domain.Institution;
import edu.wustl.catissuecore.domain.Password;
import edu.wustl.catissuecore.domain.Site;
import edu.wustl.catissuecore.domain.User;
import edu.wustl.catissuecore.dto.UserDTO;
import edu.wustl.catissuecore.multiRepository.bean.SiteUserRolePrivilegeBean;
import edu.wustl.catissuecore.util.ApiSearchUtil;
import edu.wustl.catissuecore.util.EmailHandler;
import edu.wustl.catissuecore.util.Roles;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.catissuecore.util.global.Utility;
import edu.wustl.common.actionForm.IValueObject;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.beans.SecurityDataBean;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.bizlogic.DefaultBizLogic;
import edu.wustl.common.cde.CDEManager;
import edu.wustl.common.dao.AbstractDAO;
import edu.wustl.common.dao.DAO;
import edu.wustl.common.dao.DAOFactory;
import edu.wustl.common.dao.HibernateDAO;
import edu.wustl.common.domain.AbstractDomainObject;
import edu.wustl.common.exception.BizLogicException;
import edu.wustl.common.exceptionformatter.DefaultExceptionFormatter;
import edu.wustl.common.security.PrivilegeCache;
import edu.wustl.common.security.PrivilegeManager;
import edu.wustl.common.security.PrivilegeUtility;
import edu.wustl.common.security.SecurityManager;
import edu.wustl.common.security.exceptions.PasswordEncryptionException;
import edu.wustl.common.security.exceptions.SMException;
import edu.wustl.common.security.exceptions.UserNotAuthorizedException;
import edu.wustl.common.util.XMLPropertyHandler;
import edu.wustl.common.util.dbManager.DAOException;
import edu.wustl.common.util.dbManager.DBUtil;
import edu.wustl.common.util.global.ApplicationProperties;
import edu.wustl.common.util.global.PasswordManager;
import edu.wustl.common.util.global.Validator;
import edu.wustl.common.util.logger.Logger;
import gov.nih.nci.security.authorization.domainobjects.ProtectionElement;
import gov.nih.nci.security.authorization.domainobjects.ProtectionGroup;
import gov.nih.nci.security.authorization.domainobjects.Role;
import gov.nih.nci.security.dao.ProtectionElementSearchCriteria;
import gov.nih.nci.security.exceptions.CSException;
/**
* UserBizLogic is used to add user information into the database using Hibernate.
* @author kapil_kaveeshwar
*/
public class UserBizLogic extends DefaultBizLogic
{
public static final int FAIL_SAME_AS_LAST_N = 8;
public static final int FAIL_FIRST_LOGIN = 9;
public static final int FAIL_EXPIRE = 10;
public static final int FAIL_CHANGED_WITHIN_SOME_DAY = 11;
public static final int FAIL_SAME_NAME_SURNAME_EMAIL = 12;
public static final int FAIL_PASSWORD_EXPIRED = 13;
public static final int SUCCESS = 0;
/**
* Saves the user object in the database.
* @param obj The user object to be saved.
* @param session The session in which the object is saved.
* @throws DAOException
*/
protected void insert(Object obj, DAO dao, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException
{
User user = null;
Map<String,SiteUserRolePrivilegeBean> userRowIdMap =new HashMap<String, SiteUserRolePrivilegeBean>();
if(obj instanceof UserDTO)
{
user = ((UserDTO)obj).getUser();
userRowIdMap = ((UserDTO)obj).getUserRowIdBeanMap();
}
else
{
user = (User) obj;
}
if (user.getRoleId() != null && !user.getRoleId().equalsIgnoreCase("-1") && !user.getRoleId().equalsIgnoreCase("0"))
{
if (userRowIdMap == null || userRowIdMap.isEmpty() && user.getSiteCollection() != null && !user.getSiteCollection().isEmpty())
{
List<NameValueBean> list = new AssignPrivilegePageBizLogic().getActionsForSelRole(user.getRoleId());
NameValueBean roleBean = new NameValueBean();
try
{
Vector<Role> roleList = SecurityManager.getInstance(this.getClass()).getRoles();
roleBean.setValue(user.getRoleId());
for (Role role : roleList)
{
if (role.getId().toString().equalsIgnoreCase(user.getRoleId()))
{
roleBean.setName(role.getName());
break;
}
}
}
catch (SMException e)
{
}
int i = 0;
userRowIdMap = new HashMap<String, SiteUserRolePrivilegeBean>();
for (Site site : user.getSiteCollection())
{
List <Site> siteList = new ArrayList<Site>();
siteList.add(site);
SiteUserRolePrivilegeBean siteUserRolePrivilegeBean = new SiteUserRolePrivilegeBean();
siteUserRolePrivilegeBean.setAllCPChecked(true);
siteUserRolePrivilegeBean.setPrivileges(list);
siteUserRolePrivilegeBean.setRole(roleBean);
siteUserRolePrivilegeBean.setSiteList(siteList);
userRowIdMap.put(new Integer(i).toString(),siteUserRolePrivilegeBean);
i++;
}
}
}
gov.nih.nci.security.authorization.domainobjects.User csmUser = new gov.nih.nci.security.authorization.domainobjects.User();
try
{
Object object = dao.retrieve(Department.class.getName(), user.getDepartment().getId());
Department department = null;
if (object != null)
{
department = (Department) object;
}
object = dao.retrieve(Institution.class.getName(), user.getInstitution().getId());
Institution institution = null;
if (object != null)
{
institution = (Institution) object;
}
object = dao.retrieve(CancerResearchGroup.class.getName(), user.getCancerResearchGroup().getId());
CancerResearchGroup cancerResearchGroup = null;
if (object != null)
{
cancerResearchGroup = (CancerResearchGroup) object;
}
user.setDepartment(department);
user.setInstitution(institution);
user.setCancerResearchGroup(cancerResearchGroup);
String generatedPassword = PasswordManager.generatePassword();
// If the page is of signup user don't create the csm user.
if (user.getPageOf().equals(Constants.PAGEOF_SIGNUP) == false)
{
csmUser.setLoginName(user.getLoginName());
csmUser.setLastName(user.getLastName());
csmUser.setFirstName(user.getFirstName());
csmUser.setEmailId(user.getEmailAddress());
csmUser.setStartDate(user.getStartDate());
csmUser.setPassword(generatedPassword);
SecurityManager.getInstance(UserBizLogic.class).createUser(csmUser);
// if (user.getAdminuser())
// securityManager.assignRoleToUser(csmUser.getUserId().toString(),"1");
if (user.getRoleId() != null)
{
if (user.getRoleId().equalsIgnoreCase(Constants.ADMIN_USER))
{
user.setRoleId(Constants.NON_ADMIN_USER);
}
if (user.getRoleId().equalsIgnoreCase(Constants.SUPER_ADMIN_USER))
{
user.setRoleId(Constants.ADMIN_USER);
}
SecurityManager.getInstance(UserBizLogic.class).assignRoleToUser(csmUser.getUserId().toString(), user.getRoleId());
}
user.setCsmUserId(csmUser.getUserId());
// user.setPassword(csmUser.getPassword());
//Add password of user in password table.Updated by Supriya Dankh
Password password = new Password();
ApiSearchUtil.setPasswordDefault(password);
//End:- Change for API Search
password.setUser(user);
password.setPassword(PasswordManager.encrypt(generatedPassword));
password.setUpdateDate(new Date());
user.getPasswordCollection().add(password);
Logger.out.debug("password stored in passwore table");
// user.setPassword(csmUser.getPassword());
}
/**
* First time login is always set to true when a new user is created
*/
user.setFirstTimeLogin(new Boolean(true));
// Create address and the user in catissue tables.
dao.insert(user.getAddress(), sessionDataBean, true, false);
if(userRowIdMap != null && !userRowIdMap.isEmpty())
{
updateUserDetails(user,userRowIdMap);
}
dao.insert(user, sessionDataBean, true, false);
Set protectionObjects = new HashSet();
protectionObjects.add(user);
EmailHandler emailHandler = new EmailHandler();
// Send the user registration email to user and the administrator.
if (Constants.PAGEOF_SIGNUP.equals(user.getPageOf()))
{
//SecurityManager.getInstance(this.getClass()).insertAuthorizationData(null, protectionObjects, null);
emailHandler.sendUserSignUpEmail(user);
}
else
// Send the user creation email to user and the administrator.
{
// SecurityManager.getInstance(this.getClass()).insertAuthorizationData(getAuthorizationData(user), protectionObjects, null);
PrivilegeManager privilegeManager = PrivilegeManager.getInstance();
privilegeManager.insertAuthorizationData(getAuthorizationData(user, userRowIdMap),
protectionObjects, null, user.getObjectId());
emailHandler.sendApprovalEmail(user);
}
}
catch (DAOException daoExp)
{
Logger.out.debug(daoExp.getMessage(), daoExp);
deleteCSMUser(csmUser);
throw daoExp;
}
catch (SMException e)
{
// added to format constrainviolation message
deleteCSMUser(csmUser);
throw handleSMException(e);
}
catch (PasswordEncryptionException e)
{
Logger.out.debug(e.getMessage(), e);
deleteCSMUser(csmUser);
throw new DAOException(e.getMessage(), e);
}
}
/**
* Deletes the csm user from the csm user table.
* @param csmUser The csm user to be deleted.
* @throws DAOException
*/
public void deleteCSMUser(gov.nih.nci.security.authorization.domainobjects.User csmUser) throws DAOException
{
try
{
if (csmUser.getUserId() != null)
{
SecurityManager.getInstance(ApproveUserBizLogic.class).removeUser(csmUser.getUserId().toString());
}
}
catch (SMException smExp)
{
throw handleSMException(smExp);
}
}
/**
* This method returns collection of UserGroupRoleProtectionGroup objects that speciefies the
* user group protection group linkage through a role. It also specifies the groups the protection
* elements returned by this class should be added to.
* @return
*/
private Vector getAuthorizationData(AbstractDomainObject obj, Map<String,SiteUserRolePrivilegeBean> userRowIdMap) throws SMException
{
Vector authorizationData = new Vector();
Set group = new HashSet();
User aUser = (User) obj;
String userId = String.valueOf(aUser.getCsmUserId());
gov.nih.nci.security.authorization.domainobjects.User user = SecurityManager.getInstance(this.getClass()).getUserById(userId);
Logger.out.debug(" User: " + user.getLoginName());
group.add(user);
// Protection group of User
String protectionGroupName = Constants.getUserPGName(aUser.getId());
SecurityDataBean userGroupRoleProtectionGroupBean = new SecurityDataBean();
userGroupRoleProtectionGroupBean.setUser(userId);
userGroupRoleProtectionGroupBean.setRoleName(Roles.UPDATE_ONLY);
userGroupRoleProtectionGroupBean.setGroupName(Constants.getUserGroupName(aUser.getId()));
userGroupRoleProtectionGroupBean.setProtectionGroupName(protectionGroupName);
userGroupRoleProtectionGroupBean.setGroup(group);
authorizationData.add(userGroupRoleProtectionGroupBean);
Logger.out.debug(authorizationData.toString());
if(userRowIdMap !=null)
{
insertCPSitePrivileges(aUser, authorizationData, userRowIdMap);
}
return authorizationData;
}
private void insertCPSitePrivileges(User user1, Vector authorizationData, Map<String, SiteUserRolePrivilegeBean> userRowIdMap)
{
if(userRowIdMap == null || userRowIdMap.isEmpty())
{
return;
}
Map<String, SiteUserRolePrivilegeBean> cpPrivilegeMap = new HashMap<String, SiteUserRolePrivilegeBean>();
Map<String, SiteUserRolePrivilegeBean> sitePrivilegeMap = new HashMap<String, SiteUserRolePrivilegeBean>();
Object[] mapKeys = userRowIdMap.keySet().toArray();
for(Object mapKey : mapKeys)
{
String key = mapKey.toString();
SiteUserRolePrivilegeBean siteUserRolePrivilegeBean = userRowIdMap.get(key);
if(siteUserRolePrivilegeBean.isAllCPChecked())
{
Map<String, SiteUserRolePrivilegeBean> map = Utility.splitBeanData(siteUserRolePrivilegeBean);
SiteUserRolePrivilegeBean bean1 = map.get("SITE");
SiteUserRolePrivilegeBean bean2 = map.get("CP");
userRowIdMap.remove(key);
userRowIdMap.put(key, bean1);
userRowIdMap.put(key+"All_CurrentnFuture_CPs", bean2);
}
}
distributeMapData(userRowIdMap, cpPrivilegeMap, sitePrivilegeMap);
/* For SITE Privileges Purpose */
insertSitePrivileges(user1, authorizationData, sitePrivilegeMap);
/* For CP Privileges Purpose */
insertCPPrivileges(user1, authorizationData, cpPrivilegeMap);
/* Common for both */
//updateUserDetails(user1, userRowIdMap);
}
private void updateUserDetails(User user1, Map<String, SiteUserRolePrivilegeBean> userRowIdMap)
{
Set<Site> siteCollection = new HashSet<Site>();
Set<CollectionProtocol> cpCollection = new HashSet<CollectionProtocol>();
for (Iterator<String> mapItr = userRowIdMap.keySet().iterator(); mapItr.hasNext(); )
{
String key = mapItr.next();
SiteUserRolePrivilegeBean siteUserRolePrivilegeBean = userRowIdMap.get(key);
CollectionProtocol cp = siteUserRolePrivilegeBean.getCollectionProtocol();
if(cp != null && !siteUserRolePrivilegeBean.isRowDeleted())
{
cpCollection.add(cp);
}
List<Site> siteList = null;
if(!siteUserRolePrivilegeBean.isRowDeleted())
{
siteList = siteUserRolePrivilegeBean.getSiteList();
if(siteList != null && !siteList.isEmpty())
{
for(Site site : siteList)
{
boolean isPresent = false;
for (Site site1 : siteCollection)
{
if (site1.getId().equals(site.getId()))
{
isPresent = true;
}
}
if(!isPresent)
{
siteCollection.add(site);
}
}
}
}
}
user1.getSiteCollection().clear();
user1.getSiteCollection().addAll(siteCollection);
user1.getAssignedProtocolCollection().clear();
user1.getAssignedProtocolCollection().addAll(cpCollection);
}
private void insertSitePrivileges(User user1, Vector authorizationData, Map<String, SiteUserRolePrivilegeBean> sitePrivilegeMap)
{
String roleName = "";
for (Iterator<String> mapItr = sitePrivilegeMap.keySet().iterator(); mapItr.hasNext(); )
{
try
{
String key = mapItr.next();
SiteUserRolePrivilegeBean siteUserRolePrivilegeBean = sitePrivilegeMap.get(key);
if(siteUserRolePrivilegeBean.isRowDeleted())
{
Utility.processDeletedPrivileges(siteUserRolePrivilegeBean);
}
else if(siteUserRolePrivilegeBean.isRowEdited())
{
Site site = siteUserRolePrivilegeBean.getSiteList().get(0);
String defaultRole = siteUserRolePrivilegeBean.getRole().getValue();
if (defaultRole != null && (defaultRole.equalsIgnoreCase("0") || defaultRole.equalsIgnoreCase("-1")))
{
roleName = Constants.getSiteRoleName(site.getId(), user1.getCsmUserId(), defaultRole);
} else
{
roleName = siteUserRolePrivilegeBean.getRole().getName();
}
Set<String> privileges = new HashSet<String>();
List<NameValueBean> privilegeList = siteUserRolePrivilegeBean.getPrivileges();
for(NameValueBean privilege : privilegeList)
{
privileges.add(privilege.getValue());
}
PrivilegeManager.getInstance().createRole(roleName,
privileges);
String userId = String.valueOf(user1.getCsmUserId());
gov.nih.nci.security.authorization.domainobjects.User csmUser = null;
csmUser = getUserByID(userId);
HashSet<gov.nih.nci.security.authorization.domainobjects.User> group = new HashSet<gov.nih.nci.security.authorization.domainobjects.User>();
group.add(csmUser);
String protectionGroupName = new String(Constants
.getSitePGName(site.getId()));
createProtectionGroup(protectionGroupName, site, false);
SecurityDataBean userGroupRoleProtectionGroupBean = new SecurityDataBean();
userGroupRoleProtectionGroupBean.setUser("");
userGroupRoleProtectionGroupBean.setRoleName(roleName);
userGroupRoleProtectionGroupBean.setGroupName(Constants.getSiteUserGroupName(site.getId(), user1.getCsmUserId()));
userGroupRoleProtectionGroupBean.setProtectionGroupName(protectionGroupName);
userGroupRoleProtectionGroupBean.setGroup(group);
authorizationData.add(userGroupRoleProtectionGroupBean);
}
}
catch (CSException e)
{
Logger.out.error(e.getMessage(), e);
}
catch (SMException e)
{
Logger.out.error(e.getMessage(), e);
}
}
}
private void insertCPPrivileges(User user1, Vector authorizationData, Map<String, SiteUserRolePrivilegeBean> cpPrivilegeMap)
{
String roleName = "";
String protectionGroupName = "";
for (Iterator<String> mapItr = cpPrivilegeMap.keySet().iterator(); mapItr.hasNext(); )
{
try
{
SecurityDataBean userGroupRoleProtectionGroupBean = new SecurityDataBean();
String key = mapItr.next();
SiteUserRolePrivilegeBean siteUserRolePrivilegeBean = cpPrivilegeMap.get(key);
if(siteUserRolePrivilegeBean.isRowDeleted())
{
Utility.processDeletedPrivileges(siteUserRolePrivilegeBean);
}
else if(siteUserRolePrivilegeBean.isRowEdited())
{
// Case for 'All Current & Future CP's selected
if(siteUserRolePrivilegeBean.isAllCPChecked() == true)
{
String defaultRole = siteUserRolePrivilegeBean.getRole().getValue();
Site site = siteUserRolePrivilegeBean.getSiteList().get(0);
if (defaultRole != null && (defaultRole.equalsIgnoreCase("-1") || defaultRole.equalsIgnoreCase("0") || defaultRole.equalsIgnoreCase("7")))
{
roleName = Constants.getCurrentAndFutureRoleName(site.getId(), user1.getCsmUserId(), defaultRole);
} else
{
roleName = siteUserRolePrivilegeBean.getRole().getName();
}
protectionGroupName = Constants.getCurrentAndFuturePGAndPEName(site.getId());
createProtectionGroup(protectionGroupName, site, true);
userGroupRoleProtectionGroupBean.setGroupName(Constants.getSiteUserGroupName(site.getId(), user1.getCsmUserId()));
}
else
{
CollectionProtocol cp = siteUserRolePrivilegeBean.getCollectionProtocol();
String defaultRole = siteUserRolePrivilegeBean.getRole().getValue();
if (defaultRole != null && (defaultRole.equalsIgnoreCase("0") || defaultRole.equalsIgnoreCase("-1") || defaultRole.equalsIgnoreCase("7")))
{
roleName = Constants.getCPRoleName(cp.getId(), user1.getCsmUserId(), defaultRole);
}
else
{
roleName = siteUserRolePrivilegeBean.getRole().getName();
}
protectionGroupName = Constants.getCollectionProtocolPGName(cp.getId());
createProtectionGroup(protectionGroupName, cp, false);
userGroupRoleProtectionGroupBean.setGroupName(Constants.getCPUserGroupName(cp.getId(), user1.getCsmUserId()));
}
Set<String> privileges = new HashSet<String>();
List<NameValueBean> privilegeList = siteUserRolePrivilegeBean.getPrivileges();
for(NameValueBean privilege : privilegeList)
{
privileges.add(privilege.getValue());
}
PrivilegeManager.getInstance().createRole(roleName,
privileges);
String userId = String.valueOf(user1.getCsmUserId());
gov.nih.nci.security.authorization.domainobjects.User csmUser = getUserByID(userId);
HashSet<gov.nih.nci.security.authorization.domainobjects.User> group = new HashSet<gov.nih.nci.security.authorization.domainobjects.User>();
group.add(csmUser);
userGroupRoleProtectionGroupBean.setUser("");
userGroupRoleProtectionGroupBean.setRoleName(roleName);
userGroupRoleProtectionGroupBean.setProtectionGroupName(protectionGroupName);
userGroupRoleProtectionGroupBean.setGroup(group);
authorizationData.add(userGroupRoleProtectionGroupBean);
}
}
catch (CSException e)
{
Logger.out.error(e.getMessage(), e);
}
catch (SMException e)
{
Logger.out.error(e.getMessage(), e);
}
}
}
private void createProtectionGroup(String protectionGroupName, AbstractDomainObject obj, boolean isAllCPChecked)
{
ProtectionElement pe = new ProtectionElement();
Set<ProtectionElement> peSet = new HashSet<ProtectionElement>();
List<ProtectionElement> peList = new ArrayList<ProtectionElement>();
PrivilegeUtility privilegeUtility = new PrivilegeUtility();
try
{
if(isAllCPChecked)
{
pe.setObjectId(Constants.getCurrentAndFuturePGAndPEName(obj.getId()));
pe.setProtectionElementName(Constants.getCurrentAndFuturePGAndPEName(obj.getId()));
pe.setProtectionElementDescription("For All Current & Future CP's for Site with Id "+obj.getId().toString());
pe.setApplication(privilegeUtility.getApplication(SecurityManager.APPLICATION_CONTEXT_NAME));
ProtectionElementSearchCriteria searchCriteria = new ProtectionElementSearchCriteria(pe);
peList = privilegeUtility.getUserProvisioningManager().getObjects(searchCriteria);
if (peList != null && !peList.isEmpty())
{
pe = peList.get(0);
}
else
{
privilegeUtility.getUserProvisioningManager().createProtectionElement(pe);
}
peList.add(pe);
}
else
{
pe.setObjectId(obj.getObjectId());
ProtectionElementSearchCriteria searchCriteria = new ProtectionElementSearchCriteria(pe);
peList = privilegeUtility.getUserProvisioningManager().getObjects(searchCriteria);
}
ProtectionGroup pg = new ProtectionGroup();
pg.setProtectionGroupName(protectionGroupName);
peSet.addAll(peList);
pg.setProtectionElements(peSet);
new PrivilegeUtility().getUserProvisioningManager().createProtectionGroup(pg);
}
catch (CSException e)
{
Logger.out.error(e.getMessage(), e);
}
}
private void distributeMapData(Map<String, SiteUserRolePrivilegeBean> userRowIdMap, Map<String, SiteUserRolePrivilegeBean> cpPrivilegeMap,
Map<String, SiteUserRolePrivilegeBean> sitePrivilegeMap)
{
for (Iterator<String> mapItr = userRowIdMap.keySet().iterator(); mapItr.hasNext(); )
{
String key = mapItr.next();
SiteUserRolePrivilegeBean siteUserRolePrivilegeBean = userRowIdMap.get(key);
if(siteUserRolePrivilegeBean.getCollectionProtocol() == null && siteUserRolePrivilegeBean.isAllCPChecked() == false)
{
sitePrivilegeMap.put(key, siteUserRolePrivilegeBean);
}
else
{
cpPrivilegeMap.put(key, siteUserRolePrivilegeBean);
}
}
}
/**
* @param userId
* @return
* @throws SMException
*/
private gov.nih.nci.security.authorization.domainobjects.User getUserByID(String userId)
throws SMException
{
gov.nih.nci.security.authorization.domainobjects.User user = SecurityManager.getInstance(
this.getClass()).getUserById(userId);
return user;
}
/**
* Updates the persistent object in the database.
* @param obj The object to be updated.
* @param session The session in which the object is saved.
* @throws DAOException
*/
protected void update(DAO dao, Object obj, Object oldObj, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException
{
User user = null;
Map<String,SiteUserRolePrivilegeBean> userRowIdMap =new HashMap<String, SiteUserRolePrivilegeBean>();
if(obj instanceof UserDTO)
{
user = ((UserDTO)obj).getUser();
userRowIdMap = ((UserDTO)obj).getUserRowIdBeanMap();
}
else
{
user = (User) obj;
}
User oldUser = (User) oldObj;
boolean isLoginUserUpdate = false;
if(sessionDataBean.getUserName().equals(oldUser.getLoginName()))
{
isLoginUserUpdate = true;
}
//If the user is rejected, its record cannot be updated.
if (Constants.ACTIVITY_STATUS_REJECT.equals(oldUser.getActivityStatus()))
{
throw new DAOException(ApplicationProperties.getValue("errors.editRejectedUser"));
}
else if (Constants.ACTIVITY_STATUS_NEW.equals(oldUser.getActivityStatus())
|| Constants.ACTIVITY_STATUS_PENDING.equals(oldUser.getActivityStatus()))
{
//If the user is not approved yet, its record cannot be updated.
throw new DAOException(ApplicationProperties.getValue("errors.editNewPendingUser"));
}
try
{
// Get the csm userId if present.
String csmUserId = null;
/**
* Santosh: Changes done for Api
* User should not edit the first time login field.
*/
if (user.getFirstTimeLogin() == null)
{
throw new DAOException(ApplicationProperties.getValue("domain.object.null.err.msg","First Time Login"));
}
if(oldUser.getFirstTimeLogin() != null && user.getFirstTimeLogin().booleanValue() != oldUser.getFirstTimeLogin().booleanValue())
{
throw new DAOException(ApplicationProperties.getValue("errors.cannotedit.firsttimelogin"));
}
if (user.getCsmUserId() != null)
{
csmUserId = user.getCsmUserId().toString();
}
gov.nih.nci.security.authorization.domainobjects.User csmUser = SecurityManager.getInstance(UserBizLogic.class).getUserById(csmUserId);
//Bug:7979
if(Constants.DUMMY_PASSWORD.equals(user.getNewPassword()))
{
user.setNewPassword(csmUser.getPassword());
}
String oldPassword = user.getOldPassword();
// If the page is of change password,
// update the password of the user in csm and catissue tables.
if (user.getPageOf().equals(Constants.PAGEOF_CHANGE_PASSWORD))
{
if (!oldPassword.equals(csmUser.getPassword()))
{
throw new DAOException(ApplicationProperties.getValue("errors.oldPassword.wrong"));
}
//Added for Password validation by Supriya Dankh.
Validator validator = new Validator();
if (!validator.isEmpty(user.getNewPassword()) && !validator.isEmpty(oldPassword))
{
int result = validatePassword(oldUser, user.getNewPassword(), oldPassword);
Logger.out.debug("return from Password validate " + result);
//if validatePassword method returns value greater than zero then validation fails
if (result != SUCCESS)
{
// get error message of validation failure
String errorMessage = getPasswordErrorMsg(result);
Logger.out.debug("Error Message from method" + errorMessage);
throw new DAOException(errorMessage);
}
}
csmUser.setPassword(user.getNewPassword());
// Set values in password domain object and adds changed password in Password Collection
Password password = new Password(PasswordManager.encrypt(user.getNewPassword()), user);
user.getPasswordCollection().add(password);
}
//Bug-1516: Jitendra Administartor should be able to edit the password
else if(user.getPageOf().equals(Constants.PAGEOF_USER_ADMIN) && !user.getNewPassword().equals(csmUser.getPassword()))
{
Validator validator = new Validator();
if (!validator.isEmpty(user.getNewPassword()))
{
int result = validatePassword(oldUser, user.getNewPassword(), oldPassword);
Logger.out.debug("return from Password validate " + result);
//if validatePassword method returns value greater than zero then validation fails
if (result != SUCCESS)
{
// get error message of validation failure
String errorMessage = getPasswordErrorMsg(result);
Logger.out.debug("Error Message from method" + errorMessage);
throw new DAOException(errorMessage);
}
}
csmUser.setPassword(user.getNewPassword());
// Set values in password domain object and adds changed password in Password Collection
Password password = new Password(PasswordManager.encrypt(user.getNewPassword()), user);
user.getPasswordCollection().add(password);
user.setFirstTimeLogin(new Boolean(true));
}
else
{
csmUser.setLoginName(user.getLoginName());
csmUser.setLastName(user.getLastName());
csmUser.setFirstName(user.getFirstName());
csmUser.setEmailId(user.getEmailAddress());
// Assign Role only if the page is of Administrative user edit.
if ((Constants.PAGEOF_USER_PROFILE.equals(user.getPageOf()) == false)
&& (Constants.PAGEOF_CHANGE_PASSWORD.equals(user.getPageOf()) == false))
{
SecurityManager.getInstance(UserBizLogic.class).assignRoleToUser(csmUser.getUserId().toString(), user.getRoleId());
}
// Set protectionObjects = new HashSet();
// protectionObjects.add(user);
if(userRowIdMap != null && !userRowIdMap.isEmpty())
{
updateUserDetails(user,userRowIdMap);
}
Vector authorizationData = new Vector();
PrivilegeManager privilegeManager = PrivilegeManager.getInstance();
insertCPSitePrivileges(user, authorizationData, userRowIdMap);
privilegeManager.insertAuthorizationData(authorizationData, null, null, user.getObjectId());
// privilegeManager.insertAuthorizationData(getAuthorizationData(user, userRowIdMap),
// protectionObjects, null, user.getObjectId());
dao.update(user.getAddress(), sessionDataBean, true, false, false);
// Audit of user address.
dao.audit(user.getAddress(), oldUser.getAddress(), sessionDataBean, true);
}
if (user.getPageOf().equals(Constants.PAGEOF_CHANGE_PASSWORD))
{
user.setFirstTimeLogin(new Boolean(false));
}
dao.update(user, sessionDataBean, true, true, true);
//Modify the csm user.
SecurityManager.getInstance(UserBizLogic.class).modifyUser(csmUser);
if(isLoginUserUpdate)
{
sessionDataBean.setUserName(csmUser.getLoginName());
}
//Audit of user.
dao.audit(obj, oldObj, sessionDataBean, true);
/* pratha commented for bug# 7304
if (Constants.ACTIVITY_STATUS_ACTIVE.equals(user.getActivityStatus()))
{
Set protectionObjects = new HashSet();
protectionObjects.add(user);
try{
SecurityManager.getInstance(this.getClass()).insertAuthorizationData(getAuthorizationData(user), protectionObjects, null);
}
catch (SMException e)
{
//digest exception
}
} */
}
catch (SMException e)
{
throw handleSMException(e);
}
catch (PasswordEncryptionException e)
{
throw new DAOException(e.getMessage(), e);
}
}
/**
* Returns the list of NameValueBeans with name as "LastName,Firstname"
* and value as systemtIdentifier, of all users who are not disabled.
* @return the list of NameValueBeans with name as "LastName,Firstname"
* and value as systemtIdentifier, of all users who are not disabled.
* @throws DAOException
*/
public Vector getUsers(String operation) throws DAOException
{
String sourceObjectName = User.class.getName();
//Get only the fields required
String[] selectColumnName = {Constants.SYSTEM_IDENTIFIER,Constants.LASTNAME,Constants.FIRSTNAME};
String[] whereColumnName;
String[] whereColumnCondition;
Object[] whereColumnValue;
String joinCondition;
if (operation != null && operation.equalsIgnoreCase(Constants.ADD))
{
String tmpArray1[] = {Constants.ACTIVITY_STATUS};
String tmpArray2[] = {Constants.EQUALS};
String tmpArray3[] = {Constants.ACTIVITY_STATUS_ACTIVE};
whereColumnName = tmpArray1;
whereColumnCondition = tmpArray2;
whereColumnValue = tmpArray3;
joinCondition = null;
}
else
{
String tmpArray1[] = {Constants.ACTIVITY_STATUS, Constants.ACTIVITY_STATUS};
String tmpArray2[] = {Constants.EQUALS,Constants.EQUALS};
String tmpArray3[] = {Constants.ACTIVITY_STATUS_ACTIVE, Constants.ACTIVITY_STATUS_CLOSED};
whereColumnName = tmpArray1;
whereColumnCondition = tmpArray2;
whereColumnValue = tmpArray3;
joinCondition = Constants.OR_JOIN_CONDITION;
}
//Retrieve the users whose activity status is not disabled.
List users = retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition);
Vector nameValuePairs = new Vector();
nameValuePairs.add(new NameValueBean(Constants.SELECT_OPTION, String.valueOf(Constants.SELECT_OPTION_VALUE)));
// If the list of users retrieved is not empty.
if (users.isEmpty() == false)
{
// Creating name value beans.
for (int i = 0; i < users.size(); i++)
{
//Changes made to optimize the query to get only required fields data
Object[] userData = (Object[])users.get(i);
NameValueBean nameValueBean = new NameValueBean();
nameValueBean.setName(userData[1]+", "+userData[2]);
nameValueBean.setValue(userData[0]);
nameValuePairs.add(nameValueBean);
}
}
Collections.sort(nameValuePairs);
return nameValuePairs;
}
/**
* Returns the list of NameValueBeans with name as "LastName,Firstname"
* and value as systemtIdentifier, of all users who are not disabled.
* @return the list of NameValueBeans with name as "LastName,Firstname"
* and value as systemtIdentifier, of all users who are not disabled.
* @throws DAOException
*/
public Vector getCSMUsers() throws DAOException, SMException
{
//Retrieve the users whose activity status is not disabled.
List users = SecurityManager.getInstance(UserBizLogic.class).getUsers();
Vector nameValuePairs = new Vector();
nameValuePairs.add(new NameValueBean(Constants.SELECT_OPTION, String.valueOf(Constants.SELECT_OPTION_VALUE)));
// If the list of users retrieved is not empty.
if (users.isEmpty() == false)
{
// Creating name value beans.
for (int i = 0; i < users.size(); i++)
{
gov.nih.nci.security.authorization.domainobjects.User user = (gov.nih.nci.security.authorization.domainobjects.User) users.get(i);
NameValueBean nameValueBean = new NameValueBean();
nameValueBean.setName(user.getLastName() + ", " + user.getFirstName());
nameValueBean.setValue(String.valueOf(user.getUserId()));
Logger.out.debug(nameValueBean.toString());
nameValuePairs.add(nameValueBean);
}
}
Collections.sort(nameValuePairs);
return nameValuePairs;
}
/**
* Returns a list of users according to the column name and value.
* @param colName column name on the basis of which the user list is to be retrieved.
* @param colValue Value for the column name.
* @throws DAOException
*/
public List retrieve(String className, String colName, Object colValue) throws DAOException
{
List userList = null;
Logger.out.debug("In user biz logic retrieve........................");
try
{
// Get the caTISSUE user.
userList = super.retrieve(className, colName, colValue);
User appUser = null;
if (userList!=null && !userList.isEmpty())
{
appUser = (User) userList.get(0);
if (appUser.getCsmUserId() != null)
{
//Get the role of the user.
Role role = SecurityManager.getInstance(UserBizLogic.class).getUserRole(appUser.getCsmUserId().longValue());
//Logger.out.debug("In USer biz logic.............role........id......." + role.getId().toString());
if (role != null)
{
appUser.setRoleId(role.getId().toString());
}
}
}
}
catch (SMException e)
{
throw handleSMException(e);
}
return userList;
}
/**
* Retrieves and sends the login details email to the user whose email address is passed
* else returns the error key in case of an error.
* @param emailAddress the email address of the user whose password is to be sent.
* @return the error key in case of an error.
* @throws DAOException
* @throws DAOException
* @throws UserNotAuthorizedException
* @throws UserNotAuthorizedException
*/
public String sendForgotPassword(String emailAddress,SessionDataBean sessionData) throws DAOException, UserNotAuthorizedException
{
String statusMessageKey = null;
List list = retrieve(User.class.getName(), "emailAddress", emailAddress);
if (list!=null && !list.isEmpty())
{
User user = (User) list.get(0);
if (user.getActivityStatus().equals(Constants.ACTIVITY_STATUS_ACTIVE))
{
EmailHandler emailHandler = new EmailHandler();
//Send the login details email to the user.
boolean emailStatus = false;
try
{
emailStatus = emailHandler.sendLoginDetailsEmail(user, null);
}
catch (DAOException e)
{
e.printStackTrace();
}
if (emailStatus)
{
// if success commit
/**
* Update the field FirstTimeLogin which will ensure user changes his password on login
* Note --> We can not use CommonAddEditAction to update as the user has not still logged in
* and user authorisation will fail. So writing saperate code for update.
*/
user.setFirstTimeLogin(new Boolean(true));
AbstractDAO dao = DAOFactory.getInstance().getDAO(Constants.HIBERNATE_DAO);
dao.openSession(sessionData);
dao.update(user, sessionData, true, true, true);
dao.commit();
dao.closeSession();
statusMessageKey = "password.send.success";
}
else
{
statusMessageKey = "password.send.failure";
}
}
else
{
//Error key if the user is not active.
statusMessageKey = "errors.forgotpassword.user.notApproved";
}
}
else
{
// Error key if the user is not present.
statusMessageKey = "errors.forgotpassword.user.unknown";
}
return statusMessageKey;
}
/**
* Overriding the parent class's method to validate the enumerated attribute values
*/
protected boolean validate(Object obj, DAO dao, String operation) throws DAOException
{
User user = null;
if (obj instanceof UserDTO)
{
user = ((UserDTO)obj).getUser();
}
else
{
user = (User) obj;
}
ApiSearchUtil.setUserDefault(user);
//End:- Change for API Search
//Added by Ashish Gupta
/*
if (user == null)
throw new DAOException("domain.object.null.err.msg", new String[]{"User"});
*/
//END
if (Constants.PAGEOF_CHANGE_PASSWORD.equals(user.getPageOf()) == false)
{
if (!Validator.isEnumeratedValue(CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_STATE_LIST, null), user
.getAddress().getState()))
{
throw new DAOException(ApplicationProperties.getValue("state.errMsg"));
}
if (!Validator.isEnumeratedValue(CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_COUNTRY_LIST, null), user
.getAddress().getCountry()))
{
throw new DAOException(ApplicationProperties.getValue("country.errMsg"));
}
if (Constants.PAGEOF_USER_ADMIN.equals(user.getPageOf()))
{
// try
// if (!Validator.isEnumeratedValue(getRoles(), user.getRoleId()))
// throw new DAOException(ApplicationProperties.getValue("user.role.errMsg"));
// catch (SMException e)
// throw handleSMException(e);
if (operation.equals(Constants.ADD))
{
if (!Constants.ACTIVITY_STATUS_ACTIVE.equals(user.getActivityStatus()))
{
throw new DAOException(ApplicationProperties.getValue("activityStatus.active.errMsg"));
}
}
else
{
if (!Validator.isEnumeratedValue(Constants.USER_ACTIVITY_STATUS_VALUES, user.getActivityStatus()))
{
throw new DAOException(ApplicationProperties.getValue("activityStatus.errMsg"));
}
}
}
//Added by Ashish
/**
* Two more parameter 'dao' and 'operation' is added by Vijay Pande to use it in isUniqueEmailAddress method
*/
apiValidate(user, dao,operation);
//END
}
return true;
}
//Added by Ashish
/**
* @param user user
* @param dao
* @param operation
* @return
* @throws DAOException
*/
private boolean apiValidate(User user, DAO dao, String operation)
throws DAOException
{
Validator validator = new Validator();
String message = "";
boolean validate = true;
if (validator.isEmpty(user.getEmailAddress()))
{
message = ApplicationProperties.getValue("user.emailAddress");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
else
{
if (!validator.isValidEmailAddress(user.getEmailAddress()))
{
message = ApplicationProperties.getValue("user.emailAddress");
throw new DAOException(ApplicationProperties.getValue("errors.item.format",message));
}
/**
* Name : Vijay_Pande
* Reviewer : Sntosh_Chandak
* Bug ID: 4185_2
* Patch ID: 1-2
* See also: 1
* Description: Wrong error meassage was dispayed while adding user with existing email address in use.
* Following method is provided to verify whether the email address is already present in the system or not.
*/
if(operation.equals(Constants.ADD) && !(isUniqueEmailAddress(user.getEmailAddress(),dao)))
{
String arguments[] = null;
arguments = new String[]{"User", ApplicationProperties.getValue("user.emailAddress")};
String errMsg = new DefaultExceptionFormatter().getErrorMessage("Err.ConstraintViolation", arguments);
Logger.out.debug("Unique Constraint Violated: " + errMsg);
throw new DAOException(errMsg);
}
/** -- patch ends here -- */
}
if (validator.isEmpty(user.getLastName()))
{
message = ApplicationProperties.getValue("user.lastName");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
else if(validator.isXssVulnerable(user.getLastName()))
{
message = ApplicationProperties.getValue("user.lastName");
throw new DAOException(ApplicationProperties.getValue("errors.xss.invalid",message));
}
if (validator.isEmpty(user.getFirstName()))
{
message = ApplicationProperties.getValue("user.firstName");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
else if(validator.isXssVulnerable(user.getFirstName()))
{
message = ApplicationProperties.getValue("user.firstName");
throw new DAOException(ApplicationProperties.getValue("errors.xss.invalid",message));
}
if (validator.isEmpty(user.getAddress().getCity()))
{
message = ApplicationProperties.getValue("user.city");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
if (!validator.isValidOption(user.getAddress().getState()) || validator.isEmpty(user.getAddress().getState()))
{
message = ApplicationProperties.getValue("user.state");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
if (validator.isEmpty(user.getAddress().getZipCode()))
{
message = ApplicationProperties.getValue("user.zipCode");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
else
{
if (!validator.isValidZipCode(user.getAddress().getZipCode()))
{
message = ApplicationProperties.getValue("user.zipCode");
throw new DAOException(ApplicationProperties.getValue("errors.item.format",message));
}
}
if (!validator.isValidOption(user.getAddress().getCountry()) || validator.isEmpty(user.getAddress().getCountry()))
{
message = ApplicationProperties.getValue("user.country");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
//Bug #4349
if (validator.isEmpty(user.getAddress().getPhoneNumber()))
{
message = ApplicationProperties.getValue("user.phoneNumber");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
else
{
if (!validator.isValidPhoneNumber(user.getAddress().getPhoneNumber()))
{
message = ApplicationProperties.getValue("user.phoneNumber");
throw new DAOException(ApplicationProperties.getValue("error.phonenumber.format",message));
}
}
if (!validator.isEmpty(user.getAddress().getFaxNumber()))
{
if (!validator.isValidPhoneNumber(user.getAddress().getFaxNumber()))
{
message = ApplicationProperties.getValue("user.faxNumber");
throw new DAOException(ApplicationProperties.getValue("error.faxnumber.format",message));
}
}
//Bug #4349 ends
if (user.getInstitution().getId()==null || user.getInstitution().getId().longValue()<=0)
{
message = ApplicationProperties.getValue("user.institution");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
if (user.getDepartment().getId()==null || user.getDepartment().getId().longValue()<=0)
{
message = ApplicationProperties.getValue("user.department");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
if (user.getCancerResearchGroup().getId()==null || user.getCancerResearchGroup().getId().longValue()<=0)
{
message = ApplicationProperties.getValue("user.cancerResearchGroup");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
// if (user.getRoleId() != null)
// if (!validator.isValidOption(user.getRoleId()) || validator.isEmpty(String.valueOf(user.getRoleId())))
// message = ApplicationProperties.getValue("user.role");
// throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
return validate;
}
//END
/**
* Returns a list of all roles that can be assigned to a user.
* @return a list of all roles that can be assigned to a user.
* @throws SMException
*/
private List getRoles() throws SMException
{
//Sets the roleList attribute to be used in the Add/Edit User Page.
Vector roleList = SecurityManager.getInstance(UserBizLogic.class).getRoles();
List roleNameValueBeanList = new ArrayList();
NameValueBean nameValueBean = new NameValueBean();
nameValueBean.setName(Constants.SELECT_OPTION);
nameValueBean.setValue("-1");
roleNameValueBeanList.add(nameValueBean);
ListIterator iterator = roleList.listIterator();
while (iterator.hasNext())
{
Role role = (Role) iterator.next();
nameValueBean = new NameValueBean();
nameValueBean.setName(role.getName());
nameValueBean.setValue(String.valueOf(role.getId()));
roleNameValueBeanList.add(nameValueBean);
}
return roleNameValueBeanList;
}
/**
* @param oldUser User object
* @param newPassword New Password value
* @param validator VAlidator object
* @param oldPassword Old Password value
* @return SUCCESS (constant int 0) if all condition passed
* else return respective error code (constant int) value
* @throws PasswordEncryptionException
*/
private int validatePassword(User oldUser, String newPassword, String oldPassword) throws PasswordEncryptionException
{
List oldPwdList = new ArrayList(oldUser.getPasswordCollection());
Collections.sort(oldPwdList);
if (oldPwdList != null && !oldPwdList.isEmpty())
{
//Check new password is equal to last n password if value
String encryptedPassword = PasswordManager.encrypt(newPassword);
if (checkPwdNotSameAsLastN(newPassword, oldPwdList))
{
Logger.out.debug("Password is not valid returning FAIL_SAME_AS_LAST_N");
return FAIL_SAME_AS_LAST_N;
}
//Get the last updated date of the password
Date lastestUpdateDate = ((Password) oldPwdList.get(0)).getUpdateDate();
boolean firstTimeLogin = false;
if(oldUser.getFirstTimeLogin() != null)
{
firstTimeLogin = oldUser.getFirstTimeLogin().booleanValue();
}
if (!firstTimeLogin)
{
if (checkPwdUpdatedOnSameDay(lastestUpdateDate))
{
Logger.out.debug("Password is not valid returning FAIL_CHANGED_WITHIN_SOME_DAY");
return FAIL_CHANGED_WITHIN_SOME_DAY;
}
}
/**
* to check password does not contain user name,surname,email address. if same return FAIL_SAME_NAME_SURNAME_EMAIL
* eg. username=XabcY@abc.com newpassword=abc is not valid
*/
String emailAddress = oldUser.getEmailAddress();
int usernameBeforeMailaddress = emailAddress.indexOf('@');
// get substring of emailAddress before '@' character
emailAddress = emailAddress.substring(0, usernameBeforeMailaddress);
String userFirstName = oldUser.getFirstName();
String userLastName = oldUser.getLastName();
StringBuffer sb = new StringBuffer(newPassword);
if (emailAddress != null && newPassword.toLowerCase().indexOf(emailAddress.toLowerCase())!=-1)
{
Logger.out.debug("Password is not valid returning FAIL_SAME_NAME_SURNAME_EMAIL");
return FAIL_SAME_NAME_SURNAME_EMAIL;
}
if (userFirstName != null && newPassword.toLowerCase().indexOf(userFirstName.toLowerCase())!=-1)
{
Logger.out.debug("Password is not valid returning FAIL_SAME_NAME_SURNAME_EMAIL");
return FAIL_SAME_NAME_SURNAME_EMAIL;
}
if (userLastName != null && newPassword.toLowerCase().indexOf(userLastName.toLowerCase())!=-1)
{
Logger.out.debug("Password is not valid returning FAIL_SAME_NAME_SURNAME_EMAIL");
return FAIL_SAME_NAME_SURNAME_EMAIL;
}
}
return SUCCESS;
}
/**
* This function checks whether user has logged in for first time or whether user's password is expired.
* In both these case user needs to change his password so Error key is returned
* @param user - user object
* @throws DAOException - throws DAOException
*/
public String checkFirstLoginAndExpiry(User user)
{
List passwordList = new ArrayList(user.getPasswordCollection());
boolean firstTimeLogin = false;
if(user.getFirstTimeLogin() != null)
{
firstTimeLogin = user.getFirstTimeLogin().booleanValue();
}
// If user has logged in for the first time, return key of Change password on first login
if (firstTimeLogin)
{
return "errors.changePassword.changeFirstLogin";
}
Collections.sort(passwordList);
Password lastPassword = (Password)passwordList.get(0);
Date lastUpdateDate = lastPassword.getUpdateDate();
Validator validator = new Validator();
//Get difference in days between last password update date and current date.
long dayDiff = validator.getDateDiff(lastUpdateDate, new Date());
int expireDaysCount = Integer.parseInt(XMLPropertyHandler.getValue("password.expire_after_n_days"));
if (dayDiff > expireDaysCount)
{
return "errors.changePassword.expire";
}
return Constants.SUCCESS;
}
private boolean checkPwdNotSameAsLastN(String newPassword, List oldPwdList)
{
int noOfPwdNotSameAsLastN = 0;
String pwdNotSameAsLastN = XMLPropertyHandler.getValue("password.not_same_as_last_n");
if (pwdNotSameAsLastN != null && !pwdNotSameAsLastN.equals(""))
{
noOfPwdNotSameAsLastN = Integer.parseInt(pwdNotSameAsLastN);
noOfPwdNotSameAsLastN = Math.max(0, noOfPwdNotSameAsLastN);
}
boolean isSameFound = false;
int loopCount = Math.min(oldPwdList.size(), noOfPwdNotSameAsLastN);
for (int i = 0; i < loopCount; i++)
{
Password pasword = (Password) oldPwdList.get(i);
if (newPassword.equals(pasword.getPassword()))
{
isSameFound = true;
break;
}
}
return isSameFound;
}
private boolean checkPwdUpdatedOnSameDay(Date lastUpdateDate)
{
Validator validator = new Validator();
//Get difference in days between last password update date and current date.
long dayDiff = validator.getDateDiff(lastUpdateDate, new Date());
int dayDiffConstant = Integer.parseInt(XMLPropertyHandler.getValue("daysCount"));
if (dayDiff <= dayDiffConstant)
{
Logger.out.debug("Password is not valid returning FAIL_CHANGED_WITHIN_SOME_DAY");
return true;
}
return false;
}
/**
* @param errorCode int value return by validatePassword() method
* @return String error message with respect to error code
*/
private String getPasswordErrorMsg(int errorCode)
{
String errMsg = "";
switch (errorCode)
{
case FAIL_SAME_AS_LAST_N :
List parameters = new ArrayList();
String dayCount = "" + Integer.parseInt(XMLPropertyHandler.getValue("password.not_same_as_last_n"));
parameters.add(dayCount);
errMsg = ApplicationProperties.getValue("errors.newPassword.sameAsLastn",parameters);
break;
case FAIL_FIRST_LOGIN :
errMsg = ApplicationProperties.getValue("errors.changePassword.changeFirstLogin");
break;
case FAIL_EXPIRE :
errMsg = ApplicationProperties.getValue("errors.changePassword.expire");
break;
case FAIL_CHANGED_WITHIN_SOME_DAY :
errMsg = ApplicationProperties.getValue("errors.changePassword.afterSomeDays");
break;
case FAIL_SAME_NAME_SURNAME_EMAIL :
errMsg = ApplicationProperties.getValue("errors.changePassword.sameAsNameSurnameEmail");
break;
case FAIL_PASSWORD_EXPIRED :
errMsg = ApplicationProperties.getValue("errors.changePassword.expire");
default :
errMsg = PasswordManager.getErrorMessage(errorCode);
break;
}
return errMsg;
}
/**
* Name : Vijay_Pande
* Reviewer : Sntosh_Chandak
* Bug ID: 4185_2
* Patch ID: 1-2
* See also: 1
* Description: Wrong error meassage was dispayed while adding user with existing email address in use.
* Following method is provided to verify whether the email address is already present in the system or not.
*/
/**
* Method to check whether email address already exist or not
* @param emailAddress email address to be check
* @param dao an object of DAO
* @return isUnique boolean value to indicate presence of similar email address
* @throws DAOException database exception
*/
private boolean isUniqueEmailAddress(String emailAddress, DAO dao) throws DAOException
{
boolean isUnique=true;
String sourceObjectName=User.class.getName();
String[] selectColumnName=new String[] {"id"};
String[] whereColumnName = new String[]{"emailAddress"};
String[] whereColumnCondition = new String[]{"="};
Object[] whereColumnValue = new String[]{emailAddress};
String joinCondition = null;
List userList = dao.retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition);
if (userList.size() > 0)
{
isUnique=false;
}
return isUnique;
}
/**
* Set Role to user object before populating actionForm out of it
* @param domainObj object of AbstractDomainObject
* @param uiForm object of the class which implements IValueObject
* @throws BizLogicException
*/
protected void prePopulateUIBean(AbstractDomainObject domainObj, IValueObject uiForm) throws BizLogicException
{
Logger.out.info("Inside prePopulateUIBean method of UserBizLogic...");
User user = (User)domainObj;
Role role=null;
if (user.getCsmUserId() != null)
{
try
{
//Get the role of the user.
role = SecurityManager.getInstance(UserBizLogic.class).getUserRole(user.getCsmUserId().longValue());
if (role != null)
{
user.setRoleId(role.getId().toString());
}
// Logger.out.debug("In USer biz logic.............role........id......." + role.getId().toString());
}
catch (SMException e)
{
Logger.out.error("SMException in prePopulateUIBean method of UserBizLogic..."+e);
//throw new BizLogicException(e.getMessage());
}
}
}
// //method to return a comma seperated list of emails of administrators of a particular institute
// private String getInstitutionAdmins(Long instID) throws DAOException,SMException
// String retStr="";
// String[] userEmail;
// Long[] csmAdminIDs = SecurityManager.getInstance(UserBizLogic.class).getAllAdministrators() ;
// if (csmAdminIDs != null )
// for(int cnt=0;cnt<csmAdminIDs.length ;cnt++ )
// String sourceObjectName = User.class.getName();
// String[] selectColumnName = null;
// String[] whereColumnName = {"institution","csmUserId"};
// String[] whereColumnCondition = {"=","="};
// Object[] whereColumnValue = {instID, csmAdminIDs[cnt] };
// String joinCondition = Constants.AND_JOIN_CONDITION;
// //Retrieve the users for given institution and who are administrators.
// List users = retrieve(sourceObjectName, selectColumnName, whereColumnName,
// whereColumnCondition, whereColumnValue, joinCondition);
// if(!users.isEmpty() )
// User adminUser = (User)users.get(0);
// retStr = retStr + "," + adminUser.getEmailAddress();
// Logger.out.debug(retStr);
// retStr = retStr.substring(retStr.indexOf(",")+1 );
// Logger.out.debug(retStr);
// return retStr;
/**
* To Sort CP's in CP based view according to the
* Privilges of User on CP
* Done for MSR functionality change
* @author ravindra_jain
*/
public Set<Long> getRelatedCPIds(Long userId)
{
AbstractDAO dao = DAOFactory.getInstance().getDAO(Constants.HIBERNATE_DAO);
Collection<CollectionProtocol> userCpCollection = new HashSet<CollectionProtocol>();
Collection<CollectionProtocol> userColl;
Set<Long> cpIds = new HashSet<Long>();
try
{
dao.openSession(null);
User user = (User) dao.retrieve(User.class.getName(), userId);
userColl = user.getCollectionProtocolCollection();
userCpCollection = user.getAssignedProtocolCollection();
if (user.getRoleId().equalsIgnoreCase(Constants.ADMIN_USER))
{
cpIds = null;
}
else
{
PrivilegeManager privilegeManager = PrivilegeManager.getInstance();
PrivilegeCache privilegeCache = privilegeManager.getPrivilegeCache(user
.getLoginName());
for (CollectionProtocol collectionProtocol : userCpCollection)
{
if (privilegeCache.hasPrivilege(collectionProtocol.getObjectId(),
Variables.privilegeDetailsMap.get(Constants.EDIT_PROFILE_PRIVILEGE))
|| collectionProtocol.getPrincipalInvestigator().getLoginName().equals(
user.getLoginName()))
{
cpIds.add(collectionProtocol.getId());
}
}
for (CollectionProtocol cp : userColl)
{
cpIds.add(cp.getId());
}
}
}
catch (DAOException e)
{
Logger.out.error(e.getMessage(), e);
}
finally
{
try
{
dao.closeSession();
}
catch (DAOException e)
{
Logger.out.error(e.getMessage(), e);
}
}
return cpIds;
}
public Set<Long> getRelatedSiteIds(Long userId)
{
Session session = null;
HashSet<Long> idSet = null;
try
{
session = DBUtil.getCleanSession();
User user = (User) session.load(User.class.getName(), userId);
if (!user.getRoleId().equalsIgnoreCase(Constants.ADMIN_USER))
{
Collection<Site> siteCollection = user.getSiteCollection();
idSet = new HashSet<Long>();
for (Site site : siteCollection)
{
idSet.add(site.getId());
}
}
}
catch (BizLogicException e1)
{
Logger.out.debug(e1.getMessage(), e1);
}
finally
{
session.close();
}
return idSet;
}
/**
* Custom method for Add User Case
* @param dao
* @param domainObject
* @param sessionDataBean
* @return
*/
public String getObjectId(AbstractDAO dao, Object domainObject)
{
User user = null;
UserDTO userDTO = null;
Map<String,SiteUserRolePrivilegeBean> userRowIdMap =new HashMap<String, SiteUserRolePrivilegeBean>();
Collection<Site> siteCollection = new ArrayList<Site>();
if(domainObject instanceof UserDTO)
{
userDTO = (UserDTO) domainObject;
user = userDTO.getUser();
userRowIdMap = userDTO.getUserRowIdBeanMap();
}
else
{
user = (User) domainObject;
}
Object[] mapKeys = userRowIdMap.keySet().toArray();
for(Object mapKey : mapKeys)
{
String key = mapKey.toString();
SiteUserRolePrivilegeBean siteUserRolePrivilegeBean = userRowIdMap.get(key);
siteCollection.add(siteUserRolePrivilegeBean.getSiteList().get(0));
}
// Collection<Site> siteCollection = user.getSiteCollection();
StringBuffer sb = new StringBuffer();
boolean hasUserProvisioningPrivilege = false;
if (siteCollection != null && !siteCollection.isEmpty())
{
sb.append(Constants.SITE_CLASS_NAME);
for (Site site : siteCollection)
{
if (site.getId()!=null)
{
sb.append(Constants.UNDERSCORE).append(site.getId());
hasUserProvisioningPrivilege = true;
}
}
}
if(hasUserProvisioningPrivilege)
{
return sb.toString();
}
return null;
}
protected String getPrivilegeKey(Object domainObject)
{
return Constants.ADD_EDIT_USER;
}
/**
* Over-ridden for the case of Non - Admin user should be able to edit
* his/her details e.g. Password
* (non-Javadoc)
* @throws UserNotAuthorizedException
* @see edu.wustl.common.bizlogic.DefaultBizLogic#isAuthorized(edu.wustl.common.dao.AbstractDAO, java.lang.Object, edu.wustl.common.beans.SessionDataBean)
*/
public boolean isAuthorized(AbstractDAO dao, Object domainObject, SessionDataBean sessionDataBean) throws UserNotAuthorizedException
{
User user = null;
UserDTO userDTO = null;
if(sessionDataBean != null && sessionDataBean.isAdmin())
{
return true;
}
if(domainObject instanceof User)
{
user = (User) domainObject;
}
if(domainObject instanceof UserDTO)
{
userDTO = (UserDTO) domainObject;
user = userDTO.getUser();
}
if(user.getPageOf().equalsIgnoreCase("pageOfSignUp"))
{
return true;
}
if(user.getPageOf().equalsIgnoreCase("pageOfChangePassword"))
{
return true;
}
if(sessionDataBean!=null && user.getLoginName().equals(sessionDataBean.getUserName()))
{
return true;
}
boolean isAuthorized = false;
String privilegeName = getPrivilegeName(domainObject);
String protectionElementName = getObjectId(dao, domainObject);
PrivilegeCache privilegeCache = PrivilegeManager.getInstance().getPrivilegeCache(sessionDataBean.getUserName());
if (protectionElementName != null)
{
String [] prArray = protectionElementName.split(Constants.UNDERSCORE);
String baseObjectId = prArray[0];
String objId = null;
for (int i = 1 ; i < prArray.length;i++)
{
objId = baseObjectId+Constants.UNDERSCORE+prArray[i];
isAuthorized = privilegeCache.hasPrivilege(objId.toString(),privilegeName);
if (!isAuthorized)
{
break;
}
}
if (!isAuthorized)
{
throw Utility.getUserNotAuthorizedException(privilegeName, protectionElementName);
}
return isAuthorized;
}
else
{
// return false;
throw Utility.getUserNotAuthorizedException(privilegeName, protectionElementName);
}
}
} |
package org.exist.util;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.xml.parsers.SAXParserFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* Helper class for creating an instance of javax.xml.parsers.SAXParserFactory
*
* @author dizzzz@exist-db.org
*/
public class ExistSAXParserFactory {
private final static Logger LOG = LogManager.getLogger(ExistSAXParserFactory.class);
public final static String ORG_EXIST_SAXPARSERFACTORY = "org.exist.SAXParserFactory";
/**
* Get SAXParserFactory instance specified by factory class name.
*
* @param className Full class name of factory
* @return A Sax parser factory or NULL when not available.
*/
public static SAXParserFactory getSAXParserFactory(final String className) {
Class<?> clazz = null;
try {
clazz = Class.forName(className);
} catch (final ClassNotFoundException ex) {
// quick escape
if (LOG.isDebugEnabled()) {
LOG.debug(className + ": " + ex.getMessage(), ex);
}
return null;
}
// Get specific method
Method method = null;
try {
method = clazz.getMethod("newInstance", (Class[]) null);
} catch (final SecurityException | NoSuchMethodException ex) {
// quick escape
if (LOG.isDebugEnabled()) {
LOG.debug("Method " + className + ".newInstance not found.", ex);
}
return null;
}
// Invoke method
Object result = null;
try {
result = method.invoke(null, (Object[]) null);
} catch (final IllegalAccessException | InvocationTargetException ex) {
// quick escape
if (LOG.isDebugEnabled()) {
LOG.debug("Could not invoke method " + className + ".newInstance.", ex);
}
return null;
}
if (!(result instanceof SAXParserFactory)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Could not create instance of SAXParserFactory: " + result.toString());
}
return null;
}
return (SAXParserFactory) result;
}
/**
* Get instance of a SAXParserFactory. Return factory specified by
* system property org.exist.SAXParserFactory (if available) otherwise
* return system default.
*
* @return A sax parser factory.
*/
public static SAXParserFactory getSAXParserFactory() {
SAXParserFactory factory = null;
// Get SAXParser configuratin from system
final String config = System.getProperty(ORG_EXIST_SAXPARSERFACTORY);
// Get SAXparser factory specified by system property
if (config != null) {
factory = getSAXParserFactory(config);
}
// If no factory could be retrieved, create system default property.
if (factory == null) {
factory = SAXParserFactory.newInstance();
if (LOG.isDebugEnabled()) {
LOG.debug(String.format("Using default SAXParserFactory '%s'", factory.getClass().getCanonicalName()));
}
}
return factory;
}
} |
package edu.wustl.catissuecore.util.global;
/**
* This class stores the constants used in the operations in the application.
* @author gautam_shetty
*/
public class Constants extends edu.wustl.common.util.global.Constants
{
//// suite constants
//Consent tracking
public static final String SHOW_CONSENTS="showConsents";
public static final String SPECIMEN_CONSENTS="specimenConsents";
public static final String YES="yes";
public static final String CP_ID="cpID";
public static final String BARCODE_LABLE="barcodelabel";
public static final String DISTRIBUTION_ON="labelBarcode";
public static final String POPUP="popup";
public static final String ERROR="error";
public static final String ERROR_SHOWCONSENTS="errorShowConsent";
public static final String COMPLETE="Complete";
public static final String VIEW_CONSENTS="View";
public static final String APPLY="Apply";
public static final String APPLY_ALL="ApplyAll";
public static final String APPLY_NONE="ApplyNone";
public static final String PREDEFINED_CADSR_CONSENTS="predefinedConsentsList";
public static final String DISABLED="disabled";
public static final String VIEWAll="ViewAll";
public static final String BARCODE_DISTRIBUTION="1";
public static final String LABLE_DISTRIBUTION="2";
public static final String CONSENT_WAIVED="Consent Waived";
public static final String NO_CONSENTS="No Consents";
public static final String INVALID="Invalid";
public static final String VALID="valid";
public static final String FALSE="false";
public static final String NULL="null";
public static final String CONSENT_TABLE="tableId4";
public static final String DISABLE="disable";
public static final String SCG_ID="-1";
public static final String SELECTED_TAB="tab";
public static final String TAB_SELECTED="tabSelected";
public static final String NEWSPECIMEN_FORM="newSpecimenForm";
public static final String CONSENT_TABLE_SHOWHIDE="tableStatus";
public static final String SPECIMEN_RESPONSELIST="specimenResponseList";
public static final String PROTOCOL_EVENT_ID="protocolEventId";
public static final String SCG_DROPDOWN="value";
public static final String HASHED_OUT="
//Ordering System Status
public static final String CDE_NAME_REQUEST_STATUS="Request Status";
public static final String CDE_NAME_REQUESTED_ITEMS_STATUS="Requested Items Status";
public static final String REQUEST_LIST="requestStatusList";
public static final String REQUESTED_ITEMS_STATUS_LIST="requestedItemsStatusList";
public static final String ARRAY_STATUS_LIST="arrayStatusList";
public static final String REQUEST_OBJECT="requestObjectList";
public static final String REQUEST_DETAILS_LIST="requestDetailsList";
public static final String ARRAY_REQUESTS_BEAN_LIST="arrayRequestsBeanList";
public static final String SPECIMEN_ORDER_FORM_TYPE = "specimen";
public static final String ARRAY_ORDER_FORM_TYPE = "specimenArray";
public static final String PATHOLOGYCASE_ORDER_FORM_TYPE="pathologyCase";
public static final String REQUESTED_BIOSPECIMENS="RequestedBioSpecimens";
//Constants required in RequestDetailsPage
public static final String SUBMIT_REQUEST_DETAILS_ACTION="SubmitRequestDetails.do";
public static final String REQUEST_HEADER_OBJECT = "requestHeaderObject";
public static final String SITE_LIST_OBJECT = "siteList";
public static final String REQUEST_DETAILS_PAGE = "RequestDetails.do";
public static final String ARRAYREQUEST_DETAILS_PAGE = "ArrayRequests.do";
public static final String ARRAY_REQUESTS_LIST = "arrayRequestsList";
public static final String EXISISTINGARRAY_REQUESTS_LIST = "existingArrayRequestDetailsList";
public static final String DEFINEDARRAY_REQUESTS_LIST = "DefinedRequestDetailsMapList";
public static final String ITEM_STATUS_LIST="itemsStatusList";
public static final String ITEM_STATUS_LIST_WO_DISTRIBUTE="itemsStatusListWithoutDistribute";
public static final String ITEM_STATUS_LIST_FOR_ITEMS_IN_ARRAY="itemsStatusListForItemsInArray";
public static final String REQUEST_FOR_LIST="requestForList";
//Used for tree display in RequestDetails page
public static final String TREE_DATA_LIST = "treeDataList";
//Constants for Order Status
public static final String ORDER_STATUS_NEW = "New";
public static final String ORDER_STATUS_PENDING = "Pending";
public static final String ORDER_STATUS_REJECTED = "Rejected";
public static final String ORDER_STATUS_COMPLETED = "Completed";
//Constants for Order Request Status.
public static final String ORDER_REQUEST_STATUS_NEW = "New";
public static final String ORDER_REQUEST_STATUS_PENDING_PROTOCOL_REVIEW = "Pending - Protocol Review";
public static final String ORDER_REQUEST_STATUS_PENDING_SPECIMEN_PREPARATION = "Pending - Specimen Preparation";
public static final String ORDER_REQUEST_STATUS_PENDING_FOR_DISTRIBUTION = "Pending - For Distribution";
public static final String ORDER_REQUEST_STATUS_REJECTED_INAPPROPRIATE_REQUEST = "Rejected - Inappropriate Request";
public static final String ORDER_REQUEST_STATUS_REJECTED_SPECIMEN_UNAVAILABLE = "Rejected - Specimen Unavailable";
public static final String ORDER_REQUEST_STATUS_REJECTED_UNABLE_TO_CREATE = "Rejected - Unable to Create";
public static final String ORDER_REQUEST_STATUS_DISTRIBUTED = "Distributed";
public static final String ORDER_REQUEST_STATUS_READY_FOR_ARRAY_PREPARATION = "Ready For Array Preparation";
public static final String SPREADSHEET_DATA_LIST_FOR_PATHOLOGICAL_CASES = "spreadsheetDataListForPathologicalCases";
public static final String SPREADSHEET_DATA_LIST_FOR_ARRAY = "spreadsheetDataListForArray";
// Report Loader
public static final String MAX_PARTICIPANT_MATCHING_PERCENTAGE="maxParticipantMatchingPercentage";
// Query Module Interface UI constants
public static final String ViewSearchResultsAction = "ViewSearchResultsAction.do";
public static final String categorySearchForm = "categorySearchForm";
public static final String SearchCategory = "SearchCategory.do";
public static final String DefineSearchResultsViewAction = "DefineSearchResultsView.do";
public static final String DefineSearchResultsViewJSPAction = "ViewSearchResultsJSPAction.do";
public static final String QUERY_DAG_VIEW_APPLET = "edu/wustl/catissuecore/applet/ui/querysuite/DiagrammaticViewApplet.class";
public static final String QUERY_DAG_VIEW_APPLET_NAME = "Dag View Applet";
public static final String APP_DYNAMIC_UI_XML = "xmlfile.dynamicUI";
public static final String QUERY_CONDITION_DELIMITER = "@#condition#@";
public static final String QUERY_OPERATOR_DELIMITER = "!*=*!";
public static final String SEARCHED_ENTITIES_MAP = "searchedEntitiesMap";
public static final String SUCCESS = "success";
public static final String LIST_OF_ENTITIES_IN_QUERY = "ListOfEntitiesInQuery";
public static final String DYNAMIC_UI_XML = "dynamicUI.xml";
public static final String TREE_DATA = "treeData";
public static final String ZERO_ID = "0";
public static final String TEMP_OUPUT_TREE_TABLE_NAME = "temp_OutputTree";
public static final String CREATE_TABLE = "Create table ";
public static final String AS = "as";
public static final String UNDERSCORE = "_";
public static final String ID_NODES_MAP = "idNodesMap";
public static final String ID_COLUMNS_MAP = "idColumnsMap";
//Surgical Pathology Report UI constants
public static final String SPR_VIEW_ACTION="ViewSurgicalPathologyReport.do";
public static final String VIEW_SURGICAL_PATHOLOGY_REPORT="viewSPR";
public static final String PAGEOF_SPECIMEN_COLLECTION_GROUP="pageOfSpecimenCollectionGroup";
public static final String PAGEOF_PARTICIPANT="pageOfParticipant";
public static final String PAGEOF_SPECIMEN="pageOfNewSpecimen";
public static final String REVIEW="REVIEW";
public static final String QUARANTINE="QUARANTINE";
public static final String COMMENT_STATUS_RENDING="PENDING";
public static final String COMMENT_STATUS_REVIEWED="REVIEWED";
public static final String COMMENT_STATUS_NOT_REVIEWED="NOT_REVIEWED";
public static final String COMMENT_STATUS_QUARANTINED="QUARANTINED";
public static final String COMMENT_STATUS_NOT_QUARANTINED="NOT_QUARANTINED";
public static final String ROLE_ADMINISTRATOR="Administrator";
public static final String REPORT_LIST="reportIdList";
public static final String MAX_IDENTIFIER = "maxIdentifier";
public static final String AND_JOIN_CONDITION = "AND";
public static final String OR_JOIN_CONDITION = "OR";
//Sri: Changed the format for displaying in Specimen Event list (#463)
public static final String TIMESTAMP_PATTERN = "MM-dd-yyyy HH:mm";
public static final String DATE_PATTERN_YYYY_MM_DD = "yyyy-MM-dd";
// Mandar: Used for Date Validations in Validator Class
public static final String DATE_SEPARATOR = "-";
public static final String DATE_SEPARATOR_DOT = ".";
public static final String MIN_YEAR = "1900";
public static final String MAX_YEAR = "9999";
public static final String VIEW = "view";
public static final String DELETE = "delete";
public static final String EXPORT = "export";
public static final String SHOPPING_CART_ADD = "shoppingCartAdd";
public static final String SHOPPING_CART_DELETE = "shoppingCartDelete";
public static final String SHOPPING_CART_EXPORT = "shoppingCartExport";
public static final String NEWUSERFORM = "newUserForm";
public static final String REDIRECT_TO_SPECIMEN = "specimenRedirect";
public static final String CALLED_FROM = "calledFrom";
public static final String ACCESS = "access";
//Constants required for Forgot Password
public static final String FORGOT_PASSWORD = "forgotpassword";
public static final String LOGINNAME = "loginName";
public static final String LASTNAME = "lastName";
public static final String FIRSTNAME = "firstName";
public static final String INSTITUTION = "institution";
public static final String EMAIL = "email";
public static final String DEPARTMENT = "department";
public static final String ADDRESS = "address";
public static final String CITY = "city";
public static final String STATE = "state";
public static final String COUNTRY = "country";
public static final String NEXT_CONTAINER_NO = "startNumber";
public static final String CSM_USER_ID = "csmUserId";
public static final String INSTITUTIONLIST = "institutionList";
public static final String DEPARTMENTLIST = "departmentList";
public static final String STATELIST = "stateList";
public static final String COUNTRYLIST = "countryList";
public static final String ROLELIST = "roleList";
public static final String ROLEIDLIST = "roleIdList";
public static final String CANCER_RESEARCH_GROUP_LIST = "cancerResearchGroupList";
public static final String GENDER_LIST = "genderList";
public static final String GENOTYPE_LIST = "genotypeList";
public static final String ETHNICITY_LIST = "ethnicityList";
public static final String PARTICIPANT_MEDICAL_RECORD_SOURCE_LIST = "participantMedicalRecordSourceList";
public static final String RACELIST = "raceList";
public static final String VITAL_STATUS_LIST = "vitalStatusList";
public static final String PARTICIPANT_LIST = "participantList";
public static final String PARTICIPANT_ID_LIST = "participantIdList";
public static final String PROTOCOL_LIST = "protocolList";
public static final String TIMEHOURLIST = "timeHourList";
public static final String TIMEMINUTESLIST = "timeMinutesList";
public static final String TIMEAMPMLIST = "timeAMPMList";
public static final String RECEIVEDBYLIST = "receivedByList";
public static final String COLLECTEDBYLIST = "collectedByList";
public static final String COLLECTIONSITELIST = "collectionSiteList";
public static final String RECEIVEDSITELIST = "receivedSiteList";
public static final String RECEIVEDMODELIST = "receivedModeList";
public static final String ACTIVITYSTATUSLIST = "activityStatusList";
public static final String USERLIST = "userList";
public static final String SITETYPELIST = "siteTypeList";
public static final String STORAGETYPELIST="storageTypeList";
public static final String STORAGECONTAINERLIST="storageContainerList";
public static final String SITELIST="siteList";
// public static final String SITEIDLIST="siteIdList";
public static final String USERIDLIST = "userIdList";
public static final String STORAGETYPEIDLIST="storageTypeIdList";
public static final String SPECIMENCOLLECTIONLIST="specimentCollectionList";
public static final String PARTICIPANT_IDENTIFIER_IN_CPR = "participant";
public static final String APPROVE_USER_STATUS_LIST = "statusList";
public static final String EVENT_PARAMETERS_LIST = "eventParametersList";
//New Specimen lists.
public static final String SPECIMEN_COLLECTION_GROUP_LIST = "specimenCollectionGroupIdList";
public static final String SPECIMEN_TYPE_LIST = "specimenTypeList";
public static final String SPECIMEN_SUB_TYPE_LIST = "specimenSubTypeList";
public static final String TISSUE_SITE_LIST = "tissueSiteList";
public static final String TISSUE_SIDE_LIST = "tissueSideList";
public static final String PATHOLOGICAL_STATUS_LIST = "pathologicalStatusList";
public static final String BIOHAZARD_TYPE_LIST = "biohazardTypeList";
public static final String BIOHAZARD_NAME_LIST = "biohazardNameList";
public static final String BIOHAZARD_ID_LIST = "biohazardIdList";
public static final String BIOHAZARD_TYPES_LIST = "biohazardTypesList";
public static final String PARENT_SPECIMEN_ID_LIST = "parentSpecimenIdList";
public static final String RECEIVED_QUALITY_LIST = "receivedQualityList";
public static final String SPECIMEN_COLL_GP_NAME = "specimenCollectionGroupName";
//SpecimenCollecionGroup lists.
public static final String PROTOCOL_TITLE_LIST = "protocolTitleList";
public static final String PARTICIPANT_NAME_LIST = "participantNameList";
public static final String PROTOCOL_PARTICIPANT_NUMBER_LIST = "protocolParticipantNumberList";
//public static final String PROTOCOL_PARTICIPANT_NUMBER_ID_LIST = "protocolParticipantNumberIdList";
public static final String STUDY_CALENDAR_EVENT_POINT_LIST = "studyCalendarEventPointList";
//public static final String STUDY_CALENDAR_EVENT_POINT_ID_LIST="studyCalendarEventPointIdList";
public static final String PARTICIPANT_MEDICAL_IDNETIFIER_LIST = "participantMedicalIdentifierArray";
//public static final String PARTICIPANT_MEDICAL_IDNETIFIER_ID_LIST = "participantMedicalIdentifierIdArray";
public static final String SPECIMEN_COLLECTION_GROUP_ID = "specimenCollectionGroupId";
public static final String REQ_PATH = "redirectTo";
public static final String CLINICAL_STATUS_LIST = "cinicalStatusList";
public static final String SPECIMEN_CLASS_LIST = "specimenClassList";
public static final String SPECIMEN_CLASS_ID_LIST = "specimenClassIdList";
public static final String SPECIMEN_TYPE_MAP = "specimenTypeMap";
//Simple Query Interface Lists
public static final String OBJECT_COMPLETE_NAME_LIST = "objectCompleteNameList";
public static final String SIMPLE_QUERY_INTERFACE_TITLE = "simpleQueryInterfaceTitle";
public static final String MAP_OF_STORAGE_CONTAINERS = "storageContainerMap";
public static final String STORAGE_CONTAINER_GRID_OBJECT = "storageContainerGridObject";
public static final String STORAGE_CONTAINER_CHILDREN_STATUS = "storageContainerChildrenStatus";
public static final String START_NUMBER = "startNumber";
public static final String CHILD_CONTAINER_SYSTEM_IDENTIFIERS = "childContainerIds";
public static final int STORAGE_CONTAINER_FIRST_ROW = 1;
public static final int STORAGE_CONTAINER_FIRST_COLUMN = 1;
public static final String MAP_COLLECTION_PROTOCOL_LIST = "collectionProtocolList";
public static final String MAP_SPECIMEN_CLASS_LIST = "specimenClassList";
//event parameters lists
public static final String METHOD_LIST = "methodList";
public static final String HOUR_LIST = "hourList";
public static final String MINUTES_LIST = "minutesList";
public static final String EMBEDDING_MEDIUM_LIST = "embeddingMediumList";
public static final String PROCEDURE_LIST = "procedureList";
public static final String PROCEDUREIDLIST = "procedureIdList";
public static final String CONTAINER_LIST = "containerList";
public static final String CONTAINERIDLIST = "containerIdList";
public static final String FROMCONTAINERLIST="fromContainerList";
public static final String TOCONTAINERLIST="toContainerList";
public static final String FIXATION_LIST = "fixationList";
public static final String FROM_SITE_LIST="fromsiteList";
public static final String TO_SITE_LIST="tositeList";
public static final String ITEMLIST="itemList";
public static final String DISTRIBUTIONPROTOCOLLIST="distributionProtocolList";
public static final String TISSUE_SPECIMEN_ID_LIST="tissueSpecimenIdList";
public static final String MOLECULAR_SPECIMEN_ID_LIST="molecularSpecimenIdList";
public static final String CELL_SPECIMEN_ID_LIST="cellSpecimenIdList";
public static final String FLUID_SPECIMEN_ID_LIST="fluidSpecimenIdList";
public static final String STORAGE_STATUS_LIST="storageStatusList";
public static final String CLINICAL_DIAGNOSIS_LIST = "clinicalDiagnosisList";
public static final String HISTOLOGICAL_QUALITY_LIST="histologicalQualityList";
//For Specimen Event Parameters.
public static final String SPECIMEN_ID = "specimenId";
public static final String FROM_POSITION_DATA = "fromPositionData";
public static final String POS_ONE ="posOne";
public static final String POS_TWO ="posTwo";
public static final String STORAGE_CONTAINER_ID ="storContId";
public static final String IS_RNA = "isRNA";
public static final String RNA = "RNA";
// New Participant Event Parameters
public static final String PARTICIPANT_ID="participantId";
//Constants required in User.jsp Page
public static final String USER_SEARCH_ACTION = "UserSearch.do";
public static final String USER_ADD_ACTION = "UserAdd.do";
public static final String USER_EDIT_ACTION = "UserEdit.do";
public static final String APPROVE_USER_ADD_ACTION = "ApproveUserAdd.do";
public static final String APPROVE_USER_EDIT_ACTION = "ApproveUserEdit.do";
public static final String SIGNUP_USER_ADD_ACTION = "SignUpUserAdd.do";
public static final String USER_EDIT_PROFILE_ACTION = "UserEditProfile.do";
public static final String UPDATE_PASSWORD_ACTION = "UpdatePassword.do";
//Constants required in Accession.jsp Page
public static final String ACCESSION_SEARCH_ACTION = "AccessionSearch.do";
public static final String ACCESSION_ADD_ACTION = "AccessionAdd.do";
public static final String ACCESSION_EDIT_ACTION = "AccessionEdit.do";
//Constants required in StorageType.jsp Page
public static final String STORAGE_TYPE_SEARCH_ACTION = "StorageTypeSearch.do";
public static final String STORAGE_TYPE_ADD_ACTION = "StorageTypeAdd.do";
public static final String STORAGE_TYPE_EDIT_ACTION = "StorageTypeEdit.do";
//Constants required in StorageContainer.jsp Page
public static final String STORAGE_CONTAINER_SEARCH_ACTION = "StorageContainerSearch.do";
public static final String STORAGE_CONTAINER_ADD_ACTION = "StorageContainerAdd.do";
public static final String STORAGE_CONTAINER_EDIT_ACTION = "StorageContainerEdit.do";
public static final String HOLDS_LIST1 = "HoldsList1";
public static final String HOLDS_LIST2 = "HoldsList2";
public static final String HOLDS_LIST3 = "HoldsList3";
//Constants required in Site.jsp Page
public static final String SITE_SEARCH_ACTION = "SiteSearch.do";
public static final String SITE_ADD_ACTION = "SiteAdd.do";
public static final String SITE_EDIT_ACTION = "SiteEdit.do";
//Constants required in Site.jsp Page
public static final String BIOHAZARD_SEARCH_ACTION = "BiohazardSearch.do";
public static final String BIOHAZARD_ADD_ACTION = "BiohazardAdd.do";
public static final String BIOHAZARD_EDIT_ACTION = "BiohazardEdit.do";
//Constants required in Partcipant.jsp Page
public static final String PARTICIPANT_SEARCH_ACTION = "ParticipantSearch.do";
public static final String PARTICIPANT_ADD_ACTION = "ParticipantAdd.do";
public static final String PARTICIPANT_EDIT_ACTION = "ParticipantEdit.do";
public static final String PARTICIPANT_LOOKUP_ACTION= "ParticipantLookup.do";
//Constants required in Institution.jsp Page
public static final String INSTITUTION_SEARCH_ACTION = "InstitutionSearch.do";
public static final String INSTITUTION_ADD_ACTION = "InstitutionAdd.do";
public static final String INSTITUTION_EDIT_ACTION = "InstitutionEdit.do";
//Constants required in Department.jsp Page
public static final String DEPARTMENT_SEARCH_ACTION = "DepartmentSearch.do";
public static final String DEPARTMENT_ADD_ACTION = "DepartmentAdd.do";
public static final String DEPARTMENT_EDIT_ACTION = "DepartmentEdit.do";
//Constants required in CollectionProtocolRegistration.jsp Page
public static final String COLLECTION_PROTOCOL_REGISTRATION_SEARCH_ACTION = "CollectionProtocolRegistrationSearch.do";
public static final String COLLECTIONP_ROTOCOL_REGISTRATION_ADD_ACTION = "CollectionProtocolRegistrationAdd.do";
public static final String COLLECTION_PROTOCOL_REGISTRATION_EDIT_ACTION = "CollectionProtocolRegistrationEdit.do";
//Constants required in CancerResearchGroup.jsp Page
public static final String CANCER_RESEARCH_GROUP_SEARCH_ACTION = "CancerResearchGroupSearch.do";
public static final String CANCER_RESEARCH_GROUP_ADD_ACTION = "CancerResearchGroupAdd.do";
public static final String CANCER_RESEARCH_GROUP_EDIT_ACTION = "CancerResearchGroupEdit.do";
//Constants required for Approve user
public static final String USER_DETAILS_SHOW_ACTION = "UserDetailsShow.do";
public static final String APPROVE_USER_SHOW_ACTION = "ApproveUserShow.do";
//Reported Problem Constants
public static final String REPORTED_PROBLEM_ADD_ACTION = "ReportedProblemAdd.do";
public static final String REPORTED_PROBLEM_EDIT_ACTION = "ReportedProblemEdit.do";
public static final String PROBLEM_DETAILS_ACTION = "ProblemDetails.do";
public static final String REPORTED_PROBLEM_SHOW_ACTION = "ReportedProblemShow.do";
//Query Results view Actions
public static final String TREE_VIEW_ACTION = "TreeView.do";
public static final String DATA_VIEW_FRAME_ACTION = "SpreadsheetView.do";
public static final String SIMPLE_QUERY_INTERFACE_URL = "SimpleQueryInterface.do?pageOf=pageOfSimpleQueryInterface&menuSelected=17";
//New Specimen Data Actions.
public static final String SPECIMEN_ADD_ACTION = "NewSpecimenAdd.do";
public static final String SPECIMEN_EDIT_ACTION = "NewSpecimenEdit.do";
public static final String SPECIMEN_SEARCH_ACTION = "NewSpecimenSearch.do";
public static final String SPECIMEN_EVENT_PARAMETERS_ACTION = "ListSpecimenEventParameters.do";
//Create Specimen Data Actions.
public static final String CREATE_SPECIMEN_ADD_ACTION = "AddSpecimen.do";
public static final String CREATE_SPECIMEN_EDIT_ACTION = "CreateSpecimenEdit.do";
public static final String CREATE_SPECIMEN_SEARCH_ACTION = "CreateSpecimenSearch.do";
//ShoppingCart Actions.
public static final String SHOPPING_CART_OPERATION = "ShoppingCartOperation.do";
public static final String SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "SpecimenCollectionGroup.do";
public static final String SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "SpecimenCollectionGroupAdd.do";
public static final String SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "SpecimenCollectionGroupEdit.do";
//Constants required in FrozenEventParameters.jsp Page
public static final String FROZEN_EVENT_PARAMETERS_SEARCH_ACTION = "FrozenEventParametersSearch.do";
public static final String FROZEN_EVENT_PARAMETERS_ADD_ACTION = "FrozenEventParametersAdd.do";
public static final String FROZEN_EVENT_PARAMETERS_EDIT_ACTION = "FrozenEventParametersEdit.do";
//Constants required in CheckInCheckOutEventParameters.jsp Page
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_SEARCH_ACTION = "CheckInCheckOutEventParametersSearch.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_ADD_ACTION = "CheckInCheckOutEventParametersAdd.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_EDIT_ACTION = "CheckInCheckOutEventParametersEdit.do";
//Constants required in ReceivedEventParameters.jsp Page
public static final String RECEIVED_EVENT_PARAMETERS_SEARCH_ACTION = "receivedEventParametersSearch.do";
public static final String RECEIVED_EVENT_PARAMETERS_ADD_ACTION = "ReceivedEventParametersAdd.do";
public static final String RECEIVED_EVENT_PARAMETERS_EDIT_ACTION = "receivedEventParametersEdit.do";
//Constants required in FluidSpecimenReviewEventParameters.jsp Page
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "FluidSpecimenReviewEventParametersSearch.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "FluidSpecimenReviewEventParametersAdd.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "FluidSpecimenReviewEventParametersEdit.do";
//Constants required in CELLSPECIMENREVIEWParameters.jsp Page
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "CellSpecimenReviewParametersSearch.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "CellSpecimenReviewParametersAdd.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "CellSpecimenReviewParametersEdit.do";
//Constants required in tissue SPECIMEN REVIEW event Parameters.jsp Page
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "TissueSpecimenReviewEventParametersSearch.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "TissueSpecimenReviewEventParametersAdd.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "TissueSpecimenReviewEventParametersEdit.do";
// Constants required in DisposalEventParameters.jsp Page
public static final String DISPOSAL_EVENT_PARAMETERS_SEARCH_ACTION = "DisposalEventParametersSearch.do";
public static final String DISPOSAL_EVENT_PARAMETERS_ADD_ACTION = "DisposalEventParametersAdd.do";
public static final String DISPOSAL_EVENT_PARAMETERS_EDIT_ACTION = "DisposalEventParametersEdit.do";
// Constants required in ThawEventParameters.jsp Page
public static final String THAW_EVENT_PARAMETERS_SEARCH_ACTION = "ThawEventParametersSearch.do";
public static final String THAW_EVENT_PARAMETERS_ADD_ACTION = "ThawEventParametersAdd.do";
public static final String THAW_EVENT_PARAMETERS_EDIT_ACTION = "ThawEventParametersEdit.do";
// Constants required in MOLECULARSPECIMENREVIEWParameters.jsp Page
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "MolecularSpecimenReviewParametersSearch.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "MolecularSpecimenReviewParametersAdd.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "MolecularSpecimenReviewParametersEdit.do";
// Constants required in CollectionEventParameters.jsp Page
public static final String COLLECTION_EVENT_PARAMETERS_SEARCH_ACTION = "CollectionEventParametersSearch.do";
public static final String COLLECTION_EVENT_PARAMETERS_ADD_ACTION = "CollectionEventParametersAdd.do";
public static final String COLLECTION_EVENT_PARAMETERS_EDIT_ACTION = "CollectionEventParametersEdit.do";
// Constants required in SpunEventParameters.jsp Page
public static final String SPUN_EVENT_PARAMETERS_SEARCH_ACTION = "SpunEventParametersSearch.do";
public static final String SPUN_EVENT_PARAMETERS_ADD_ACTION = "SpunEventParametersAdd.do";
public static final String SPUN_EVENT_PARAMETERS_EDIT_ACTION = "SpunEventParametersEdit.do";
// Constants required in EmbeddedEventParameters.jsp Page
public static final String EMBEDDED_EVENT_PARAMETERS_SEARCH_ACTION = "EmbeddedEventParametersSearch.do";
public static final String EMBEDDED_EVENT_PARAMETERS_ADD_ACTION = "EmbeddedEventParametersAdd.do";
public static final String EMBEDDED_EVENT_PARAMETERS_EDIT_ACTION = "EmbeddedEventParametersEdit.do";
// Constants required in TransferEventParameters.jsp Page
public static final String TRANSFER_EVENT_PARAMETERS_SEARCH_ACTION = "TransferEventParametersSearch.do";
public static final String TRANSFER_EVENT_PARAMETERS_ADD_ACTION = "TransferEventParametersAdd.do";
public static final String TRANSFER_EVENT_PARAMETERS_EDIT_ACTION = "TransferEventParametersEdit.do";
// Constants required in FixedEventParameters.jsp Page
public static final String FIXED_EVENT_PARAMETERS_SEARCH_ACTION = "FixedEventParametersSearch.do";
public static final String FIXED_EVENT_PARAMETERS_ADD_ACTION = "FixedEventParametersAdd.do";
public static final String FIXED_EVENT_PARAMETERS_EDIT_ACTION = "FixedEventParametersEdit.do";
// Constants required in ProcedureEventParameters.jsp Page
public static final String PROCEDURE_EVENT_PARAMETERS_SEARCH_ACTION = "ProcedureEventParametersSearch.do";
public static final String PROCEDURE_EVENT_PARAMETERS_ADD_ACTION = "ProcedureEventParametersAdd.do";
public static final String PROCEDURE_EVENT_PARAMETERS_EDIT_ACTION = "ProcedureEventParametersEdit.do";
// Constants required in Distribution.jsp Page
public static final String DISTRIBUTION_SEARCH_ACTION = "DistributionSearch.do";
public static final String DISTRIBUTION_ADD_ACTION = "DistributionAdd.do";
public static final String DISTRIBUTION_EDIT_ACTION = "DistributionEdit.do";
public static final String SPECIMENARRAYTYPE_ADD_ACTION = "SpecimenArrayTypeAdd.do?operation=add";
public static final String SPECIMENARRAYTYPE_EDIT_ACTION = "SpecimenArrayTypeEdit.do?operation=edit";
public static final String ARRAY_DISTRIBUTION_ADD_ACTION = "ArrayDistributionAdd.do";
public static final String SPECIMENARRAY_ADD_ACTION = "SpecimenArrayAdd.do";
public static final String SPECIMENARRAY_EDIT_ACTION = "SpecimenArrayEdit.do";
//Spreadsheet Export Action
public static final String SPREADSHEET_EXPORT_ACTION = "SpreadsheetExport.do";
//Aliquots Action
public static final String ALIQUOT_ACTION = "Aliquots.do";
public static final String CREATE_ALIQUOT_ACTION = "CreateAliquots.do";
public static final String ALIQUOT_SUMMARY_ACTION = "AliquotSummary.do";
//Constants required in Ordering System.
public static final String ACTION_ORDER_LIST = "OrderExistingSpecimen.do";
public static final String SPECIMEN_TREE_SPECIMEN_ID = "specimenId";
public static final String SPECIMEN_TREE_SPECCOLLGRP_ID = "specimenCollGrpId";
public static final String ACTION_REMOVE_ORDER_ITEM = "AddToOrderListSpecimen.do?remove=yes";
public static final String ACTION_REMOVE_ORDER_ITEM_ARRAY = "AddToOrderListArray.do?remove=yes";
public static final String ACTION_REMOVE_ORDER_ITEM_PATHOLOGYCASE = "AddToOrderListPathologyCase.do?remove=yes";
public static final String DEFINEARRAY_REQUESTMAP_LIST = "definedArrayRequestMapList";
public static final String CREATE_DEFINED_ARRAY = "CreateDefinedArray.do";
public static final String ACTION_SAVE_ORDER_ITEM = "SaveOrderItems.do";
public static final String ORDERTO_LIST_ARRAY = "orderToListArrayList";
public static final String ACTION_SAVE_ORDER_ARRAY_ITEM = "SaveOrderArrayItems.do";
public static final String ACTION_SAVE_ORDER_PATHOLOGY_ITEM="SaveOrderPathologyItems.do";
public static final String ACTION_ADD_ORDER_SPECIMEN_ITEM="AddToOrderListSpecimen.do";
public static final String ACTION_ADD_ORDER_ARRAY_ITEM="AddToOrderListArray.do";
public static final String ACTION_ADD_ORDER_PATHOLOGY_ITEM="AddToOrderListPathologyCase.do";
public static final String ACTION_DEFINE_ARRAY="DefineArraySubmit.do";
public static final String ACTION_ORDER_SPECIMEN="OrderExistingSpecimen.do";
public static final String ACTION_ORDER_BIOSPECIMENARRAY="OrderBiospecimenArray.do";
public static final String ACTION_ORDER_PATHOLOGYCASE="OrderPathologyCase.do";
//Constants related to Aliquots functionality
public static final String PAGEOF_ALIQUOT = "pageOfAliquot";
public static final String PAGEOF_CREATE_ALIQUOT = "pageOfCreateAliquot";
public static final String PAGEOF_ALIQUOT_SUMMARY = "pageOfAliquotSummary";
public static final String AVAILABLE_CONTAINER_MAP = "availableContainerMap";
public static final String COMMON_ADD_EDIT = "commonAddEdit";
//Constants related to SpecimenArrayAliquots functionality
public static final String STORAGE_TYPE_ID="storageTypeId";
public static final String ALIQUOT_SPECIMEN_ARRAY_TYPE="SpecimenArrayType";
public static final String ALIQUOT_SPECIMEN_CLASS="SpecimenClass";
public static final String ALIQUOT_SPECIMEN_TYPES="SpecimenTypes";
public static final String ALIQUOT_ALIQUOT_COUNTS="AliquotCounts";
//Specimen Array Aliquots pages
public static final String PAGEOF_SPECIMEN_ARRAY_ALIQUOT = "pageOfSpecimenArrayAliquot";
public static final String PAGEOF_SPECIMEN_ARRAY_CREATE_ALIQUOT = "pageOfSpecimenArrayCreateAliquot";
public static final String PAGEOF_SPECIMEN_ARRAY_ALIQUOT_SUMMARY = "pageOfSpecimenArrayAliquotSummary";
//Specimen Array Aliquots Action
public static final String SPECIMEN_ARRAY_ALIQUOT_ACTION = "SpecimenArrayAliquots.do";
public static final String SPECIMEN_ARRAY_CREATE_ALIQUOT_ACTION = "SpecimenArrayCreateAliquots.do";
//Constants related to QuickEvents functionality
public static final String QUICKEVENTS_ACTION = "QuickEventsSearch.do";
public static final String QUICKEVENTSPARAMETERS_ACTION = "ListSpecimenEventParameters.do";
//SimilarContainers Action
public static final String SIMILAR_CONTAINERS_ACTION = "SimilarContainers.do";
public static final String CREATE_SIMILAR_CONTAINERS_ACTION = "CreateSimilarContainers.do";
public static final String SIMILAR_CONTAINERS_ADD_ACTION = "SimilarContainersAdd.do";
//Constants related to Similar Containsers
public static final String PAGEOF_SIMILAR_CONTAINERS = "pageOfSimilarContainers";
public static final String PAGEOF_CREATE_SIMILAR_CONTAINERS = "pageOfCreateSimilarContainers";
public static final String PAGEOF_STORAGE_CONTAINER = "pageOfStorageContainer";
//Levels of nodes in query results tree.
public static final int MAX_LEVEL = 5;
public static final int MIN_LEVEL = 1;
public static final String TABLE_NAME_COLUMN = "TABLE_NAME";
//Spreadsheet view Constants in DataViewAction.
public static final String PARTICIPANT = "Participant";
public static final String ACCESSION = "Accession";
public static final String QUERY_PARTICIPANT_SEARCH_ACTION = "QueryParticipantSearch.do?id=";
public static final String QUERY_PARTICIPANT_EDIT_ACTION = "QueryParticipantEdit.do";
public static final String QUERY_COLLECTION_PROTOCOL_SEARCH_ACTION = "QueryCollectionProtocolSearch.do?id=";
public static final String QUERY_COLLECTION_PROTOCOL_EDIT_ACTION = "QueryCollectionProtocolEdit.do";
public static final String QUERY_SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "QuerySpecimenCollectionGroupSearch.do?id=";
public static final String QUERY_SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "QuerySpecimenCollectionGroupEdit.do";
public static final String QUERY_SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "QuerySpecimenCollectionGroupAdd.do";
public static final String QUERY_SPECIMEN_SEARCH_ACTION = "QuerySpecimenSearch.do?id=";
public static final String QUERY_SPECIMEN_EDIT_ACTION = "QuerySpecimenEdit.do";
//public static final String QUERY_ACCESSION_SEARCH_ACTION = "QueryAccessionSearch.do?id=";
public static final String SPECIMEN = "Specimen";
public static final String SEGMENT = "Segment";
public static final String SAMPLE = "Sample";
public static final String COLLECTION_PROTOCOL_REGISTRATION = "CollectionProtocolRegistration";
public static final String PARTICIPANT_ID_COLUMN = "PARTICIPANT_ID";
public static final String ACCESSION_ID_COLUMN = "ACCESSION_ID";
public static final String SPECIMEN_ID_COLUMN = "SPECIMEN_ID";
public static final String SEGMENT_ID_COLUMN = "SEGMENT_ID";
public static final String SAMPLE_ID_COLUMN = "SAMPLE_ID";
//For getting the tables for Simple Query and Fcon Query.
public static final int ADVANCE_QUERY_TABLES = 2;
//Identifiers for various Form beans
public static final int DEFAULT_BIZ_LOGIC = 0;
public static final int USER_FORM_ID = 1;
public static final int ACCESSION_FORM_ID = 3;
public static final int REPORTED_PROBLEM_FORM_ID = 4;
public static final int INSTITUTION_FORM_ID = 5;
public static final int APPROVE_USER_FORM_ID = 6;
public static final int ACTIVITY_STATUS_FORM_ID = 7;
public static final int DEPARTMENT_FORM_ID = 8;
public static final int COLLECTION_PROTOCOL_FORM_ID = 9;
public static final int DISTRIBUTIONPROTOCOL_FORM_ID = 10;
public static final int STORAGE_CONTAINER_FORM_ID = 11;
public static final int STORAGE_TYPE_FORM_ID = 12;
public static final int SITE_FORM_ID = 13;
public static final int CANCER_RESEARCH_GROUP_FORM_ID = 14;
public static final int BIOHAZARD_FORM_ID = 15;
public static final int FROZEN_EVENT_PARAMETERS_FORM_ID = 16;
public static final int CHECKIN_CHECKOUT_EVENT_PARAMETERS_FORM_ID = 17;
public static final int RECEIVED_EVENT_PARAMETERS_FORM_ID = 18;
public static final int FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 21;
public static final int CELL_SPECIMEN_REVIEW_PARAMETERS_FORM_ID =23;
public static final int TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 24;
public static final int DISPOSAL_EVENT_PARAMETERS_FORM_ID = 25;
public static final int THAW_EVENT_PARAMETERS_FORM_ID = 26;
public static final int MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_FORM_ID = 27;
public static final int COLLECTION_EVENT_PARAMETERS_FORM_ID = 28;
public static final int TRANSFER_EVENT_PARAMETERS_FORM_ID = 29;
public static final int SPUN_EVENT_PARAMETERS_FORM_ID = 30;
public static final int EMBEDDED_EVENT_PARAMETERS_FORM_ID = 31;
public static final int FIXED_EVENT_PARAMETERS_FORM_ID = 32;
public static final int PROCEDURE_EVENT_PARAMETERS_FORM_ID = 33;
public static final int CREATE_SPECIMEN_FORM_ID = 34;
public static final int FORGOT_PASSWORD_FORM_ID = 35;
public static final int SIGNUP_FORM_ID = 36;
public static final int DISTRIBUTION_FORM_ID = 37;
public static final int SPECIMEN_EVENT_PARAMETERS_FORM_ID = 38;
public static final int SHOPPING_CART_FORM_ID = 39;
public static final int CONFIGURE_RESULT_VIEW_ID = 41;
public static final int ADVANCE_QUERY_INTERFACE_ID = 42;
public static final int COLLECTION_PROTOCOL_REGISTRATION_FORM_ID = 19;
public static final int PARTICIPANT_FORM_ID = 2;
public static final int SPECIMEN_COLLECTION_GROUP_FORM_ID = 20;
public static final int NEW_SPECIMEN_FORM_ID = 22;
public static final int ALIQUOT_FORM_ID = 44;
public static final int QUICKEVENTS_FORM_ID = 45;
public static final int LIST_SPECIMEN_EVENT_PARAMETERS_FORM_ID = 46;
public static final int SIMILAR_CONTAINERS_FORM_ID = 47; // chetan (13-07-2006)
public static final int SPECIMEN_ARRAY_TYPE_FORM_ID = 48;
public static final int ARRAY_DISTRIBUTION_FORM_ID = 49;
public static final int SPECIMEN_ARRAY_FORM_ID = 50;
public static final int SPECIMEN_ARRAY_ALIQUOT_FORM_ID = 51;
public static final int ASSIGN_PRIVILEGE_FORM_ID = 52;
public static final int CDE_FORM_ID = 53;
public static final int MULTIPLE_SPECIMEN_STOGAGE_LOCATION_FORM_ID = 54;
//Misc
public static final String SEPARATOR = " : ";
// CATIES
public static final int SURGICAL_PATHOLOGY_REPORT_FORM_ID=60;
public static final int DEIDENTIFIED_SURGICAL_PATHOLOGY_REPORT_FORM_ID=61;
//Ordering System
public static final int REQUEST_DETAILS_FORM_ID = 54;
public static final int REQUEST_LIST_FILTERATION_FORM_ID = 55;
public static final int ORDER_FORM_ID = 56;
public static final int ORDER_ARRAY_FORM_ID = 57;
public static final int ORDER_PATHOLOGY_FORM_ID = 58;
public static final int NEW_PATHOLOGY_FORM_ID=59;
//Identifiers for JDBC DAO.
public static final int QUERY_RESULT_TREE_JDBC_DAO = 1;
//Activity Status values
public static final String ACTIVITY_STATUS_APPROVE = "Approve";
public static final String ACTIVITY_STATUS_REJECT = "Reject";
public static final String ACTIVITY_STATUS_NEW = "New";
public static final String ACTIVITY_STATUS_PENDING = "Pending";
//Approve User status values.
public static final String APPROVE_USER_APPROVE_STATUS = "Approve";
public static final String APPROVE_USER_REJECT_STATUS = "Reject";
public static final String APPROVE_USER_PENDING_STATUS = "Pending";
//Approve User Constants
public static final int ZERO = 0;
public static final int START_PAGE = 1;
public static final int NUMBER_RESULTS_PER_PAGE = 10;
public static final int NUMBER_RESULTS_PER_PAGE_SEARCH = 15;
public static final String PAGE_NUMBER = "pageNum";
public static final String RESULTS_PER_PAGE = "numResultsPerPage";
public static final String TOTAL_RESULTS = "totalResults";
public static final String PREVIOUS_PAGE = "prevpage";
public static final String NEXT_PAGE = "nextPage";
public static final String ORIGINAL_DOMAIN_OBJECT_LIST = "originalDomainObjectList";
public static final String SHOW_DOMAIN_OBJECT_LIST = "showDomainObjectList";
public static final String USER_DETAILS = "details";
public static final String CURRENT_RECORD = "currentRecord";
public static final String APPROVE_USER_EMAIL_SUBJECT = "Your membership status in caTISSUE Core.";
//Query Interface Results View Constants
public static final String PAGEOF_APPROVE_USER = "pageOfApproveUser";
public static final String PAGEOF_SIGNUP = "pageOfSignUp";
public static final String PAGEOF_USERADD = "pageOfUserAdd";
public static final String PAGEOF_USER_ADMIN = "pageOfUserAdmin";
public static final String PAGEOF_USER_PROFILE = "pageOfUserProfile";
public static final String PAGEOF_CHANGE_PASSWORD = "pageOfChangePassword";
//For Simple Query Interface and Edit.
public static final String PAGEOF_EDIT_OBJECT = "pageOfEditObject";
//Query results view temporary table columns.
public static final String QUERY_RESULTS_PARTICIPANT_ID = "PARTICIPANT_ID";
public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_ID = "COLLECTION_PROTOCOL_ID";
public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID = "COLLECTION_PROTOCOL_EVENT_ID";
public static final String QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID = "SPECIMEN_COLLECTION_GROUP_ID";
public static final String QUERY_RESULTS_SPECIMEN_ID = "SPECIMEN_ID";
public static final String QUERY_RESULTS_SPECIMEN_TYPE = "SPECIMEN_TYPE";
// Assign Privilege Constants.
public static final boolean PRIVILEGE_DEASSIGN = false;
public static final String OPERATION_DISALLOW = "Disallow";
//Constants for default column names to be shown for query result.
public static final String[] DEFAULT_SPREADSHEET_COLUMNS = {
// QUERY_RESULTS_PARTICIPANT_ID,QUERY_RESULTS_COLLECTION_PROTOCOL_ID,
// QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID,QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID,
// QUERY_RESULTS_SPECIMEN_ID,QUERY_RESULTS_SPECIMEN_TYPE
"IDENTIFIER","TYPE","ONE_DIMENSION_LABEL"
};
//Query results edit constants - MakeEditableAction.
public static final String EDITABLE = "editable";
//URL paths for Applet in TreeView.jsp
public static final String QUERY_TREE_APPLET = "edu/wustl/common/treeApplet/TreeApplet.class";
public static final String APPLET_CODEBASE = "Applet";
//Shopping Cart
public static final String SHOPPING_CART = "shoppingCart";
public static final int SELECT_OPTION_VALUE = -1;
public static final String [] TIME_HOUR_AMPM_ARRAY = {"AM","PM"};
// Constants required in CollectionProtocol.jsp Page
public static final String COLLECTIONPROTOCOL_SEARCH_ACTION = "CollectionProtocolSearch.do";
public static final String COLLECTIONPROTOCOL_ADD_ACTION = "CollectionProtocolAdd.do";
public static final String COLLECTIONPROTOCOL_EDIT_ACTION = "CollectionProtocolEdit.do";
// Constants required in DistributionProtocol.jsp Page
public static final String DISTRIBUTIONPROTOCOL_SEARCH_ACTION = "DistributionProtocolSearch.do";
public static final String DISTRIBUTIONPROTOCOL_ADD_ACTION = "DistributionProtocolAdd.do";
public static final String DISTRIBUTIONPROTOCOL_EDIT_ACTION = "DistributionProtocolEdit.do";
public static final String [] ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed",
"Disabled"
};
public static final String [] SITE_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed"
};
public static final String [] USER_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed"
};
public static final String [] APPROVE_USER_STATUS_VALUES = {
SELECT_OPTION,
APPROVE_USER_APPROVE_STATUS,
APPROVE_USER_REJECT_STATUS,
APPROVE_USER_PENDING_STATUS,
};
public static final String [] REPORTED_PROBLEM_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Closed",
"Pending"
};
public static final String [] DISPOSAL_EVENT_ACTIVITY_STATUS_VALUES = {
"Closed",
"Disabled"
};
public static final String TISSUE = "Tissue";
public static final String FLUID = "Fluid";
public static final String CELL = "Cell";
public static final String MOLECULAR = "Molecular";
public static final String [] SPECIMEN_TYPE_VALUES = {
SELECT_OPTION,
TISSUE,
FLUID,
CELL,
MOLECULAR
};
public static final String [] HOUR_ARRAY = {
"00",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23"
};
public static final String [] MINUTES_ARRAY = {
"00",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23",
"24",
"25",
"26",
"27",
"28",
"29",
"30",
"31",
"32",
"33",
"34",
"35",
"36",
"37",
"38",
"39",
"40",
"41",
"42",
"43",
"44",
"45",
"46",
"47",
"48",
"49",
"50",
"51",
"52",
"53",
"54",
"55",
"56",
"57",
"58",
"59"
};
public static final String UNIT_GM = "gm";
public static final String UNIT_ML = "ml";
public static final String UNIT_CC = "cell count";
public static final String UNIT_MG = "g";
public static final String UNIT_CN = "count";
public static final String UNIT_CL = "cells";
public static final String CDE_NAME_CLINICAL_STATUS = "Clinical Status";
public static final String CDE_NAME_GENDER = "Gender";
public static final String CDE_NAME_GENOTYPE = "Genotype";
public static final String CDE_NAME_SPECIMEN_CLASS = "Specimen";
public static final String CDE_NAME_SPECIMEN_TYPE = "Specimen Type";
public static final String CDE_NAME_TISSUE_SIDE = "Tissue Side";
public static final String CDE_NAME_PATHOLOGICAL_STATUS = "Pathological Status";
public static final String CDE_NAME_RECEIVED_QUALITY = "Received Quality";
public static final String CDE_NAME_FIXATION_TYPE = "Fixation Type";
public static final String CDE_NAME_COLLECTION_PROCEDURE = "Collection Procedure";
public static final String CDE_NAME_CONTAINER = "Container";
public static final String CDE_NAME_METHOD = "Method";
public static final String CDE_NAME_EMBEDDING_MEDIUM = "Embedding Medium";
public static final String CDE_NAME_BIOHAZARD = "Biohazard";
public static final String CDE_NAME_ETHNICITY = "Ethnicity";
public static final String CDE_NAME_RACE = "Race";
public static final String CDE_VITAL_STATUS = "Vital Status";
public static final String CDE_NAME_CLINICAL_DIAGNOSIS = "Clinical Diagnosis";
public static final String CDE_NAME_SITE_TYPE = "Site Type";
public static final String CDE_NAME_COUNTRY_LIST = "Countries";
public static final String CDE_NAME_STATE_LIST = "States";
public static final String CDE_NAME_HISTOLOGICAL_QUALITY = "Histological Quality";
//Constants for Advanced Search
public static final String STRING_OPERATORS = "StringOperators";
public static final String DATE_NUMERIC_OPERATORS = "DateNumericOperators";
public static final String ENUMERATED_OPERATORS = "EnumeratedOperators";
public static final String MULTI_ENUMERATED_OPERATORS = "MultiEnumeratedOperators";
public static final String [] STORAGE_STATUS_ARRAY = {
SELECT_OPTION,
"CHECK IN",
"CHECK OUT"
};
// constants for Data required in query
public static final String ALIAS_NAME_TABLE_NAME_MAP="objectTableNames";
public static final String SYSTEM_IDENTIFIER_COLUMN_NAME = "IDENTIFIER";
public static final String NAME = "name";
public static final String EVENT_PARAMETERS[] = { Constants.SELECT_OPTION,
"Cell Specimen Review", "Check In Check Out", "Collection",
"Disposal", "Embedded", "Fixed", "Fluid Specimen Review",
"Frozen", "Molecular Specimen Review", "Procedure", "Received",
"Spun", "Thaw", "Tissue Specimen Review", "Transfer" };
public static final String EVENT_PARAMETERS_COLUMNS[] = { "Identifier",
"Event Parameter", "User", "Date / Time", "PageOf"};
public static final String DERIVED_SPECIMEN_COLUMNS[] = { "Label",
"Class", "Type", "Quantity", "rowSelected"};
public static final String [] SHOPPING_CART_COLUMNS = {"","Identifier",
"Type", "Subtype", "Tissue Site", "Tissue Side", "Pathological Status"};
public static final String [] SHOPPING_CART_COLUMNS_FOR_PATHOLOGICAL_CASES = {"",
"Accession No.","Specimen Collection Group","Source","Report Status"};
public static final String [] SHOPPING_CART_COLUMNS_FOR_ARRAY = {"",
"Name", "Barcode", "Type"};
//Constants required in AssignPrivileges.jsp
public static final String ASSIGN = "assignOperation";
public static final String PRIVILEGES = "privileges";
public static final String OBJECT_TYPES = "objectTypes";
public static final String OBJECT_TYPE_VALUES = "objectTypeValues";
public static final String RECORD_IDS = "recordIds";
public static final String ATTRIBUTES = "attributes";
public static final String GROUPS = "groups";
public static final String USERS_FOR_USE_PRIVILEGE = "usersForUsePrivilege";
public static final String USERS_FOR_READ_PRIVILEGE = "usersForReadPrivilege";
public static final String ASSIGN_PRIVILEGES_ACTION = "AssignPrivileges.do";
public static final int CONTAINER_IN_ANOTHER_CONTAINER = 2;
/**
* @param id
* @return
*/
public static String getUserPGName(Long identifier)
{
if(identifier == null)
{
return "USER_";
}
return "USER_"+identifier;
}
/**
* @param id
* @return
*/
public static String getUserGroupName(Long identifier)
{
if(identifier == null)
{
return "USER_";
}
return "USER_"+identifier;
}
//Mandar 25-Apr-06 : bug 1414 : Tissue units as per type
// tissue types with unit= count
public static final String FROZEN_TISSUE_BLOCK = "Frozen Tissue Block"; // PREVIOUS FROZEN BLOCK
public static final String FROZEN_TISSUE_SLIDE = "Frozen Tissue Slide"; // SLIDE
public static final String FIXED_TISSUE_BLOCK = "Fixed Tissue Block"; // PARAFFIN BLOCK
public static final String NOT_SPECIFIED = "Not Specified";
public static final String WITHDRAWN = "Withdrawn";
// tissue types with unit= g
public static final String FRESH_TISSUE = "Fresh Tissue";
public static final String FROZEN_TISSUE = "Frozen Tissue";
public static final String FIXED_TISSUE = "Fixed Tissue";
public static final String FIXED_TISSUE_SLIDE = "Fixed Tissue Slide";
//tissue types with unit= cc
public static final String MICRODISSECTED = "Microdissected";
// constants required for Distribution Report
public static final String CONFIGURATION_TABLES = "configurationTables";
public static final String DISTRIBUTION_TABLE_AlIAS[] = {"CollectionProtReg","Participant","Specimen",
"SpecimenCollectionGroup","DistributedItem"};
public static final String TABLE_COLUMN_DATA_MAP = "tableColumnDataMap";
public static final String CONFIGURE_RESULT_VIEW_ACTION = "ConfigureResultView.do";
public static final String TABLE_NAMES_LIST = "tableNamesList";
public static final String COLUMN_NAMES_LIST = "columnNamesList";
public static final String SPECIMEN_COLUMN_NAMES_LIST = "specimenColumnNamesList";
public static final String DISTRIBUTION_ID = "distributionId";
public static final String CONFIGURE_DISTRIBUTION_ACTION = "ConfigureDistribution.do";
public static final String DISTRIBUTION_REPORT_ACTION = "DistributionReport.do";
public static final String ARRAY_DISTRIBUTION_REPORT_ACTION = "ArrayDistributionReport.do";
public static final String DISTRIBUTION_REPORT_SAVE_ACTION="DistributionReportSave.do";
public static final String ARRAY_DISTRIBUTION_REPORT_SAVE_ACTION="ArrayDistributionReportSave.do";
public static final String SELECTED_COLUMNS[] = {"Specimen.IDENTIFIER.Identifier : Specimen",
"Specimen.TYPE.Type : Specimen",
"SpecimenCharacteristics.TISSUE_SITE.Tissue Site : Specimen",
"SpecimenCharacteristics.TISSUE_SIDE.Tissue Side : Specimen",
"Specimen.PATHOLOGICAL_STATUS.Pathological Status : Specimen",
"DistributedItem.QUANTITY.Quantity : Distribution"};
//"SpecimenCharacteristics.PATHOLOGICAL_STATUS.Pathological Status : Specimen",
public static final String SPECIMEN_IN_ARRAY_SELECTED_COLUMNS[] = {
"Specimen.LABEL.Label : Specimen",
"Specimen.BARCODE.barcode : Specimen",
"SpecimenArrayContent.PositionDimensionOne.PositionDimensionOne : Specimen",
"SpecimenArrayContent.PositionDimensionTwo.PositionDimensionTwo : Specimen",
"Specimen.CLASS.CLASS : Specimen",
"Specimen.TYPE.Type : Specimen",
"SpecimenCharacteristics.TISSUE_SIDE.Tissue Side : Specimen",
"SpecimenCharacteristics.TISSUE_SITE.Tissue Site : Specimen",
};
public static final String ARRAY_SELECTED_COLUMNS[] = {
"SpecimenArray.Name.Name : SpecimenArray",
"Container.barcode.Barcode : SpecimenArray",
"ContainerType.name.ArrayType : ContainerType",
"Container.PositionDimensionOne.Position One: Container",
"Container.PositionDimensionTwo.Position Two: Container",
"Container.CapacityOne.Dimension One: Container",
"Container.CapacityTwo.Dimension Two: Container",
"ContainerType.SpecimenClass.specimen class : ContainerType",
"ContainerType.SpecimenTypes.specimen Types : ContainerType",
"Container.Comment.comment: Container",
};
public static final String SPECIMEN_ID_LIST = "specimenIdList";
public static final String DISTRIBUTION_ACTION = "Distribution.do?pageOf=pageOfDistribution";
public static final String DISTRIBUTION_REPORT_NAME = "Distribution Report.csv";
public static final String DISTRIBUTION_REPORT_FORM="distributionReportForm";
public static final String DISTRIBUTED_ITEMS_DATA = "distributedItemsData";
public static final String DISTRIBUTED_ITEM = "DistributedItem";
//constants for Simple Query Interface Configuration
public static final String CONFIGURE_SIMPLE_QUERY_ACTION = "ConfigureSimpleQuery.do";
public static final String CONFIGURE_SIMPLE_QUERY_VALIDATE_ACTION = "ConfigureSimpleQueryValidate.do";
public static final String CONFIGURE_SIMPLE_SEARCH_ACTION = "ConfigureSimpleSearch.do";
public static final String SIMPLE_SEARCH_ACTION = "SimpleSearch.do";
public static final String SIMPLE_SEARCH_AFTER_CONFIGURE_ACTION = "SimpleSearchAfterConfigure.do";
public static final String PAGEOF_DISTRIBUTION = "pageOfDistribution";
public static final String RESULT_VIEW_VECTOR = "resultViewVector";
public static final String SPECIMENT_VIEW_ATTRIBUTE = "defaultViewAttribute";
//public static final String SIMPLE_QUERY_COUNTER = "simpleQueryCount";
public static final String UNDEFINED = "Undefined";
public static final String UNKNOWN = "Unknown";
public static final String UNSPECIFIED = "Unspecified";
public static final String NOTSPECIFIED = "Not Specified";
public static final String SEARCH_RESULT = "SearchResult.csv";
// Mandar : LightYellow and Green colors for CollectionProtocol SpecimenRequirements. Bug id: 587
// public static final String ODD_COLOR = "#FEFB85";
// public static final String EVEN_COLOR = "#A7FEAB";
// Light and dark shades of GREY.
public static final String ODD_COLOR = "#E5E5E5";
public static final String EVEN_COLOR = "#F7F7F7";
// TO FORWARD THE REQUEST ON SUBMIT IF STATUS IS DISABLED
public static final String BIO_SPECIMEN = "/ManageBioSpecimen.do";
public static final String ADMINISTRATIVE = "/ManageAdministrativeData.do";
public static final String PARENT_SPECIMEN_ID = "parentSpecimenId";
public static final String COLLECTION_REGISTRATION_ID = "collectionProtocolId";
public static final String FORWARDLIST = "forwardToList";
public static final String [][] SPECIMEN_FORWARD_TO_LIST = {
{"Submit", "success"},
{"Derive", "createNew"},
{"Add Events", "eventParameters"},
{"More", "sameCollectionGroup"},
{"Distribute", "distribution" }
};
public static final String [] SPECIMEN_BUTTON_TIPS = {
"Submit only",
"Submit and derive",
"Submit and add events",
"Submit and add more to same group",
"Submit and distribute"
};
public static final String [][] SPECIMEN_COLLECTION_GROUP_FORWARD_TO_LIST = {
{"Submit", "success"},
{"Add Specimen", "createNewSpecimen"},
{"Add Multiple Specimen", "createMultipleSpecimen"}
};
public static final String [][] PROTOCOL_REGISTRATION_FORWARD_TO_LIST = {
{"Submit", "success"},
{"Specimen Collection Group", "createSpecimenCollectionGroup"}
};
public static final String [][] PARTICIPANT_FORWARD_TO_LIST = {
{"Submit", "success"},
{"Register to Protocol", "createParticipantRegistration"},
{"Specimen Collection Group", "specimenCollectionGroup"}
};
public static final String [][] STORAGE_TYPE_FORWARD_TO_LIST = {
{"Submit", "success"},
{"Add Container", "storageContainer"}
};
//Constants Required for Advance Search
//Tree related
//public static final String PARTICIPANT ='Participant';
public static final String[] ADVANCE_QUERY_TREE_HEIRARCHY={ //Represents the Advance Query tree Heirarchy.
Constants.PARTICIPANT,
Constants.COLLECTION_PROTOCOL,
Constants.SPECIMEN_COLLECTION_GROUP,
Constants.SPECIMEN
};
public static final String MENU_COLLECTION_PROTOCOL ="Collection Protocol";
public static final String MENU_SPECIMEN_COLLECTION_GROUP ="Specimen Collection Group";
public static final String MENU_DISTRIBUTION_PROTOCOL = "Distribution Protocol";
public static final String SPECIMEN_COLLECTION_GROUP ="SpecimenCollectionGroup";
public static final String DISTRIBUTION = "Distribution";
public static final String DISTRIBUTION_PROTOCOL = "DistributionProtocol";
public static final String CP = "CP";
public static final String SCG = "SCG";
public static final String D = "D";
public static final String DP = "DP";
public static final String C = "C";
public static final String S = "S";
public static final String P = "P";
public static final String ADVANCED_CONDITIONS_QUERY_VIEW = "advancedCondtionsQueryView";
public static final String ADVANCED_SEARCH_ACTION = "AdvanceSearch.do";
public static final String ADVANCED_SEARCH_RESULTS_ACTION = "AdvanceSearchResults.do";
public static final String CONFIGURE_ADVANCED_SEARCH_RESULTS_ACTION = "ConfigureAdvanceSearchResults.do";
public static final String ADVANCED_QUERY_ADD = "Add";
public static final String ADVANCED_QUERY_EDIT = "Edit";
public static final String ADVANCED_QUERY_DELETE = "Delete";
public static final String ADVANCED_QUERY_OPERATOR = "Operator";
public static final String ADVANCED_QUERY_OR = "OR";
public static final String ADVANCED_QUERY_AND = "pAND";
public static final String EVENT_CONDITIONS = "eventConditions";
public static final String IDENTIFIER_COLUMN_ID_MAP = "identifierColumnIdsMap";
public static final String PAGEOF_PARTICIPANT_QUERY_EDIT= "pageOfParticipantQueryEdit";
public static final String PAGEOF_COLLECTION_PROTOCOL_QUERY_EDIT= "pageOfCollectionProtocolQueryEdit";
public static final String PAGEOF_SPECIMEN_COLLECTION_GROUP_QUERY_EDIT= "pageOfSpecimenCollectionGroupQueryEdit";
public static final String PAGEOF_SPECIMEN_QUERY_EDIT= "pageOfSpecimenQueryEdit";
public static final String PARTICIPANT_COLUMNS = "particpantColumns";
public static final String COLLECTION_PROTOCOL_COLUMNS = "collectionProtocolColumns";
public static final String SPECIMEN_COLLECTION_GROUP_COLUMNS = "SpecimenCollectionGroupColumns";
public static final String SPECIMEN_COLUMNS = "SpecimenColumns";
public static final String USER_ID_COLUMN = "USER_ID";
public static final String GENERIC_SECURITYMANAGER_ERROR = "The Security Violation error occured during a database operation. Please report this problem to the adminstrator";
public static final String BOOLEAN_YES = "Yes";
public static final String BOOLEAN_NO = "No";
public static final String PACKAGE_DOMAIN = "edu.wustl.catissuecore.domain";
//Constants for isAuditable and isSecureUpdate required for Dao methods in Bozlogic
public static final boolean IS_AUDITABLE_TRUE = true;
public static final boolean IS_SECURE_UPDATE_TRUE = true;
public static final boolean HAS_OBJECT_LEVEL_PRIVILEGE_FALSE = false;
//Constants for HTTP-API
public static final String CONTENT_TYPE = "CONTENT-TYPE";
// For StorageContainer isFull status
public static final String IS_CONTAINER_FULL_LIST = "isContainerFullList";
public static final String [] IS_CONTAINER_FULL_VALUES = {
SELECT_OPTION,
"True",
"False"
};
public static final String STORAGE_CONTAINER_DIM_ONE_LABEL = "oneDimLabel";
public static final String STORAGE_CONTAINER_DIM_TWO_LABEL = "twoDimLabel";
// public static final String SPECIMEN_TYPE_TISSUE = "Tissue";
// public static final String SPECIMEN_TYPE_FLUID = "Fluid";
// public static final String SPECIMEN_TYPE_CELL = "Cell";
// public static final String SPECIMEN_TYPE_MOL = "Molecular";
public static final String SPECIMEN_TYPE_COUNT = "Count";
public static final String SPECIMEN_TYPE_QUANTITY = "Quantity";
public static final String SPECIMEN_TYPE_DETAILS = "Details";
public static final String SPECIMEN_COUNT = "totalSpecimenCount";
public static final String TOTAL = "Total";
public static final String SPECIMENS = "Specimens";
//User Roles
public static final String TECHNICIAN = "Technician";
public static final String SUPERVISOR = "Supervisor";
public static final String SCIENTIST = "Scientist";
public static final String CHILD_CONTAINER_TYPE = "childContainerType";
public static final String UNUSED = "Unused";
public static final String TYPE = "Type";
//Mandar: 28-Apr-06 Bug 1129
public static final String DUPLICATE_SPECIMEN="duplicateSpecimen";
//Constants required in ParticipantLookupAction
public static final String PARTICIPANT_LOOKUP_PARAMETER="ParticipantLookupParameter";
public static final String PARTICIPANT_LOOKUP_CUTOFF="lookup.cutoff";
public static final String PARTICIPANT_LOOKUP_ALGO="ParticipantLookupAlgo";
public static final String PARTICIPANT_LOOKUP_SUCCESS="success";
public static final String PARTICIPANT_ADD_FORWARD="participantAdd";
public static final String PARTICIPANT_SYSTEM_IDENTIFIER="IDENTIFIER";
public static final String PARTICIPANT_LAST_NAME="LAST_NAME";
public static final String PARTICIPANT_FIRST_NAME="FIRST_NAME";
public static final String PARTICIPANT_MIDDLE_NAME="MIDDLE_NAME";
public static final String PARTICIPANT_BIRTH_DATE="BIRTH_DATE";
public static final String PARTICIPANT_DEATH_DATE="DEATH_DATE";
public static final String PARTICIPANT_VITAL_STATUS="VITAL_STATUS";
public static final String PARTICIPANT_GENDER="GENDER";
public static final String PARTICIPANT_SEX_GENOTYPE="SEX_GENOTYPE";
public static final String PARTICIPANT_RACE="RACE";
public static final String PARTICIPANT_ETHINICITY="ETHINICITY";
public static final String PARTICIPANT_SOCIAL_SECURITY_NUMBER="SOCIAL_SECURITY_NUMBER";
public static final String PARTICIPANT_PROBABLITY_MATCH="Probability";
public static final String PARTICIPANT_SSN_EXACT="SSNExact";
public static final String PARTICIPANT_SSN_PARTIAL="SSNPartial";
public static final String PARTICIPANT_DOB_EXACT="DOBExact";
public static final String PARTICIPANT_DOB_PARTIAL="DOBPartial";
public static final String PARTICIPANT_LAST_NAME_EXACT="LastNameExact";
public static final String PARTICIPANT_LAST_NAME_PARTIAL="LastNamePartial";
public static final String PARTICIPANT_FIRST_NAME_EXACT="NameExact";
public static final String PARTICIPANT_FIRST_NAME_PARTIAL="NamePartial";
public static final String PARTICIPANT_MIDDLE_NAME_EXACT="MiddleNameExact";
public static final String PARTICIPANT_MIDDLE_NAME_PARTIAL="MiddleNamePartial";
public static final String PARTICIPANT_GENDER_EXACT="GenderExact";
public static final String PARTICIPANT_RACE_EXACT="RaceExact";
public static final String PARTICIPANT_RACE_PARTIAL="RacePartial";
public static final String PARTICIPANT_BONUS="Bonus";
public static final String PARTICIPANT_TOTAL_POINTS="TotalPoints";
public static final String PARTICIPANT_MATCH_CHARACTERS_FOR_LAST_NAME="MatchCharactersForLastName";
//Constants for integration of caTies and CAE with caTissue Core
public static final String LINKED_DATA = "linkedData";
public static final String APPLICATION_ID = "applicationId";
public static final String CATIES = "caTies";
public static final String CAE = "cae";
public static final String EDIT_TAB_LINK = "editTabLink";
public static final String CATIES_PUBLIC_SERVER_NAME = "CaTiesPublicServerName";
public static final String CATIES_PRIVATE_SERVER_NAME = "CaTiesPrivateServerName";
//Constants for StorageContainerMap Applet
public static final String CONTAINER_STYLEID = "containerStyleId";
public static final String CONTAINER_STYLE = "containerStyle";
public static final String XDIM_STYLEID = "xDimStyleId";
public static final String YDIM_STYLEID = "yDimStyleId";
public static final String SELECTED_CONTAINER_NAME="selectedContainerName";
public static final String CONTAINERID="containerId";
public static final String POS1="pos1";
public static final String POS2="pos2";
//Constants for QuickEvents
public static final String EVENT_SELECTED = "eventSelected";
//Constant for SpecimenEvents page.
public static final String EVENTS_TITLE_MESSAGE = "Existing events for this specimen";
public static final String SURGICAL_PATHOLOGY_REPORT = "Surgical Pathology Report";
public static final String CLINICAL_ANNOTATIONS = "Clinical Annotations";
//Constants for Specimen Collection Group name- new field
public static final String RESET_NAME ="resetName";
// Labels for Storage Containers
public static final String[] STORAGE_CONTAINER_LABEL = {" Name"," Pos1"," Pos2"};
//Constans for Any field
public static final String HOLDS_ANY = "--All
//Constants : Specimen -> lineage
public static final String NEW_SPECIMEN = "New";
public static final String DERIVED_SPECIMEN = "Derived";
public static final String ALIQUOT = "Aliquot";
//Constant for length of messageBody in Reported problem page
public static final int messageLength= 500;
public static final String NEXT_NUMBER="nextNumber";
// public static final String getCollectionProtocolPIGroupName(Long identifier)
// if(identifier == null)
// return "PI_COLLECTION_PROTOCOL_";
// return "PI_COLLECTION_PROTOCOL_"+identifier;
// public static final String getCollectionProtocolCoordinatorGroupName(Long identifier)
// if(identifier == null)
// return "COORDINATORS_COLLECTION_PROTOCOL_";
// return "COORDINATORS_COLLECTION_PROTOCOL_"+identifier;
// public static final String getDistributionProtocolPIGroupName(Long identifier)
// if(identifier == null)
// return "PI_DISTRIBUTION_PROTOCOL_";
// return "PI_DISTRIBUTION_PROTOCOL_"+identifier;
// public static final String getCollectionProtocolPGName(Long identifier)
// if(identifier == null)
// return "COLLECTION_PROTOCOL_";
// return "COLLECTION_PROTOCOL_"+identifier;
// public static final String getDistributionProtocolPGName(Long identifier)
// if(identifier == null)
// return "DISTRIBUTION_PROTOCOL_";
// return "DISTRIBUTION_PROTOCOL_"+identifier;
public static final String ALL = "All";
//constant for pagination data list
public static final String PAGINATION_DATA_LIST = "paginationDataList";
public static final int SPECIMEN_DISTRIBUTION_TYPE = 1;
public static final int SPECIMEN_ARRAY_DISTRIBUTION_TYPE = 2;
public static final int BARCODE_BASED_DISTRIBUTION = 1;
public static final int LABEL_BASED_DISTRIBUTION = 2;
public static final String DISTRIBUTION_TYPE_LIST = "DISTRIBUTION_TYPE_LIST";
public static final String DISTRIBUTION_BASED_ON = "DISTRIBUTION_BASED_ON";
public static final String SYSTEM_LABEL = "label";
public static final String SYSTEM_BARCODE = "barcode";
public static final String SYSTEM_NAME = "name";
//Mandar : 05Sep06 Array for multiple specimen field names
public static final String DERIVED_OPERATION = "derivedOperation";
public static final String [] MULTIPLE_SPECIMEN_FIELD_NAMES = {
"Collection Group",
"Parent ID",
"Name",
"Barcode",
"Class",
"Type",
"Tissue Site",
"Tissue Side",
"Pathological Status",
"Concentration",
"Quantity",
"Storage Location",
"Comments",
"Events",
"External Identifier",
"Biohazards"
// "Derived",
// "Aliquots"
};
public static final String PAGEOF_MULTIPLE_SPECIMEN = "pageOfMultipleSpecimen";
public static final String PAGEOF_MULTIPLE_SPECIMEN_MAIN = "pageOfMultipleSpecimenMain";
public static final String MULTIPLE_SPECIMEN_ACTION = "MultipleSpecimen.do";
public static final String INIT_MULTIPLE_SPECIMEN_ACTION = "InitMultipleSpecimen.do";
public static final String MULTIPLE_SPECIMEN_APPLET_ACTION = "MultipleSpecimenAppletAction.do";
public static final String NEW_MULTIPLE_SPECIMEN_ACTION = "NewMultipleSpecimenAction.do";
public static final String MULTIPLE_SPECIMEN_RESULT = "multipleSpecimenResult";
public static final String SAVED_SPECIMEN_COLLECTION = "savedSpecimenCollection";
public static final String [] MULTIPLE_SPECIMEN_FORM_FIELD_NAMES = {
"CollectionGroup",
"ParentID",
"Name",
"Barcode",
"Class",
"Type",
"TissueSite",
"TissueSide",
"PathologicalStatus",
"Concentration",
"Quantity",
"StorageLocation",
"Comments",
"Events",
"ExternalIdentifier",
"Biohazards"
// "Derived",
// "Aliquots"
};
public static final String MULTIPLE_SPECIMEN_MAP_KEY = "MULTIPLE_SPECIMEN_MAP_KEY";
public static final String MULTIPLE_SPECIMEN_EVENT_MAP_KEY = "MULTIPLE_SPECIMEN_EVENT_MAP_KEY";
public static final String MULTIPLE_SPECIMEN_FORM_BEAN_MAP_KEY = "MULTIPLE_SPECIMEN_FORM_BEAN_MAP_KEY";
public static final String MULTIPLE_SPECIMEN_BUTTONS_MAP_KEY = "MULTIPLE_SPECIMEN_BUTTONS_MAP_KEY";
public static final String DERIVED_FORM = "DerivedForm";
public static final String SPECIMEN_ATTRIBUTE_KEY = "specimenAttributeKey";
public static final String SPECIMEN_CLASS = "specimenClass";
public static final String SPECIMEN_CALL_BACK_FUNCTION = "specimenCallBackFunction";
public static final String APPEND_COUNT = "_count";
public static final String EXTERNALIDENTIFIER_TYPE = "ExternalIdentifier";
public static final String BIOHAZARD_TYPE = "BioHazard";
public static final String COMMENTS_TYPE = "comments";
public static final String EVENTS_TYPE = "Events";
public static final String MULTIPLE_SPECIMEN_APPLET_NAME = "MultipleSpecimenApplet";
public static final String INPUT_APPLET_DATA = "inputAppletData";
// Start Specimen Array Applet related constants
public static final String SPECIMEN_ARRAY_APPLET = "edu/wustl/catissuecore/applet/ui/SpecimenArrayApplet.class";
public static final String SPECIMEN_ARRAY_APPLET_NAME = "specimenArrayApplet";
public static final String SPECIMEN_ARRAY_CONTENT_KEY = "SpecimenArrayContentKey";
public static final String SPECIMEN_LABEL_COLUMN_NAME = "label";
public static final String SPECIMEN_BARCODE_COLUMN_NAME = "barcode";
public static final String ARRAY_SPECIMEN_DOES_NOT_EXIST_EXCEPTION_MESSAGE = "Please enter valid specimen for specimen array!!specimen does not exist ";
public static final String ARRAY_SPECIMEN_NOT_ACTIVE_EXCEPTION_MESSAGE = "Please enter valid specimen for specimen array!! Specimen is closed/disabled ";
public static final String ARRAY_NO_SPECIMEN__EXCEPTION_MESSAGE = "Specimen Array should contain at least one specimen";
public static final String ARRAY_SPEC_NOT_COMPATIBLE_EXCEPTION_MESSAGE = "Please add compatible specimens to specimen array (belong to same specimen class & specimen types of Array)";
public static final String ARRAY_MOLECULAR_QUAN_EXCEPTION_MESSAGE = "Please enter quantity for Molecular Specimen
/**
* Specify the SPECIMEN_ARRAY_LIST as key for specimen array type list
*/
public static final String SPECIMEN_ARRAY_TYPE_LIST = "specimenArrayList";
public static final String SPECIMEN_ARRAY_CLASSNAME = "edu.wustl.catissuecore.domain.SpecimenArray";
public static final String SPECIMEN_ARRAY_TYPE_CLASSNAME = "edu.wustl.catissuecore.domain.SpecimenArrayType";
// End
// Common Applet Constants
public static final String APPLET_SERVER_HTTP_START_STR = "http:
public static final String APPLET_SERVER_URL_PARAM_NAME = "serverURL";
public static final String IS_NOT_NULL = "is not null";
public static final String IS_NULL = "is null";
// Used in array action
public static final String ARRAY_TYPE_ANY_VALUE = "2";
public static final String ARRAY_TYPE_ANY_NAME = "Any";
// end
// Array Type All Id in table
public static final short ARRAY_TYPE_ALL_ID = 2;
// constants required for caching mechanism of ParticipantBizLogic
public static final String MAP_OF_PARTICIPANTS = "listOfParticipants";
public static final String LIST_OF_REGISTRATION_INFO = "listOfParticipantRegistrations";
public static final String EHCACHE_FOR_CATISSUE_CORE = "cacheForCaTissueCore";
public static final String MAP_OF_DISABLED_CONTAINERS = "listOfDisabledContainers";
public static final String MAP_OF_CONTAINER_FOR_DISABLED_SPECIEN = "listOfContainerForDisabledContainerSpecimen";
public static final String ADD = "add";
public static final String EDIT = "edit";
public static final String ID = "id";
public static final String MANAGE_BIO_SPECIMEN_ACTION = "/ManageBioSpecimen.do";
public static final String CREATE_PARTICIPANT_REGISTRATION = "createParticipantRegistration";
public static final String CREATE_PARTICIPANT_REGISTRATION_ADD = "createParticipantRegistrationAdd";
public static final String CREATE_PARTICIPANT_REGISTRATION_EDIT= "createParticipantRegistrationEdit";
public static final String CAN_HOLD_CONTAINER_TYPE = "holdContainerType";
public static final String CAN_HOLD_SPECIMEN_CLASS = "holdSpecimenClass";
public static final String CAN_HOLD_COLLECTION_PROTOCOL = "holdCollectionProtocol";
public static final String CAN_HOLD_SPECIMEN_ARRAY_TYPE = "holdSpecimenArrayType";
public static final String COLLECTION_PROTOCOL_ID = "collectionProtocolId";
public static final String SPECIMEN_CLASS_NAME = "specimeClassName";
public static final String ENABLE_STORAGE_CONTAINER_GRID_PAGE = "enablePage";
public static final int ALL_STORAGE_TYPE_ID = 1; //Constant for the "All" storage type, which can hold all container type
public static final int ALL_SPECIMEN_ARRAY_TYPE_ID = 2;//Constant for the "All" storage type, which can hold all specimen array type
public static final String SPECIMEN_LABEL_CONTAINER_MAP = "Specimen : ";
public static final String CONTAINER_LABEL_CONTAINER_MAP = "Container : ";
public static final String SPECIMEN_ARRAY_LABEL_CONTAINER_MAP = "Array : ";
public static final String SPECIMEN_PROTOCOL ="SpecimenProtocol";
public static final String SPECIMEN_PROTOCOL_SHORT_TITLE ="SHORT_TITLE";
public static final String SPECIMEN_COLLECTION_GROUP_NAME ="NAME";
public static final String SPECIMEN_LABEL = "LABEL";
//Constants required for max limit on no. of containers in the drop down
public static final String CONTAINERS_MAX_LIMIT = "containers_max_limit";
public static final String EXCEEDS_MAX_LIMIT = "exceedsMaxLimit";
//MultipleSpecimen Constants
public static final String MULTIPLE_SPECIMEN_COLUMNS_PER_PAGE="multipleSpecimen.ColumnsPerPage";
public static final String MULTIPLE_SPECIMEN_STORAGE_LOCATION_ACTION="MultipleSpecimenStorageLocationAdd.do";
public static final String MULTIPLE_SPECIMEN_STORAGE_LOCATION_AVAILABLE_MAP="locationMap";
public static final String MULTIPLE_SPECIMEN_STORAGE_LOCATION_SPECIMEN_MAP= "specimenMap";
public static final String MULTIPLE_SPECIMEN_STORAGE_LOCATION_KEY_SEPARATOR = "$";
public static final String PAGEOF_MULTIPLE_SPECIMEN_STORAGE_LOCATION = "formSubmitted";
public static final String MULTIPLE_SPECIMEN_SUBMIT_SUCCESSFUL = "submitSuccessful";
public static final String MULTIPLE_SPECIMEN_SPECIMEN_ORDER_LIST= "specimenOrderList";
public static final String MULTIPLE_SPECIMEN_DELETELAST_SPECIMEN_ID = "SpecimenId";
public static final String MULTIPLE_SPECIMEN_PARENT_COLLECTION_GROUP = "ParentSpecimenCollectionGroup";
public static final String NO_OF_RECORDS_PER_PAGE="resultView.noOfRecordsPerPage";
public static final int[] RESULT_PERPAGE_OPTIONS = {10,50,100,1000,5000};
/**
* Specify the SPECIMEN_MAP_KEY field ) used in multiple specimen applet action.
*/
public static final String SPECIMEN_MAP_KEY = "Specimen_derived_map_key";
/**
* Specify the SPECIMEN_MAP_KEY field ) used in multiple specimen applet action.
*/
public static final String CONTAINER_MAP_KEY = "container_map_key";
/**
* Used to saperate storage container, xPos, yPos
*/
public static final String STORAGE_LOCATION_SAPERATOR = "@";
public static final String METHOD_NAME="method";
public static final String GRID_FOR_EVENTS="eventParameter";
public static final String GRID_FOR_EDIT_SEARCH="editSearch";
public static final String GRID_FOR_DERIVED_SPECIMEN="derivedSpecimen";
//CpBasedSearch Constants
public static final String CP_QUERY = "CPQuery";
public static final String CP_QUERY_PARTICIPANT_EDIT_ACTION = "CPQueryParticipantEdit.do";
public static final String CP_QUERY_PARTICIPANT_ADD_ACTION = "CPQueryParticipantAdd.do";
public static final String CP_QUERY_SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "CPQuerySpecimenCollectionGroupAdd.do";
public static final String CP_QUERY_SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "CPQuerySpecimenCollectionGroupEdit.do";
public static final String CP_AND_PARTICIPANT_VIEW="cpAndParticipantView";
public static final String DATA_DETAILS_VIEW="dataDetailsView";
public static final String SHOW_CP_AND_PARTICIPANTS_ACTION="showCpAndParticipants.do";
public static final String PAGE_OF_CP_QUERY_RESULTS = "pageOfCpQueryResults";
public static final String CP_LIST = "cpList";
public static final String REGISTERED_PARTICIPANT_LIST = "participantList";
public static final String PAGE_OF_PARTICIPANT_CP_QUERY = "pageOfParticipantCPQuery";
public static final String PAGE_OF_SCG_CP_QUERY = "pageOfSpecimenCollectionGroupCPQuery";
public static final String CP_SEARCH_PARTICIPANT_ID="cpSearchParticipantId";
public static final String CP_SEARCH_CP_ID="cpSearchCpId";
public static final String CP_TREE_VIEW = "cpTreeView";
public static final String CP_TREE_VIEW_ACTION = "showTree.do";
public static final String PAGE_OF_SPECIMEN_CP_QUERY = "pageOfNewSpecimenCPQuery";
public static final String CP_QUERY_SPECIMEN_ADD_ACTION = "CPQueryNewSpecimenAdd.do";
public static final String CP_QUERY_CREATE_SPECIMEN_ACTION = "CPQueryCreateSpecimen.do";
public static final String CP_QUERY_SPECIMEN_EDIT_ACTION = "CPQueryNewSpecimenEdit.do";
public static final String PAGE_OF_CREATE_SPECIMEN_CP_QUERY = "pageOfCreateSpecimenCPQuery";
public static final String PAGE_OF_ALIQUOT_CP_QUERY = "pageOfAliquotCPQuery";
public static final String PAGE_OF_CREATE_ALIQUOT_CP_QUERY = "pageOfCreateAliquotCPQuery";
public static final String PAGE_OF_ALIQUOT_SUMMARY_CP_QUERY = "pageOfAliquotSummaryCPQuery";
public static final String CP_QUERY_CREATE_ALIQUOT_ACTION = "CPQueryCreateAliquots.do";
public static final String CP_QUERY_ALIQUOT_SUMMARY_ACTION = "CPQueryAliquotSummary.do";
public static final String CP_QUERY_CREATE_SPECIMEN_ADD_ACTION = "CPQueryAddSpecimen.do";
public static final String PAGE_OF_DISTRIBUTION_CP_QUERY = "pageOfDistributionCPQuery";
public static final String CP_QUERY_DISTRIBUTION_EDIT_ACTION = "CPQueryDistributionEdit.do";
public static final String CP_QUERY_DISTRIBUTION_ADD_ACTION = "CPQueryDistributionAdd.do";
public static final String CP_QUERY_DISTRIBUTION_REPORT_SAVE_ACTION="CPQueryDistributionReportSave.do";
public static final String CP_QUERY_ARRAY_DISTRIBUTION_REPORT_SAVE_ACTION="CPQueryArrayDistributionReportSave.do";
public static final String CP_QUERY_CONFIGURE_DISTRIBUTION_ACTION = "CPQueryConfigureDistribution.do";
public static final String CP_QUERY_DISTRIBUTION_REPORT_ACTION = "CPQueryDistributionReport.do";
public static final String PAGE_OF_LIST_SPECIMEN_EVENT_PARAMETERS_CP_QUERY = "pageOfListSpecimenEventParametersCPQuery";
public static final String PAGE_OF_COLLECTION_PROTOCOL_REGISTRATION_CP_QUERY = "pageOfCollectionProtocolRegistrationCPQuery";
public static final String PAGE_OF_MULTIPLE_SPECIMEN_CP_QUERY = "pageOfMultipleSpecimenCPQuery";
public static final String CP_QUERY_NEW_MULTIPLE_SPECIMEN_ACTION = "CPQueryNewMultipleSpecimenAction.do";
public static final String CP_QUERY_MULTIPLE_SPECIMEN_STORAGE_LOCATION_ACTION="CPQueryMultipleSpecimenStorageLocationAdd.do";
public static final String CP_QUERY_PAGEOF_MULTIPLE_SPECIMEN_STORAGE_LOCATION = "CPQueryformSubmitted";
public static final String CP_QUERY_COLLECTION_PROTOCOL_REGISTRATION_ADD_ACTION = "CPQueryCollectionProtocolRegistrationAdd.do";
public static final String CP_QUERY_COLLECTION_PROTOCOL_REGISTRATION_EDIT_ACTION = "CPQueryCollectionProtocolRegistrationEdit.do";
public static final String CP_QUERY_PARTICIPANT_LOOKUP_ACTION= "CPQueryParticipantLookup.do";
public static final String CP_QUERY_BIO_SPECIMEN = "/QueryManageBioSpecimen.do";
//Mandar : 15-Jan-07
public static final String WITHDRAW_RESPONSE_NOACTION= "No Action";
public static final String WITHDRAW_RESPONSE_DISCARD= "Discard";
public static final String WITHDRAW_RESPONSE_RETURN= "Return";
public static final String WITHDRAW_RESPONSE_RESET= "Reset";
public static final String WITHDRAW_RESPONSE_REASON= "Specimen consents withdrawn";
public static final String SEARCH_CATEGORY_LIST_SELECT_TAG_NAME="selectCategoryList";
public static final String SEARCH_CATEGORY_LIST_FUNCTION_NAME="getSelectedEntities";
} |
package edu.wustl.catissuecore.util.global;
/**
* This class stores the constants used in the operations in the application.
* @author gautam_shetty
*/
public class Constants extends edu.wustl.common.util.global.Constants
{
public static final String MAX_IDENTIFIER = "maxIdentifier";
public static final String AND_JOIN_CONDITION = "AND";
public static final String OR_JOIN_CONDITION = "OR";
//Sri: Changed the format for displaying in Specimen Event list (#463)
public static final String TIMESTAMP_PATTERN = "MM-dd-yyyy HH:mm";
public static final String DATE_PATTERN_YYYY_MM_DD = "yyyy-MM-dd";
// Mandar: Used for Date Validations in Validator Class
public static final String DATE_SEPARATOR = "-";
public static final String DATE_SEPARATOR_DOT = ".";
public static final String MIN_YEAR = "1900";
public static final String MAX_YEAR = "9999";
public static final String VIEW = "view";
public static final String DELETE = "delete";
public static final String EXPORT = "export";
public static final String SHOPPING_CART_ADD = "shoppingCartAdd";
public static final String SHOPPING_CART_DELETE = "shoppingCartDelete";
public static final String SHOPPING_CART_EXPORT = "shoppingCartExport";
public static final String NEWUSERFORM = "newUserForm";
public static final String REDIRECT_TO_SPECIMEN = "specimenRedirect";
public static final String CALLED_FROM = "calledFrom";
public static final String ACCESS = "access";
//Constants required for Forgot Password
public static final String FORGOT_PASSWORD = "forgotpassword";
public static final String LOGINNAME = "loginName";
public static final String LASTNAME = "lastName";
public static final String FIRSTNAME = "firstName";
public static final String INSTITUTION = "institution";
public static final String EMAIL = "email";
public static final String DEPARTMENT = "department";
public static final String ADDRESS = "address";
public static final String CITY = "city";
public static final String STATE = "state";
public static final String COUNTRY = "country";
public static final String NEXT_CONTAINER_NO = "startNumber";
public static final String CSM_USER_ID = "csmUserId";
public static final String INSTITUTIONLIST = "institutionList";
public static final String DEPARTMENTLIST = "departmentList";
public static final String STATELIST = "stateList";
public static final String COUNTRYLIST = "countryList";
public static final String ROLELIST = "roleList";
public static final String ROLEIDLIST = "roleIdList";
public static final String CANCER_RESEARCH_GROUP_LIST = "cancerResearchGroupList";
public static final String GENDER_LIST = "genderList";
public static final String GENOTYPE_LIST = "genotypeList";
public static final String ETHNICITY_LIST = "ethnicityList";
public static final String PARTICIPANT_MEDICAL_RECORD_SOURCE_LIST = "participantMedicalRecordSourceList";
public static final String RACELIST = "raceList";
public static final String VITAL_STATUS_LIST = "vitalStatusList";
public static final String PARTICIPANT_LIST = "participantList";
public static final String PARTICIPANT_ID_LIST = "participantIdList";
public static final String PROTOCOL_LIST = "protocolList";
public static final String TIMEHOURLIST = "timeHourList";
public static final String TIMEMINUTESLIST = "timeMinutesList";
public static final String TIMEAMPMLIST = "timeAMPMList";
public static final String RECEIVEDBYLIST = "receivedByList";
public static final String COLLECTEDBYLIST = "collectedByList";
public static final String COLLECTIONSITELIST = "collectionSiteList";
public static final String RECEIVEDSITELIST = "receivedSiteList";
public static final String RECEIVEDMODELIST = "receivedModeList";
public static final String ACTIVITYSTATUSLIST = "activityStatusList";
public static final String USERLIST = "userList";
public static final String SITETYPELIST = "siteTypeList";
public static final String STORAGETYPELIST="storageTypeList";
public static final String STORAGECONTAINERLIST="storageContainerList";
public static final String SITELIST="siteList";
// public static final String SITEIDLIST="siteIdList";
public static final String USERIDLIST = "userIdList";
public static final String STORAGETYPEIDLIST="storageTypeIdList";
public static final String SPECIMENCOLLECTIONLIST="specimentCollectionList";
public static final String PARTICIPANT_IDENTIFIER_IN_CPR = "participant";
public static final String APPROVE_USER_STATUS_LIST = "statusList";
public static final String EVENT_PARAMETERS_LIST = "eventParametersList";
//New Specimen lists.
public static final String SPECIMEN_COLLECTION_GROUP_LIST = "specimenCollectionGroupIdList";
public static final String SPECIMEN_TYPE_LIST = "specimenTypeList";
public static final String SPECIMEN_SUB_TYPE_LIST = "specimenSubTypeList";
public static final String TISSUE_SITE_LIST = "tissueSiteList";
public static final String TISSUE_SIDE_LIST = "tissueSideList";
public static final String PATHOLOGICAL_STATUS_LIST = "pathologicalStatusList";
public static final String BIOHAZARD_TYPE_LIST = "biohazardTypeList";
public static final String BIOHAZARD_NAME_LIST = "biohazardNameList";
public static final String BIOHAZARD_ID_LIST = "biohazardIdList";
public static final String BIOHAZARD_TYPES_LIST = "biohazardTypesList";
public static final String PARENT_SPECIMEN_ID_LIST = "parentSpecimenIdList";
public static final String RECEIVED_QUALITY_LIST = "receivedQualityList";
//SpecimenCollecionGroup lists.
public static final String PROTOCOL_TITLE_LIST = "protocolTitleList";
public static final String PARTICIPANT_NAME_LIST = "participantNameList";
public static final String PROTOCOL_PARTICIPANT_NUMBER_LIST = "protocolParticipantNumberList";
//public static final String PROTOCOL_PARTICIPANT_NUMBER_ID_LIST = "protocolParticipantNumberIdList";
public static final String STUDY_CALENDAR_EVENT_POINT_LIST = "studyCalendarEventPointList";
//public static final String STUDY_CALENDAR_EVENT_POINT_ID_LIST="studyCalendarEventPointIdList";
public static final String PARTICIPANT_MEDICAL_IDNETIFIER_LIST = "participantMedicalIdentifierArray";
//public static final String PARTICIPANT_MEDICAL_IDNETIFIER_ID_LIST = "participantMedicalIdentifierIdArray";
public static final String SPECIMEN_COLLECTION_GROUP_ID = "specimenCollectionGroupId";
public static final String REQ_PATH = "redirectTo";
public static final String CLINICAL_STATUS_LIST = "cinicalStatusList";
public static final String SPECIMEN_CLASS_LIST = "specimenClassList";
public static final String SPECIMEN_CLASS_ID_LIST = "specimenClassIdList";
public static final String SPECIMEN_TYPE_MAP = "specimenTypeMap";
//Simple Query Interface Lists
public static final String OBJECT_COMPLETE_NAME_LIST = "objectCompleteNameList";
public static final String SIMPLE_QUERY_INTERFACE_TITLE = "simpleQueryInterfaceTitle";
public static final String MAP_OF_STORAGE_CONTAINERS = "storageContainerMap";
public static final String STORAGE_CONTAINER_GRID_OBJECT = "storageContainerGridObject";
public static final String STORAGE_CONTAINER_CHILDREN_STATUS = "storageContainerChildrenStatus";
public static final String START_NUMBER = "startNumber";
public static final String CHILD_CONTAINER_SYSTEM_IDENTIFIERS = "childContainerIds";
public static final int STORAGE_CONTAINER_FIRST_ROW = 1;
public static final int STORAGE_CONTAINER_FIRST_COLUMN = 1;
public static final String MAP_COLLECTION_PROTOCOL_LIST = "collectionProtocolList";
public static final String MAP_SPECIMEN_CLASS_LIST = "specimenClassList";
//event parameters lists
public static final String METHOD_LIST = "methodList";
public static final String HOUR_LIST = "hourList";
public static final String MINUTES_LIST = "minutesList";
public static final String EMBEDDING_MEDIUM_LIST = "embeddingMediumList";
public static final String PROCEDURE_LIST = "procedureList";
public static final String PROCEDUREIDLIST = "procedureIdList";
public static final String CONTAINER_LIST = "containerList";
public static final String CONTAINERIDLIST = "containerIdList";
public static final String FROMCONTAINERLIST="fromContainerList";
public static final String TOCONTAINERLIST="toContainerList";
public static final String FIXATION_LIST = "fixationList";
public static final String FROM_SITE_LIST="fromsiteList";
public static final String TO_SITE_LIST="tositeList";
public static final String ITEMLIST="itemList";
public static final String DISTRIBUTIONPROTOCOLLIST="distributionProtocolList";
public static final String TISSUE_SPECIMEN_ID_LIST="tissueSpecimenIdList";
public static final String MOLECULAR_SPECIMEN_ID_LIST="molecularSpecimenIdList";
public static final String CELL_SPECIMEN_ID_LIST="cellSpecimenIdList";
public static final String FLUID_SPECIMEN_ID_LIST="fluidSpecimenIdList";
public static final String STORAGE_STATUS_LIST="storageStatusList";
public static final String CLINICAL_DIAGNOSIS_LIST = "clinicalDiagnosisList";
public static final String HISTOLOGICAL_QUALITY_LIST="histologicalQualityList";
//For Specimen Event Parameters.
public static final String SPECIMEN_ID = "specimenId";
public static final String FROM_POSITION_DATA = "fromPositionData";
public static final String POS_ONE ="posOne";
public static final String POS_TWO ="posTwo";
public static final String STORAGE_CONTAINER_ID ="storContId";
public static final String IS_RNA = "isRNA";
public static final String RNA = "RNA";
// New Participant Event Parameters
public static final String PARTICIPANT_ID="participantId";
//Constants required in User.jsp Page
public static final String USER_SEARCH_ACTION = "UserSearch.do";
public static final String USER_ADD_ACTION = "UserAdd.do";
public static final String USER_EDIT_ACTION = "UserEdit.do";
public static final String APPROVE_USER_ADD_ACTION = "ApproveUserAdd.do";
public static final String APPROVE_USER_EDIT_ACTION = "ApproveUserEdit.do";
public static final String SIGNUP_USER_ADD_ACTION = "SignUpUserAdd.do";
public static final String USER_EDIT_PROFILE_ACTION = "UserEditProfile.do";
public static final String UPDATE_PASSWORD_ACTION = "UpdatePassword.do";
//Constants required in Accession.jsp Page
public static final String ACCESSION_SEARCH_ACTION = "AccessionSearch.do";
public static final String ACCESSION_ADD_ACTION = "AccessionAdd.do";
public static final String ACCESSION_EDIT_ACTION = "AccessionEdit.do";
//Constants required in StorageType.jsp Page
public static final String STORAGE_TYPE_SEARCH_ACTION = "StorageTypeSearch.do";
public static final String STORAGE_TYPE_ADD_ACTION = "StorageTypeAdd.do";
public static final String STORAGE_TYPE_EDIT_ACTION = "StorageTypeEdit.do";
//Constants required in StorageContainer.jsp Page
public static final String STORAGE_CONTAINER_SEARCH_ACTION = "StorageContainerSearch.do";
public static final String STORAGE_CONTAINER_ADD_ACTION = "StorageContainerAdd.do";
public static final String STORAGE_CONTAINER_EDIT_ACTION = "StorageContainerEdit.do";
public static final String HOLDS_LIST1 = "HoldsList1";
public static final String HOLDS_LIST2 = "HoldsList2";
public static final String HOLDS_LIST3 = "HoldsList3";
//Constants required in Site.jsp Page
public static final String SITE_SEARCH_ACTION = "SiteSearch.do";
public static final String SITE_ADD_ACTION = "SiteAdd.do";
public static final String SITE_EDIT_ACTION = "SiteEdit.do";
//Constants required in Site.jsp Page
public static final String BIOHAZARD_SEARCH_ACTION = "BiohazardSearch.do";
public static final String BIOHAZARD_ADD_ACTION = "BiohazardAdd.do";
public static final String BIOHAZARD_EDIT_ACTION = "BiohazardEdit.do";
//Constants required in Partcipant.jsp Page
public static final String PARTICIPANT_SEARCH_ACTION = "ParticipantSearch.do";
public static final String PARTICIPANT_ADD_ACTION = "ParticipantAdd.do";
public static final String PARTICIPANT_EDIT_ACTION = "ParticipantEdit.do";
public static final String PARTICIPANT_LOOKUP_ACTION= "ParticipantLookup.do";
//Constants required in Institution.jsp Page
public static final String INSTITUTION_SEARCH_ACTION = "InstitutionSearch.do";
public static final String INSTITUTION_ADD_ACTION = "InstitutionAdd.do";
public static final String INSTITUTION_EDIT_ACTION = "InstitutionEdit.do";
//Constants required in Department.jsp Page
public static final String DEPARTMENT_SEARCH_ACTION = "DepartmentSearch.do";
public static final String DEPARTMENT_ADD_ACTION = "DepartmentAdd.do";
public static final String DEPARTMENT_EDIT_ACTION = "DepartmentEdit.do";
//Constants required in CollectionProtocolRegistration.jsp Page
public static final String COLLECTION_PROTOCOL_REGISTRATION_SEARCH_ACTION = "CollectionProtocolRegistrationSearch.do";
public static final String COLLECTIONP_ROTOCOL_REGISTRATION_ADD_ACTION = "CollectionProtocolRegistrationAdd.do";
public static final String COLLECTION_PROTOCOL_REGISTRATION_EDIT_ACTION = "CollectionProtocolRegistrationEdit.do";
//Constants required in CancerResearchGroup.jsp Page
public static final String CANCER_RESEARCH_GROUP_SEARCH_ACTION = "CancerResearchGroupSearch.do";
public static final String CANCER_RESEARCH_GROUP_ADD_ACTION = "CancerResearchGroupAdd.do";
public static final String CANCER_RESEARCH_GROUP_EDIT_ACTION = "CancerResearchGroupEdit.do";
//Constants required for Approve user
public static final String USER_DETAILS_SHOW_ACTION = "UserDetailsShow.do";
public static final String APPROVE_USER_SHOW_ACTION = "ApproveUserShow.do";
//Reported Problem Constants
public static final String REPORTED_PROBLEM_ADD_ACTION = "ReportedProblemAdd.do";
public static final String REPORTED_PROBLEM_EDIT_ACTION = "ReportedProblemEdit.do";
public static final String PROBLEM_DETAILS_ACTION = "ProblemDetails.do";
public static final String REPORTED_PROBLEM_SHOW_ACTION = "ReportedProblemShow.do";
//Query Results view Actions
public static final String TREE_VIEW_ACTION = "TreeView.do";
public static final String DATA_VIEW_FRAME_ACTION = "SpreadsheetView.do";
public static final String SIMPLE_QUERY_INTERFACE_URL = "SimpleQueryInterface.do?pageOf=pageOfSimpleQueryInterface&menuSelected=17";
//New Specimen Data Actions.
public static final String SPECIMEN_ADD_ACTION = "NewSpecimenAdd.do";
public static final String SPECIMEN_EDIT_ACTION = "NewSpecimenEdit.do";
public static final String SPECIMEN_SEARCH_ACTION = "NewSpecimenSearch.do";
public static final String SPECIMEN_EVENT_PARAMETERS_ACTION = "ListSpecimenEventParameters.do";
//Create Specimen Data Actions.
public static final String CREATE_SPECIMEN_ADD_ACTION = "AddSpecimen.do";
public static final String CREATE_SPECIMEN_EDIT_ACTION = "CreateSpecimenEdit.do";
public static final String CREATE_SPECIMEN_SEARCH_ACTION = "CreateSpecimenSearch.do";
//ShoppingCart Actions.
public static final String SHOPPING_CART_OPERATION = "ShoppingCartOperation.do";
public static final String SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "SpecimenCollectionGroup.do";
public static final String SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "SpecimenCollectionGroupAdd.do";
public static final String SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "SpecimenCollectionGroupEdit.do";
//Constants required in FrozenEventParameters.jsp Page
public static final String FROZEN_EVENT_PARAMETERS_SEARCH_ACTION = "FrozenEventParametersSearch.do";
public static final String FROZEN_EVENT_PARAMETERS_ADD_ACTION = "FrozenEventParametersAdd.do";
public static final String FROZEN_EVENT_PARAMETERS_EDIT_ACTION = "FrozenEventParametersEdit.do";
//Constants required in CheckInCheckOutEventParameters.jsp Page
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_SEARCH_ACTION = "CheckInCheckOutEventParametersSearch.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_ADD_ACTION = "CheckInCheckOutEventParametersAdd.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_EDIT_ACTION = "CheckInCheckOutEventParametersEdit.do";
//Constants required in ReceivedEventParameters.jsp Page
public static final String RECEIVED_EVENT_PARAMETERS_SEARCH_ACTION = "receivedEventParametersSearch.do";
public static final String RECEIVED_EVENT_PARAMETERS_ADD_ACTION = "ReceivedEventParametersAdd.do";
public static final String RECEIVED_EVENT_PARAMETERS_EDIT_ACTION = "receivedEventParametersEdit.do";
//Constants required in FluidSpecimenReviewEventParameters.jsp Page
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "FluidSpecimenReviewEventParametersSearch.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "FluidSpecimenReviewEventParametersAdd.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "FluidSpecimenReviewEventParametersEdit.do";
//Constants required in CELLSPECIMENREVIEWParameters.jsp Page
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "CellSpecimenReviewParametersSearch.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "CellSpecimenReviewParametersAdd.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "CellSpecimenReviewParametersEdit.do";
//Constants required in tissue SPECIMEN REVIEW event Parameters.jsp Page
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "TissueSpecimenReviewEventParametersSearch.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "TissueSpecimenReviewEventParametersAdd.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "TissueSpecimenReviewEventParametersEdit.do";
// Constants required in DisposalEventParameters.jsp Page
public static final String DISPOSAL_EVENT_PARAMETERS_SEARCH_ACTION = "DisposalEventParametersSearch.do";
public static final String DISPOSAL_EVENT_PARAMETERS_ADD_ACTION = "DisposalEventParametersAdd.do";
public static final String DISPOSAL_EVENT_PARAMETERS_EDIT_ACTION = "DisposalEventParametersEdit.do";
// Constants required in ThawEventParameters.jsp Page
public static final String THAW_EVENT_PARAMETERS_SEARCH_ACTION = "ThawEventParametersSearch.do";
public static final String THAW_EVENT_PARAMETERS_ADD_ACTION = "ThawEventParametersAdd.do";
public static final String THAW_EVENT_PARAMETERS_EDIT_ACTION = "ThawEventParametersEdit.do";
// Constants required in MOLECULARSPECIMENREVIEWParameters.jsp Page
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "MolecularSpecimenReviewParametersSearch.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "MolecularSpecimenReviewParametersAdd.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "MolecularSpecimenReviewParametersEdit.do";
// Constants required in CollectionEventParameters.jsp Page
public static final String COLLECTION_EVENT_PARAMETERS_SEARCH_ACTION = "CollectionEventParametersSearch.do";
public static final String COLLECTION_EVENT_PARAMETERS_ADD_ACTION = "CollectionEventParametersAdd.do";
public static final String COLLECTION_EVENT_PARAMETERS_EDIT_ACTION = "CollectionEventParametersEdit.do";
// Constants required in SpunEventParameters.jsp Page
public static final String SPUN_EVENT_PARAMETERS_SEARCH_ACTION = "SpunEventParametersSearch.do";
public static final String SPUN_EVENT_PARAMETERS_ADD_ACTION = "SpunEventParametersAdd.do";
public static final String SPUN_EVENT_PARAMETERS_EDIT_ACTION = "SpunEventParametersEdit.do";
// Constants required in EmbeddedEventParameters.jsp Page
public static final String EMBEDDED_EVENT_PARAMETERS_SEARCH_ACTION = "EmbeddedEventParametersSearch.do";
public static final String EMBEDDED_EVENT_PARAMETERS_ADD_ACTION = "EmbeddedEventParametersAdd.do";
public static final String EMBEDDED_EVENT_PARAMETERS_EDIT_ACTION = "EmbeddedEventParametersEdit.do";
// Constants required in TransferEventParameters.jsp Page
public static final String TRANSFER_EVENT_PARAMETERS_SEARCH_ACTION = "TransferEventParametersSearch.do";
public static final String TRANSFER_EVENT_PARAMETERS_ADD_ACTION = "TransferEventParametersAdd.do";
public static final String TRANSFER_EVENT_PARAMETERS_EDIT_ACTION = "TransferEventParametersEdit.do";
// Constants required in FixedEventParameters.jsp Page
public static final String FIXED_EVENT_PARAMETERS_SEARCH_ACTION = "FixedEventParametersSearch.do";
public static final String FIXED_EVENT_PARAMETERS_ADD_ACTION = "FixedEventParametersAdd.do";
public static final String FIXED_EVENT_PARAMETERS_EDIT_ACTION = "FixedEventParametersEdit.do";
// Constants required in ProcedureEventParameters.jsp Page
public static final String PROCEDURE_EVENT_PARAMETERS_SEARCH_ACTION = "ProcedureEventParametersSearch.do";
public static final String PROCEDURE_EVENT_PARAMETERS_ADD_ACTION = "ProcedureEventParametersAdd.do";
public static final String PROCEDURE_EVENT_PARAMETERS_EDIT_ACTION = "ProcedureEventParametersEdit.do";
// Constants required in Distribution.jsp Page
public static final String DISTRIBUTION_SEARCH_ACTION = "DistributionSearch.do";
public static final String DISTRIBUTION_ADD_ACTION = "DistributionAdd.do";
public static final String DISTRIBUTION_EDIT_ACTION = "DistributionEdit.do";
public static final String SPECIMENARRAYTYPE_ADD_ACTION = "SpecimenArrayTypeAdd.do?operation=add";
public static final String SPECIMENARRAYTYPE_EDIT_ACTION = "SpecimenArrayTypeEdit.do?operation=edit";
public static final String ARRAY_DISTRIBUTION_ADD_ACTION = "ArrayDistributionAdd.do";
public static final String SPECIMENARRAY_ADD_ACTION = "SpecimenArrayAdd.do";
public static final String SPECIMENARRAY_EDIT_ACTION = "SpecimenArrayEdit.do";
//Spreadsheet Export Action
public static final String SPREADSHEET_EXPORT_ACTION = "SpreadsheetExport.do";
//Aliquots Action
public static final String ALIQUOT_ACTION = "Aliquots.do";
public static final String CREATE_ALIQUOT_ACTION = "CreateAliquots.do";
public static final String ALIQUOT_SUMMARY_ACTION = "AliquotSummary.do";
//Constants related to Aliquots functionality
public static final String PAGEOF_ALIQUOT = "pageOfAliquot";
public static final String PAGEOF_CREATE_ALIQUOT = "pageOfCreateAliquot";
public static final String PAGEOF_ALIQUOT_SUMMARY = "pageOfAliquotSummary";
public static final String AVAILABLE_CONTAINER_MAP = "availableContainerMap";
public static final String COMMON_ADD_EDIT = "commonAddEdit";
//Constants related to SpecimenArrayAliquots functionality
public static final String STORAGE_TYPE_ID="storageTypeId";
public static final String ALIQUOT_SPECIMEN_ARRAY_TYPE="SpecimenArrayType";
public static final String ALIQUOT_SPECIMEN_CLASS="SpecimenClass";
public static final String ALIQUOT_SPECIMEN_TYPES="SpecimenTypes";
public static final String ALIQUOT_ALIQUOT_COUNTS="AliquotCounts";
//Specimen Array Aliquots pages
public static final String PAGEOF_SPECIMEN_ARRAY_ALIQUOT = "pageOfSpecimenArrayAliquot";
public static final String PAGEOF_SPECIMEN_ARRAY_CREATE_ALIQUOT = "pageOfSpecimenArrayCreateAliquot";
public static final String PAGEOF_SPECIMEN_ARRAY_ALIQUOT_SUMMARY = "pageOfSpecimenArrayAliquotSummary";
//Specimen Array Aliquots Action
public static final String SPECIMEN_ARRAY_ALIQUOT_ACTION = "SpecimenArrayAliquots.do";
public static final String SPECIMEN_ARRAY_CREATE_ALIQUOT_ACTION = "SpecimenArrayCreateAliquots.do";
//Constants related to QuickEvents functionality
public static final String QUICKEVENTS_ACTION = "QuickEventsSearch.do";
public static final String QUICKEVENTSPARAMETERS_ACTION = "ListSpecimenEventParameters.do";
//SimilarContainers Action
public static final String SIMILAR_CONTAINERS_ACTION = "SimilarContainers.do";
public static final String CREATE_SIMILAR_CONTAINERS_ACTION = "CreateSimilarContainers.do";
public static final String SIMILAR_CONTAINERS_ADD_ACTION = "SimilarContainersAdd.do";
//Constants related to Similar Containsers
public static final String PAGEOF_SIMILAR_CONTAINERS = "pageOfSimilarContainers";
public static final String PAGEOF_CREATE_SIMILAR_CONTAINERS = "pageOfCreateSimilarContainers";
public static final String PAGEOF_STORAGE_CONTAINER = "pageOfStorageContainer";
//Levels of nodes in query results tree.
public static final int MAX_LEVEL = 5;
public static final int MIN_LEVEL = 1;
public static final String TABLE_NAME_COLUMN = "TABLE_NAME";
//Spreadsheet view Constants in DataViewAction.
public static final String PARTICIPANT = "Participant";
public static final String ACCESSION = "Accession";
public static final String QUERY_PARTICIPANT_SEARCH_ACTION = "QueryParticipantSearch.do?id=";
public static final String QUERY_PARTICIPANT_EDIT_ACTION = "QueryParticipantEdit.do";
public static final String QUERY_COLLECTION_PROTOCOL_SEARCH_ACTION = "QueryCollectionProtocolSearch.do?id=";
public static final String QUERY_COLLECTION_PROTOCOL_EDIT_ACTION = "QueryCollectionProtocolEdit.do";
public static final String QUERY_SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "QuerySpecimenCollectionGroupSearch.do?id=";
public static final String QUERY_SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "QuerySpecimenCollectionGroupEdit.do";
public static final String QUERY_SPECIMEN_SEARCH_ACTION = "QuerySpecimenSearch.do?id=";
public static final String QUERY_SPECIMEN_EDIT_ACTION = "QuerySpecimenEdit.do";
//public static final String QUERY_ACCESSION_SEARCH_ACTION = "QueryAccessionSearch.do?id=";
public static final String SPECIMEN = "Specimen";
public static final String SEGMENT = "Segment";
public static final String SAMPLE = "Sample";
public static final String COLLECTION_PROTOCOL_REGISTRATION = "CollectionProtocolRegistration";
public static final String PARTICIPANT_ID_COLUMN = "PARTICIPANT_ID";
public static final String ACCESSION_ID_COLUMN = "ACCESSION_ID";
public static final String SPECIMEN_ID_COLUMN = "SPECIMEN_ID";
public static final String SEGMENT_ID_COLUMN = "SEGMENT_ID";
public static final String SAMPLE_ID_COLUMN = "SAMPLE_ID";
//For getting the tables for Simple Query and Fcon Query.
public static final int ADVANCE_QUERY_TABLES = 2;
//Identifiers for various Form beans
public static final int DEFAULT_BIZ_LOGIC = 0;
public static final int USER_FORM_ID = 1;
public static final int ACCESSION_FORM_ID = 3;
public static final int REPORTED_PROBLEM_FORM_ID = 4;
public static final int INSTITUTION_FORM_ID = 5;
public static final int APPROVE_USER_FORM_ID = 6;
public static final int ACTIVITY_STATUS_FORM_ID = 7;
public static final int DEPARTMENT_FORM_ID = 8;
public static final int COLLECTION_PROTOCOL_FORM_ID = 9;
public static final int DISTRIBUTIONPROTOCOL_FORM_ID = 10;
public static final int STORAGE_CONTAINER_FORM_ID = 11;
public static final int STORAGE_TYPE_FORM_ID = 12;
public static final int SITE_FORM_ID = 13;
public static final int CANCER_RESEARCH_GROUP_FORM_ID = 14;
public static final int BIOHAZARD_FORM_ID = 15;
public static final int FROZEN_EVENT_PARAMETERS_FORM_ID = 16;
public static final int CHECKIN_CHECKOUT_EVENT_PARAMETERS_FORM_ID = 17;
public static final int RECEIVED_EVENT_PARAMETERS_FORM_ID = 18;
public static final int FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 21;
public static final int CELL_SPECIMEN_REVIEW_PARAMETERS_FORM_ID =23;
public static final int TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 24;
public static final int DISPOSAL_EVENT_PARAMETERS_FORM_ID = 25;
public static final int THAW_EVENT_PARAMETERS_FORM_ID = 26;
public static final int MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_FORM_ID = 27;
public static final int COLLECTION_EVENT_PARAMETERS_FORM_ID = 28;
public static final int TRANSFER_EVENT_PARAMETERS_FORM_ID = 29;
public static final int SPUN_EVENT_PARAMETERS_FORM_ID = 30;
public static final int EMBEDDED_EVENT_PARAMETERS_FORM_ID = 31;
public static final int FIXED_EVENT_PARAMETERS_FORM_ID = 32;
public static final int PROCEDURE_EVENT_PARAMETERS_FORM_ID = 33;
public static final int CREATE_SPECIMEN_FORM_ID = 34;
public static final int FORGOT_PASSWORD_FORM_ID = 35;
public static final int SIGNUP_FORM_ID = 36;
public static final int DISTRIBUTION_FORM_ID = 37;
public static final int SPECIMEN_EVENT_PARAMETERS_FORM_ID = 38;
public static final int SHOPPING_CART_FORM_ID = 39;
public static final int CONFIGURE_RESULT_VIEW_ID = 41;
public static final int ADVANCE_QUERY_INTERFACE_ID = 42;
public static final int COLLECTION_PROTOCOL_REGISTRATION_FORM_ID = 19;
public static final int PARTICIPANT_FORM_ID = 2;
public static final int SPECIMEN_COLLECTION_GROUP_FORM_ID = 20;
public static final int NEW_SPECIMEN_FORM_ID = 22;
public static final int ALIQUOT_FORM_ID = 44;
public static final int QUICKEVENTS_FORM_ID = 45;
public static final int LIST_SPECIMEN_EVENT_PARAMETERS_FORM_ID = 46;
public static final int SIMILAR_CONTAINERS_FORM_ID = 47; // chetan (13-07-2006)
public static final int SPECIMEN_ARRAY_TYPE_FORM_ID = 48;
public static final int ARRAY_DISTRIBUTION_FORM_ID = 49;
public static final int SPECIMEN_ARRAY_FORM_ID = 50;
public static final int SPECIMEN_ARRAY_ALIQUOT_FORM_ID = 51;
public static final int ASSIGN_PRIVILEGE_FORM_ID = 52;
public static final int CDE_FORM_ID = 53;
//Misc
public static final String SEPARATOR = " : ";
//Identifiers for JDBC DAO.
public static final int QUERY_RESULT_TREE_JDBC_DAO = 1;
//Activity Status values
public static final String ACTIVITY_STATUS_APPROVE = "Approve";
public static final String ACTIVITY_STATUS_REJECT = "Reject";
public static final String ACTIVITY_STATUS_NEW = "New";
public static final String ACTIVITY_STATUS_PENDING = "Pending";
//Approve User status values.
public static final String APPROVE_USER_APPROVE_STATUS = "Approve";
public static final String APPROVE_USER_REJECT_STATUS = "Reject";
public static final String APPROVE_USER_PENDING_STATUS = "Pending";
//Approve User Constants
public static final int ZERO = 0;
public static final int START_PAGE = 1;
public static final int NUMBER_RESULTS_PER_PAGE = 5;
public static final int NUMBER_RESULTS_PER_PAGE_SEARCH = 15;
public static final String PAGE_NUMBER = "pageNum";
public static final String RESULTS_PER_PAGE = "numResultsPerPage";
public static final String TOTAL_RESULTS = "totalResults";
public static final String PREVIOUS_PAGE = "prevpage";
public static final String NEXT_PAGE = "nextPage";
public static final String ORIGINAL_DOMAIN_OBJECT_LIST = "originalDomainObjectList";
public static final String SHOW_DOMAIN_OBJECT_LIST = "showDomainObjectList";
public static final String USER_DETAILS = "details";
public static final String CURRENT_RECORD = "currentRecord";
public static final String APPROVE_USER_EMAIL_SUBJECT = "Your membership status in caTISSUE Core.";
//Query Interface Results View Constants
public static final String PAGEOF_APPROVE_USER = "pageOfApproveUser";
public static final String PAGEOF_SIGNUP = "pageOfSignUp";
public static final String PAGEOF_USERADD = "pageOfUserAdd";
public static final String PAGEOF_USER_ADMIN = "pageOfUserAdmin";
public static final String PAGEOF_USER_PROFILE = "pageOfUserProfile";
public static final String PAGEOF_CHANGE_PASSWORD = "pageOfChangePassword";
//For Simple Query Interface and Edit.
public static final String PAGEOF_EDIT_OBJECT = "pageOfEditObject";
//Query results view temporary table columns.
public static final String QUERY_RESULTS_PARTICIPANT_ID = "PARTICIPANT_ID";
public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_ID = "COLLECTION_PROTOCOL_ID";
public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID = "COLLECTION_PROTOCOL_EVENT_ID";
public static final String QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID = "SPECIMEN_COLLECTION_GROUP_ID";
public static final String QUERY_RESULTS_SPECIMEN_ID = "SPECIMEN_ID";
public static final String QUERY_RESULTS_SPECIMEN_TYPE = "SPECIMEN_TYPE";
// Assign Privilege Constants.
public static final boolean PRIVILEGE_DEASSIGN = false;
public static final String OPERATION_DISALLOW = "Disallow";
//Constants for default column names to be shown for query result.
public static final String[] DEFAULT_SPREADSHEET_COLUMNS = {
// QUERY_RESULTS_PARTICIPANT_ID,QUERY_RESULTS_COLLECTION_PROTOCOL_ID,
// QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID,QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID,
// QUERY_RESULTS_SPECIMEN_ID,QUERY_RESULTS_SPECIMEN_TYPE
"IDENTIFIER","TYPE","ONE_DIMENSION_LABEL"
};
//Query results edit constants - MakeEditableAction.
public static final String EDITABLE = "editable";
//URL paths for Applet in TreeView.jsp
public static final String QUERY_TREE_APPLET = "edu/wustl/common/treeApplet/TreeApplet.class";
public static final String APPLET_CODEBASE = "Applet";
//Shopping Cart
public static final String SHOPPING_CART = "shoppingCart";
public static final int SELECT_OPTION_VALUE = -1;
public static final String [] TIME_HOUR_AMPM_ARRAY = {"AM","PM"};
// Constants required in CollectionProtocol.jsp Page
public static final String COLLECTIONPROTOCOL_SEARCH_ACTION = "CollectionProtocolSearch.do";
public static final String COLLECTIONPROTOCOL_ADD_ACTION = "CollectionProtocolAdd.do";
public static final String COLLECTIONPROTOCOL_EDIT_ACTION = "CollectionProtocolEdit.do";
// Constants required in DistributionProtocol.jsp Page
public static final String DISTRIBUTIONPROTOCOL_SEARCH_ACTION = "DistributionProtocolSearch.do";
public static final String DISTRIBUTIONPROTOCOL_ADD_ACTION = "DistributionProtocolAdd.do";
public static final String DISTRIBUTIONPROTOCOL_EDIT_ACTION = "DistributionProtocolEdit.do";
public static final String [] ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed",
"Disabled"
};
public static final String [] SITE_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed"
};
public static final String [] USER_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed"
};
public static final String [] APPROVE_USER_STATUS_VALUES = {
SELECT_OPTION,
APPROVE_USER_APPROVE_STATUS,
APPROVE_USER_REJECT_STATUS,
APPROVE_USER_PENDING_STATUS,
};
public static final String [] REPORTED_PROBLEM_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Closed",
"Pending"
};
public static final String [] DISPOSAL_EVENT_ACTIVITY_STATUS_VALUES = {
"Closed",
"Disabled"
};
public static final String TISSUE = "Tissue";
public static final String FLUID = "Fluid";
public static final String CELL = "Cell";
public static final String MOLECULAR = "Molecular";
public static final String [] SPECIMEN_TYPE_VALUES = {
SELECT_OPTION,
TISSUE,
FLUID,
CELL,
MOLECULAR
};
public static final String [] HOUR_ARRAY = {
"00",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23"
};
public static final String [] MINUTES_ARRAY = {
"00",
"01",
"02",
"03",
"04",
"05",
"06",
"07",
"08",
"09",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23",
"24",
"25",
"26",
"27",
"28",
"29",
"30",
"31",
"32",
"33",
"34",
"35",
"36",
"37",
"38",
"39",
"40",
"41",
"42",
"43",
"44",
"45",
"46",
"47",
"48",
"49",
"50",
"51",
"52",
"53",
"54",
"55",
"56",
"57",
"58",
"59"
};
public static final String UNIT_GM = "gm";
public static final String UNIT_ML = "ml";
public static final String UNIT_CC = "cell count";
public static final String UNIT_MG = "g";
public static final String UNIT_CN = "count";
public static final String UNIT_CL = "cells";
public static final String CDE_NAME_CLINICAL_STATUS = "Clinical Status";
public static final String CDE_NAME_GENDER = "Gender";
public static final String CDE_NAME_GENOTYPE = "Genotype";
public static final String CDE_NAME_SPECIMEN_CLASS = "Specimen";
public static final String CDE_NAME_SPECIMEN_TYPE = "Specimen Type";
public static final String CDE_NAME_TISSUE_SIDE = "Tissue Side";
public static final String CDE_NAME_PATHOLOGICAL_STATUS = "Pathological Status";
public static final String CDE_NAME_RECEIVED_QUALITY = "Received Quality";
public static final String CDE_NAME_FIXATION_TYPE = "Fixation Type";
public static final String CDE_NAME_COLLECTION_PROCEDURE = "Collection Procedure";
public static final String CDE_NAME_CONTAINER = "Container";
public static final String CDE_NAME_METHOD = "Method";
public static final String CDE_NAME_EMBEDDING_MEDIUM = "Embedding Medium";
public static final String CDE_NAME_BIOHAZARD = "Biohazard";
public static final String CDE_NAME_ETHNICITY = "Ethnicity";
public static final String CDE_NAME_RACE = "Race";
public static final String CDE_VITAL_STATUS = "Vital Status";
public static final String CDE_NAME_CLINICAL_DIAGNOSIS = "Clinical Diagnosis";
public static final String CDE_NAME_SITE_TYPE = "Site Type";
public static final String CDE_NAME_COUNTRY_LIST = "Countries";
public static final String CDE_NAME_STATE_LIST = "States";
public static final String CDE_NAME_HISTOLOGICAL_QUALITY = "Histological Quality";
//Constants for Advanced Search
public static final String STRING_OPERATORS = "StringOperators";
public static final String DATE_NUMERIC_OPERATORS = "DateNumericOperators";
public static final String ENUMERATED_OPERATORS = "EnumeratedOperators";
public static final String MULTI_ENUMERATED_OPERATORS = "MultiEnumeratedOperators";
public static final String [] STORAGE_STATUS_ARRAY = {
SELECT_OPTION,
"CHECK IN",
"CHECK OUT"
};
// constants for Data required in query
public static final String ALIAS_NAME_TABLE_NAME_MAP="objectTableNames";
public static final String SYSTEM_IDENTIFIER_COLUMN_NAME = "IDENTIFIER";
public static final String NAME = "name";
public static final String EVENT_PARAMETERS[] = { Constants.SELECT_OPTION,
"Cell Specimen Review", "Check In Check Out", "Collection",
"Disposal", "Embedded", "Fixed", "Fluid Specimen Review",
"Frozen", "Molecular Specimen Review", "Procedure", "Received",
"Spun", "Thaw", "Tissue Specimen Review", "Transfer" };
public static final String EVENT_PARAMETERS_COLUMNS[] = { "Identifier",
"Event Parameter", "User", "Date / Time", "PageOf"};
public static final String DERIVED_SPECIMEN_COLUMNS[] = { "Label",
"Class", "Type", "Quantity", "rowSelected"};
public static final String [] SHOPPING_CART_COLUMNS = {"","Identifier",
"Type", "Subtype", "Tissue Site", "Tissue Side", "Pathological Status"};
//Constants required in AssignPrivileges.jsp
public static final String ASSIGN = "assignOperation";
public static final String PRIVILEGES = "privileges";
public static final String OBJECT_TYPES = "objectTypes";
public static final String OBJECT_TYPE_VALUES = "objectTypeValues";
public static final String RECORD_IDS = "recordIds";
public static final String ATTRIBUTES = "attributes";
public static final String GROUPS = "groups";
public static final String USERS_FOR_USE_PRIVILEGE = "usersForUsePrivilege";
public static final String USERS_FOR_READ_PRIVILEGE = "usersForReadPrivilege";
public static final String ASSIGN_PRIVILEGES_ACTION = "AssignPrivileges.do";
public static final int CONTAINER_IN_ANOTHER_CONTAINER = 2;
/**
* @param id
* @return
*/
public static String getUserPGName(Long identifier)
{
if(identifier == null)
{
return "USER_";
}
return "USER_"+identifier;
}
/**
* @param id
* @return
*/
public static String getUserGroupName(Long identifier)
{
if(identifier == null)
{
return "USER_";
}
return "USER_"+identifier;
}
//Mandar 25-Apr-06 : bug 1414 : Tissue units as per type
// tissue types with unit= count
public static final String FROZEN_TISSUE_BLOCK = "Frozen Tissue Block"; // PREVIOUS FROZEN BLOCK
public static final String FROZEN_TISSUE_SLIDE = "Frozen Tissue Slide"; // SLIDE
public static final String FIXED_TISSUE_BLOCK = "Fixed Tissue Block"; // PARAFFIN BLOCK
public static final String NOT_SPECIFIED = "Not Specified";
// tissue types with unit= g
public static final String FRESH_TISSUE = "Fresh Tissue";
public static final String FROZEN_TISSUE = "Frozen Tissue";
public static final String FIXED_TISSUE = "Fixed Tissue";
public static final String FIXED_TISSUE_SLIDE = "Fixed Tissue Slide";
//tissue types with unit= cc
public static final String MICRODISSECTED = "Microdissected";
// constants required for Distribution Report
public static final String CONFIGURATION_TABLES = "configurationTables";
public static final String DISTRIBUTION_TABLE_AlIAS[] = {"CollectionProtReg","Participant","Specimen",
"SpecimenCollectionGroup","DistributedItem"};
public static final String TABLE_COLUMN_DATA_MAP = "tableColumnDataMap";
public static final String CONFIGURE_RESULT_VIEW_ACTION = "ConfigureResultView.do";
public static final String TABLE_NAMES_LIST = "tableNamesList";
public static final String COLUMN_NAMES_LIST = "columnNamesList";
public static final String SPECIMEN_COLUMN_NAMES_LIST = "specimenColumnNamesList";
public static final String DISTRIBUTION_ID = "distributionId";
public static final String CONFIGURE_DISTRIBUTION_ACTION = "ConfigureDistribution.do";
public static final String DISTRIBUTION_REPORT_ACTION = "DistributionReport.do";
public static final String ARRAY_DISTRIBUTION_REPORT_ACTION = "ArrayDistributionReport.do";
public static final String DISTRIBUTION_REPORT_SAVE_ACTION="DistributionReportSave.do";
public static final String ARRAY_DISTRIBUTION_REPORT_SAVE_ACTION="ArrayDistributionReportSave.do";
public static final String SELECTED_COLUMNS[] = {"Specimen.IDENTIFIER.Identifier : Specimen",
"Specimen.TYPE.Type : Specimen",
"SpecimenCharacteristics.TISSUE_SITE.Tissue Site : Specimen",
"SpecimenCharacteristics.TISSUE_SIDE.Tissue Side : Specimen",
"Specimen.PATHOLOGICAL_STATUS.Pathological Status : Specimen",
"DistributedItem.QUANTITY.Quantity : Distribution"};
//"SpecimenCharacteristics.PATHOLOGICAL_STATUS.Pathological Status : Specimen",
public static final String SPECIMEN_IN_ARRAY_SELECTED_COLUMNS[] = {
"Specimen.LABEL.Label : Specimen",
"Specimen.BARCODE.barcode : Specimen",
"SpecimenArrayContent.PositionDimensionOne.PositionDimensionOne : Specimen",
"SpecimenArrayContent.PositionDimensionTwo.PositionDimensionTwo : Specimen",
"Specimen.CLASS.CLASS : Specimen",
"Specimen.TYPE.Type : Specimen",
"SpecimenCharacteristics.TISSUE_SIDE.Tissue Side : Specimen",
"SpecimenCharacteristics.TISSUE_SITE.Tissue Site : Specimen",
};
public static final String ARRAY_SELECTED_COLUMNS[] = {
"SpecimenArray.Name.Name : SpecimenArray",
"Container.barcode.Barcode : SpecimenArray",
"ContainerType.name.ArrayType : ContainerType",
"Container.PositionDimensionOne.Position One: Container",
"Container.PositionDimensionTwo.Position Two: Container",
"Container.CapacityOne.Dimension One: Container",
"Container.CapacityTwo.Dimension Two: Container",
"ContainerType.SpecimenClass.specimen class : ContainerType",
"ContainerType.SpecimenTypes.specimen Types : ContainerType",
"Container.Comment.comment: Container",
};
public static final String SPECIMEN_ID_LIST = "specimenIdList";
public static final String DISTRIBUTION_ACTION = "Distribution.do?pageOf=pageOfDistribution";
public static final String DISTRIBUTION_REPORT_NAME = "Distribution Report.csv";
public static final String DISTRIBUTION_REPORT_FORM="distributionReportForm";
public static final String DISTRIBUTED_ITEMS_DATA = "distributedItemsData";
public static final String DISTRIBUTED_ITEM = "DistributedItem";
//constants for Simple Query Interface Configuration
public static final String CONFIGURE_SIMPLE_QUERY_ACTION = "ConfigureSimpleQuery.do";
public static final String CONFIGURE_SIMPLE_QUERY_VALIDATE_ACTION = "ConfigureSimpleQueryValidate.do";
public static final String CONFIGURE_SIMPLE_SEARCH_ACTION = "ConfigureSimpleSearch.do";
public static final String SIMPLE_SEARCH_ACTION = "SimpleSearch.do";
public static final String SIMPLE_SEARCH_AFTER_CONFIGURE_ACTION = "SimpleSearchAfterConfigure.do";
public static final String PAGEOF_DISTRIBUTION = "pageOfDistribution";
public static final String RESULT_VIEW_VECTOR = "resultViewVector";
public static final String SPECIMENT_VIEW_ATTRIBUTE = "defaultViewAttribute";
//public static final String SIMPLE_QUERY_COUNTER = "simpleQueryCount";
public static final String UNDEFINED = "Undefined";
public static final String UNKNOWN = "Unknown";
public static final String UNSPECIFIED = "UnSpecified";
public static final String SEARCH_RESULT = "SearchResult.csv";
// Mandar : LightYellow and Green colors for CollectionProtocol SpecimenRequirements. Bug id: 587
// public static final String ODD_COLOR = "#FEFB85";
// public static final String EVEN_COLOR = "#A7FEAB";
// Light and dark shades of GREY.
public static final String ODD_COLOR = "#E5E5E5";
public static final String EVEN_COLOR = "#F7F7F7";
// TO FORWARD THE REQUEST ON SUBMIT IF STATUS IS DISABLED
public static final String BIO_SPECIMEN = "/ManageBioSpecimen.do";
public static final String ADMINISTRATIVE = "/ManageAdministrativeData.do";
public static final String PARENT_SPECIMEN_ID = "parentSpecimenId";
public static final String COLLECTION_REGISTRATION_ID = "collectionProtocolId";
public static final String FORWARDLIST = "forwardToList";
public static final String [][] SPECIMEN_FORWARD_TO_LIST = {
{"Submit", "success"},
{"Derive", "createNew"},
{"Add Events", "eventParameters"},
{"More", "sameCollectionGroup"},
{"Distribute", "distribution" }
};
public static final String [] SPECIMEN_BUTTON_TIPS = {
"Submit only",
"Submit and derive",
"Submit and add events",
"Submit and add more to same group",
"Submit and distribute"
};
public static final String [][] SPECIMEN_COLLECTION_GROUP_FORWARD_TO_LIST = {
{"Submit", "success"},
{"Add Specimen", "createNewSpecimen"}
};
public static final String [][] PROTOCOL_REGISTRATION_FORWARD_TO_LIST = {
{"Submit", "success"},
{"Specimen Collection Group", "createSpecimenCollectionGroup"}
};
public static final String [][] PARTICIPANT_FORWARD_TO_LIST = {
{"Submit", "success"},
{"Register to Protocol", "createParticipantRegistration"}
};
public static final String [][] STORAGE_TYPE_FORWARD_TO_LIST = {
{"Submit", "success"},
{"Add Container", "storageContainer"}
};
//Constants Required for Advance Search
//Tree related
//public static final String PARTICIPANT ='Participant';
public static final String[] ADVANCE_QUERY_TREE_HEIRARCHY={ //Represents the Advance Query tree Heirarchy.
Constants.PARTICIPANT,
Constants.COLLECTION_PROTOCOL,
Constants.SPECIMEN_COLLECTION_GROUP,
Constants.SPECIMEN
};
public static final String MENU_COLLECTION_PROTOCOL ="Collection Protocol";
public static final String MENU_SPECIMEN_COLLECTION_GROUP ="Specimen Collection Group";
public static final String MENU_DISTRIBUTION_PROTOCOL = "Distribution Protocol";
public static final String SPECIMEN_COLLECTION_GROUP ="SpecimenCollectionGroup";
public static final String DISTRIBUTION = "Distribution";
public static final String DISTRIBUTION_PROTOCOL = "DistributionProtocol";
public static final String CP = "CP";
public static final String SCG = "SCG";
public static final String D = "D";
public static final String DP = "DP";
public static final String C = "C";
public static final String S = "S";
public static final String P = "P";
public static final String ADVANCED_CONDITIONS_QUERY_VIEW = "advancedCondtionsQueryView";
public static final String ADVANCED_SEARCH_ACTION = "AdvanceSearch.do";
public static final String ADVANCED_SEARCH_RESULTS_ACTION = "AdvanceSearchResults.do";
public static final String CONFIGURE_ADVANCED_SEARCH_RESULTS_ACTION = "ConfigureAdvanceSearchResults.do";
public static final String ADVANCED_QUERY_ADD = "Add";
public static final String ADVANCED_QUERY_EDIT = "Edit";
public static final String ADVANCED_QUERY_DELETE = "Delete";
public static final String ADVANCED_QUERY_OPERATOR = "Operator";
public static final String ADVANCED_QUERY_OR = "OR";
public static final String ADVANCED_QUERY_AND = "pAND";
public static final String EVENT_CONDITIONS = "eventConditions";
public static final String IDENTIFIER_COLUMN_ID_MAP = "identifierColumnIdsMap";
public static final String PAGEOF_PARTICIPANT_QUERY_EDIT= "pageOfParticipantQueryEdit";
public static final String PAGEOF_COLLECTION_PROTOCOL_QUERY_EDIT= "pageOfCollectionProtocolQueryEdit";
public static final String PAGEOF_SPECIMEN_COLLECTION_GROUP_QUERY_EDIT= "pageOfSpecimenCollectionGroupQueryEdit";
public static final String PAGEOF_SPECIMEN_QUERY_EDIT= "pageOfSpecimenQueryEdit";
public static final String PARTICIPANT_COLUMNS = "particpantColumns";
public static final String COLLECTION_PROTOCOL_COLUMNS = "collectionProtocolColumns";
public static final String SPECIMEN_COLLECTION_GROUP_COLUMNS = "SpecimenCollectionGroupColumns";
public static final String SPECIMEN_COLUMNS = "SpecimenColumns";
public static final String USER_ID_COLUMN = "USER_ID";
public static final String GENERIC_SECURITYMANAGER_ERROR = "The Security Violation error occured during a database operation. Please report this problem to the adminstrator";
public static final String BOOLEAN_YES = "Yes";
public static final String BOOLEAN_NO = "No";
public static final String PACKAGE_DOMAIN = "edu.wustl.catissuecore.domain";
//Constants for isAuditable and isSecureUpdate required for Dao methods in Bozlogic
public static final boolean IS_AUDITABLE_TRUE = true;
public static final boolean IS_SECURE_UPDATE_TRUE = true;
public static final boolean HAS_OBJECT_LEVEL_PRIVILEGE_FALSE = false;
//Constants for HTTP-API
public static final String CONTENT_TYPE = "CONTENT-TYPE";
// For StorageContainer isFull status
public static final String IS_CONTAINER_FULL_LIST = "isContainerFullList";
public static final String [] IS_CONTAINER_FULL_VALUES = {
SELECT_OPTION,
"True",
"False"
};
public static final String STORAGE_CONTAINER_DIM_ONE_LABEL = "oneDimLabel";
public static final String STORAGE_CONTAINER_DIM_TWO_LABEL = "twoDimLabel";
// public static final String SPECIMEN_TYPE_TISSUE = "Tissue";
// public static final String SPECIMEN_TYPE_FLUID = "Fluid";
// public static final String SPECIMEN_TYPE_CELL = "Cell";
// public static final String SPECIMEN_TYPE_MOL = "Molecular";
public static final String SPECIMEN_TYPE_COUNT = "Count";
public static final String SPECIMEN_TYPE_QUANTITY = "Quantity";
public static final String SPECIMEN_TYPE_DETAILS = "Details";
public static final String SPECIMEN_COUNT = "totalSpecimenCount";
public static final String TOTAL = "Total";
public static final String SPECIMENS = "Specimens";
//User Roles
public static final String TECHNICIAN = "Technician";
public static final String SUPERVISOR = "Supervisor";
public static final String SCIENTIST = "Scientist";
public static final String CHILD_CONTAINER_TYPE = "childContainerType";
public static final String UNUSED = "Unused";
public static final String TYPE = "Type";
//Mandar: 28-Apr-06 Bug 1129
public static final String DUPLICATE_SPECIMEN="duplicateSpecimen";
//Constants required in ParticipantLookupAction
public static final String PARTICIPANT_LOOKUP_PARAMETER="ParticipantLookupParameter";
public static final String PARTICIPANT_LOOKUP_CUTOFF="lookup.cutoff";
public static final String PARTICIPANT_LOOKUP_ALGO="ParticipantLookupAlgo";
public static final String PARTICIPANT_LOOKUP_SUCCESS="success";
public static final String PARTICIPANT_ADD_FORWARD="participantAdd";
public static final String PARTICIPANT_SYSTEM_IDENTIFIER="IDENTIFIER";
public static final String PARTICIPANT_LAST_NAME="LAST_NAME";
public static final String PARTICIPANT_FIRST_NAME="FIRST_NAME";
public static final String PARTICIPANT_MIDDLE_NAME="MIDDLE_NAME";
public static final String PARTICIPANT_BIRTH_DATE="BIRTH_DATE";
public static final String PARTICIPANT_DEATH_DATE="DEATH_DATE";
public static final String PARTICIPANT_VITAL_STATUS="VITAL_STATUS";
public static final String PARTICIPANT_GENDER="GENDER";
public static final String PARTICIPANT_SEX_GENOTYPE="SEX_GENOTYPE";
public static final String PARTICIPANT_RACE="RACE";
public static final String PARTICIPANT_ETHINICITY="ETHINICITY";
public static final String PARTICIPANT_SOCIAL_SECURITY_NUMBER="SOCIAL_SECURITY_NUMBER";
public static final String PARTICIPANT_PROBABLITY_MATCH="Probability";
public static final String PARTICIPANT_SSN_EXACT="SSNExact";
public static final String PARTICIPANT_SSN_PARTIAL="SSNPartial";
public static final String PARTICIPANT_DOB_EXACT="DOBExact";
public static final String PARTICIPANT_DOB_PARTIAL="DOBPartial";
public static final String PARTICIPANT_LAST_NAME_EXACT="LastNameExact";
public static final String PARTICIPANT_LAST_NAME_PARTIAL="LastNamePartial";
public static final String PARTICIPANT_FIRST_NAME_EXACT="NameExact";
public static final String PARTICIPANT_FIRST_NAME_PARTIAL="NamePartial";
public static final String PARTICIPANT_MIDDLE_NAME_EXACT="MiddleNameExact";
public static final String PARTICIPANT_MIDDLE_NAME_PARTIAL="MiddleNamePartial";
public static final String PARTICIPANT_GENDER_EXACT="GenderExact";
public static final String PARTICIPANT_RACE_EXACT="RaceExact";
public static final String PARTICIPANT_RACE_PARTIAL="RacePartial";
public static final String PARTICIPANT_BONUS="Bonus";
public static final String PARTICIPANT_TOTAL_POINTS="TotalPoints";
public static final String PARTICIPANT_MATCH_CHARACTERS_FOR_LAST_NAME="MatchCharactersForLastName";
//Constants for integration of caTies and CAE with caTissue Core
public static final String LINKED_DATA = "linkedData";
public static final String APPLICATION_ID = "applicationId";
public static final String CATIES = "caTies";
public static final String CAE = "cae";
public static final String EDIT_TAB_LINK = "editTabLink";
public static final String CATIES_PUBLIC_SERVER_NAME = "CaTiesPublicServerName";
public static final String CATIES_PRIVATE_SERVER_NAME = "CaTiesPrivateServerName";
//Constants for StorageContainerMap Applet
public static final String CONTAINER_STYLEID = "containerStyleId";
public static final String XDIM_STYLEID = "xDimStyleId";
public static final String YDIM_STYLEID = "yDimStyleId";
//Constants for QuickEvents
public static final String EVENT_SELECTED = "eventSelected";
//Constant for SpecimenEvents page.
public static final String EVENTS_TITLE_MESSAGE = "Existing events for this specimen";
public static final String SURGICAL_PATHOLOGY_REPORT = "Surgical Pathology Report";
public static final String CLINICAL_ANNOTATIONS = "Clinical Annotations";
//Constants for Specimen Collection Group name- new field
public static final String RESET_NAME ="resetName";
// Labels for Storage Containers
public static final String[] STORAGE_CONTAINER_LABEL = {" Name"," Pos1"," Pos2"};
//Constans for Any field
public static final String HOLDS_ANY = "--All
//Constants : Specimen -> lineage
public static final String NEW_SPECIMEN = "New";
public static final String DERIVED_SPECIMEN = "Derived";
public static final String ALIQUOT = "Aliquot";
//Constant for length of messageBody in Reported problem page
public static final int messageLength= 500;
public static final String NEXT_NUMBER="nextNumber";
// public static final String getCollectionProtocolPIGroupName(Long identifier)
// if(identifier == null)
// return "PI_COLLECTION_PROTOCOL_";
// return "PI_COLLECTION_PROTOCOL_"+identifier;
// public static final String getCollectionProtocolCoordinatorGroupName(Long identifier)
// if(identifier == null)
// return "COORDINATORS_COLLECTION_PROTOCOL_";
// return "COORDINATORS_COLLECTION_PROTOCOL_"+identifier;
// public static final String getDistributionProtocolPIGroupName(Long identifier)
// if(identifier == null)
// return "PI_DISTRIBUTION_PROTOCOL_";
// return "PI_DISTRIBUTION_PROTOCOL_"+identifier;
// public static final String getCollectionProtocolPGName(Long identifier)
// if(identifier == null)
// return "COLLECTION_PROTOCOL_";
// return "COLLECTION_PROTOCOL_"+identifier;
// public static final String getDistributionProtocolPGName(Long identifier)
// if(identifier == null)
// return "DISTRIBUTION_PROTOCOL_";
// return "DISTRIBUTION_PROTOCOL_"+identifier;
public static final String ALL = "All";
//constant for pagination data list
public static final String PAGINATION_DATA_LIST = "paginationDataList";
public static final int SPECIMEN_DISTRIBUTION_TYPE = 1;
public static final int SPECIMEN_ARRAY_DISTRIBUTION_TYPE = 2;
public static final int BARCODE_BASED_DISTRIBUTION = 1;
public static final int LABEL_BASED_DISTRIBUTION = 2;
public static final String DISTRIBUTION_TYPE_LIST = "DISTRIBUTION_TYPE_LIST";
public static final String DISTRIBUTION_BASED_ON = "DISTRIBUTION_BASED_ON";
public static final String SYSTEM_LABEL = "label";
public static final String SYSTEM_BARCODE = "barcode";
public static final String SYSTEM_NAME = "name";
//Mandar : 05Sep06 Array for multiple specimen field names
public static final String DERIVED_OPERATION = "derivedOperation";
public static final String [] MULTIPLE_SPECIMEN_FIELD_NAMES = {
"Collection Group",
"Parent ID",
"Name",
"Barcode",
"Class",
"Type",
"Tissue Site",
"Tissue Side",
"Pathological Status",
"Concentration",
"Quantity",
"Storage Location",
"Comments",
"Events",
"External Identifier",
"Biohazards"
// "Derived",
// "Aliquots"
};
public static final String PAGEOF_MULTIPLE_SPECIMEN = "pageOfMultipleSpecimen";
public static final String PAGEOF_MULTIPLE_SPECIMEN_MAIN = "pageOfMultipleSpecimenMain";
public static final String MULTIPLE_SPECIMEN_ACTION = "MultipleSpecimen.do";
public static final String INIT_MULTIPLE_SPECIMEN_ACTION = "InitMultipleSpecimen.do";
public static final String MULTIPLE_SPECIMEN_APPLET_ACTION = "MultipleSpecimenAppletAction.do";
public static final String NEW_MULTIPLE_SPECIMEN_ACTION = "NewMultipleSpecimenAction.do";
public static final String MULTIPLE_SPECIMEN_RESULT = "multipleSpecimenResult";
public static final String SAVED_SPECIMEN_COLLECTION = "savedSpecimenCollection";
public static final String [] MULTIPLE_SPECIMEN_FORM_FIELD_NAMES = {
"CollectionGroup",
"ParentID",
"Name",
"Barcode",
"Class",
"Type",
"TissueSite",
"TissueSide",
"PathologicalStatus",
"Concentration",
"Quantity",
"StorageLocation",
"Comments",
"Events",
"ExternalIdentifier",
"Biohazards"
// "Derived",
// "Aliquots"
};
public static final String MULTIPLE_SPECIMEN_MAP_KEY = "MULTIPLE_SPECIMEN_MAP_KEY";
public static final String MULTIPLE_SPECIMEN_EVENT_MAP_KEY = "MULTIPLE_SPECIMEN_EVENT_MAP_KEY";
public static final String MULTIPLE_SPECIMEN_FORM_BEAN_MAP_KEY = "MULTIPLE_SPECIMEN_FORM_BEAN_MAP_KEY";
public static final String MULTIPLE_SPECIMEN_BUTTONS_MAP_KEY = "MULTIPLE_SPECIMEN_BUTTONS_MAP_KEY";
public static final String DERIVED_FORM = "DerivedForm";
public static final String SPECIMEN_ATTRIBUTE_KEY = "specimenAttributeKey";
public static final String SPECIMEN_CLASS = "specimenClass";
public static final String SPECIMEN_CALL_BACK_FUNCTION = "specimenCallBackFunction";
public static final String APPEND_COUNT = "_count";
public static final String EXTERNALIDENTIFIER_TYPE = "ExternalIdentifier";
public static final String BIOHAZARD_TYPE = "BioHazard";
public static final String COMMENTS_TYPE = "comments";
public static final String EVENTS_TYPE = "Events";
public static final String MULTIPLE_SPECIMEN_APPLET_NAME = "MultipleSpecimenApplet";
public static final String INPUT_APPLET_DATA = "inputAppletData";
// Start Specimen Array Applet related constants
public static final String SPECIMEN_ARRAY_APPLET = "edu/wustl/catissuecore/applet/ui/SpecimenArrayApplet.class";
public static final String SPECIMEN_ARRAY_APPLET_NAME = "specimenArrayApplet";
public static final String SPECIMEN_ARRAY_CONTENT_KEY = "SpecimenArrayContentKey";
public static final String SPECIMEN_LABEL_COLUMN_NAME = "LABEL";
public static final String SPECIMEN_BARCODE_COLUMN_NAME = "barcode";
public static final String ARRAY_SPECIMEN_DOES_NOT_EXIST_EXCEPTION_MESSAGE = "Please enter valid specimen for specimen array!!specimen does not exist ";
public static final String ARRAY_NO_SPECIMEN__EXCEPTION_MESSAGE = "Specimen Array should contain at least one specimen";
public static final String ARRAY_SPEC_NOT_COMPATIBLE_EXCEPTION_MESSAGE = "Please add compatible specimens to specimen array (belong to same specimen class & specimen types of Array)";
public static final String ARRAY_MOLECULAR_QUAN_EXCEPTION_MESSAGE = "Please enter quantity for Molecular Specimen
/**
* Specify the SPECIMEN_ARRAY_LIST as key for specimen array type list
*/
public static final String SPECIMEN_ARRAY_TYPE_LIST = "specimenArrayList";
public static final String SPECIMEN_ARRAY_CLASSNAME = "edu.wustl.catissuecore.domain.SpecimenArray";
public static final String SPECIMEN_ARRAY_TYPE_CLASSNAME = "edu.wustl.catissuecore.domain.SpecimenArrayType";
// End
// Common Applet Constants
public static final String APPLET_SERVER_HTTP_START_STR = "http:
public static final String APPLET_SERVER_URL_PARAM_NAME = "serverURL";
public static final String IS_NOT_NULL = "is not null";
public static final String IS_NULL = "is null";
// Used in array action
public static final String ARRAY_TYPE_ANY_VALUE = "2";
public static final String ARRAY_TYPE_ANY_NAME = "Any";
// end
// Array Type All Id in table
public static final short ARRAY_TYPE_ALL_ID = 2;
// constants required for caching mechanism of ParticipantBizLogic
public static final String MAP_OF_PARTICIPANTS = "listOfParticipants";
public static final String EHCACHE_FOR_CATISSUE_CORE = "cacheForCaTissueCore";
public static final String ADD = "add";
public static final String EDIT = "edit";
public static final String ID = "id";
public static final String MANAGE_BIO_SPECIMEN_ACTION = "/ManageBioSpecimen.do";
public static final String CREATE_PARTICIPANT_REGISTRATION = "createParticipantRegistration";
public static final String CREATE_PARTICIPANT_REGISTRATION_ADD = "createParticipantRegistrationAdd";
public static final String CREATE_PARTICIPANT_REGISTRATION_EDIT= "createParticipantRegistrationEdit";
public static final String CAN_HOLD_CONTAINER_TYPE = "holdContainerType";
public static final String CAN_HOLD_SPECIMEN_CLASS = "holdSpecimenClass";
public static final String CAN_HOLD_COLLECTION_PROTOCOL = "holdCollectionProtocol";
public static final String CAN_HOLD_SPECIMEN_ARRAY_TYPE = "holdSpecimenArrayType";
public static final String COLLECTION_PROTOCOL_ID = "collectionProtocolId";
public static final String SPECIMEN_CLASS_NAME = "specimeClassName";
public static final String ENABLE_STORAGE_CONTAINER_GRID_PAGE = "enablePage";
public static final int ALL_STORAGE_TYPE_ID = 1; //Constant for the "All" storage type, which can hold all container type
public static final int ALL_SPECIMEN_ARRAY_TYPE_ID = 2;//Constant for the "All" storage type, which can hold all specimen array type
public static final String SPECIMEN_LABEL_CONTAINER_MAP = "Specimen : ";
public static final String CONTAINER_LABEL_CONTAINER_MAP = "Container : ";
public static final String SPECIMEN_ARRAY_LABEL_CONTAINER_MAP = "Array : ";
public static final String SPECIMEN_PROTOCOL ="SpecimenProtocol";
public static final String SPECIMEN_PROTOCOL_SHORT_TITLE ="SHORT_TITLE";
public static final String SPECIMEN_COLLECTION_GROUP_NAME ="NAME";
} |
package de.mickare.xserver;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.SocketTimeoutException;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;
import de.mickare.xserver.net.ConnectionObj;
import de.mickare.xserver.util.MyStringUtils;
public class MainServer implements Runnable {
private final ServerSocket server;
private final AbstractXServerManagerObj manager;
private final AtomicReference<Future<?>> task = new AtomicReference<Future<?>>( null );
protected MainServer( ServerSocket server, AbstractXServerManagerObj manager ) {
// super( "XServer Main Server Thread" );
this.server = server;
this.manager = manager;
}
public void close() throws IOException {
synchronized ( task ) {
this.server.close();
if ( this.task.get() != null ) {
this.task.get().cancel( true );
this.task.set( null );
}
}
}
public boolean isClosed() {
synchronized ( task ) {
return this.server.isClosed();
}
}
@Override
public void run() {
while ( !isClosed() ) {
try {
try {
new ConnectionObj( server.accept(), manager );
} catch ( SocketTimeoutException ste ) {
}
} catch ( IOException e ) {
manager.getLogger().warning( "Exception while connecting: " + e.getMessage() + "\n"
+ MyStringUtils.stackTraceToString( e ) );
}
}
}
public void start( ServerThreadPoolExecutor stpool ) {
synchronized ( task ) {
if ( task.get() == null ) {
task.set( stpool.runServerTask( this ) );
}
}
}
} |
package org.nutz.ioc.loader.xml;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import javax.xml.parsers.DocumentBuilder;
import org.nutz.ioc.IocLoader;
import org.nutz.ioc.IocLoading;
import org.nutz.ioc.Iocs;
import org.nutz.ioc.ObjectLoadException;
import org.nutz.ioc.meta.IocEventSet;
import org.nutz.ioc.meta.IocField;
import org.nutz.ioc.meta.IocObject;
import org.nutz.ioc.meta.IocValue;
import org.nutz.json.Json;
import org.nutz.lang.Lang;
import org.nutz.lang.Streams;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.resource.NutResource;
import org.nutz.resource.Scans;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* XMLIoc <br/>
* : <br/>
* <li>XML <li> <li>objtype,IocObject <li>
*
* @author wendal(wendal1985@gmail.com)
* @version 2.0
*/
public class XmlIocLoader implements IocLoader {
private static final Log LOG = Logs.get();
protected Map<String, IocObject> iocMap = new LinkedHashMap<String, IocObject>();
protected Map<String, String> parentMap = new TreeMap<String, String>();
protected static final String TAG_OBJ = "obj";
protected static final String TAG_ARGS = "args";
protected static final String TAG_FIELD = "field";
/**
* objid,objid <br/>
* objobj
*/
private static int innerId;
public XmlIocLoader(String... fileNames) {
try {
DocumentBuilder builder = Lang.xmls();
Document document;
List<NutResource> list = Scans.me().loadResource(getScanPatten(), fileNames);
for (NutResource nr : list) {
InputStream ins = nr.getInputStream();
document = builder.parse(ins);
document.normalizeDocument();
NodeList nodeListZ = ((Element) document.getDocumentElement()).getChildNodes();
for (int i = 0; i < nodeListZ.getLength(); i++) {
if (nodeListZ.item(i) instanceof Element)
paserBean((Element) nodeListZ.item(i), false);
}
Streams.safeClose(ins);
}
handleParent();
if (LOG.isDebugEnabled())
LOG.debugf("Load complete :\n%s", Json.toJson(iocMap));
}
catch (Throwable e) {
throw Lang.wrapThrow(e);
}
}
public String[] getName() {
return iocMap.keySet().toArray(new String[iocMap.keySet().size()]);
}
public boolean has(String name) {
return iocMap.containsKey(name);
}
public IocObject load(IocLoading loading, String name) throws ObjectLoadException {
if (has(name))
return iocMap.get(name);
throw new ObjectLoadException("Object '" + name + "' without define!");
}
protected String paserBean(Element beanElement, boolean innerBean) throws Throwable {
String beanId;
if (innerBean) {
beanId = "inner$" + innerId;
innerId++;
} else
beanId = beanElement.getAttribute("name");
if (beanId == null)
throw Lang.makeThrow("No name for one bean!");
if (iocMap.containsKey(beanId))
throw Lang.makeThrow("Name of bean is not unique! name=" + beanId);
if (LOG.isDebugEnabled())
LOG.debugf("Resolving bean define, name = %s", beanId);
IocObject iocObject = new IocObject();
String beanType = beanElement.getAttribute("type");
if (!Strings.isBlank(beanType))
iocObject.setType(Lang.loadClass(beanType));
String beanScope = beanElement.getAttribute("scope");
if (!Strings.isBlank(beanScope))
iocObject.setScope(beanScope);
String beanParent = beanElement.getAttribute("parent");
if (!Strings.isBlank(beanParent))
parentMap.put(beanId, beanParent);
parseArgs(beanElement, iocObject);
parseFields(beanElement, iocObject);
parseEvents(beanElement, iocObject);
iocMap.put(beanId, iocObject);
if (LOG.isDebugEnabled())
LOG.debugf("Resolved bean define, name = %s", beanId);
return beanId;
}
protected void parseArgs(Element beanElement, IocObject iocObject) throws Throwable {
List<Element> list = getChildNodesByTagName(beanElement, TAG_ARGS);
if (list.size() > 0) {
Element argsElement = list.get(0);
NodeList argNodeList = argsElement.getChildNodes();
for (int i = 0; i < argNodeList.getLength(); i++) {
if (argNodeList.item(i) instanceof Element)
iocObject.addArg(parseX((Element) argNodeList.item(i)));
}
}
}
protected void parseFields(Element beanElement, IocObject iocObject) throws Throwable {
List<Element> list = getChildNodesByTagName(beanElement, TAG_FIELD);
for (Element fieldElement : list) {
IocField iocField = new IocField();
iocField.setName(fieldElement.getAttribute("name"));
if (fieldElement.hasChildNodes()) {
NodeList nodeList = fieldElement.getChildNodes();
for (int j = 0; j < nodeList.getLength(); j++) {
if (nodeList.item(j) instanceof Element) {
iocField.setValue(parseX((Element) nodeList.item(j)));
break;
}
}
}
iocObject.addField(iocField);
}
}
protected static final String STR_TAG = "str";
protected static final String ARRAY_TAG = "array";
protected static final String MAP_TAG = "map";
protected static final String ITEM_TAG = "item";
protected static final String LIST_TAG = "list";
protected static final String SET_TAG = "set";
protected static final String OBJ_TAG = "obj";
protected static final String INT_TAG = "int";
protected static final String SHORT_TAG = "short";
protected static final String LONG_TAG = "long";
protected static final String FLOAT_TAG = "float";
protected static final String DOUBLE_TAG = "double";
protected static final String BOOLEAN_TAG = "bool";
protected static final String REFER_TAG = IocValue.TYPE_REFER;
protected static final String JAVA_TAG = IocValue.TYPE_JAVA;
protected static final String FILE_TAG = IocValue.TYPE_FILE;
protected static final String EVN_TAG = IocValue.TYPE_ENV;
protected static final String JNDI_TAG = IocValue.TYPE_JNDI;
protected static final String SYS_TAG = IocValue.TYPE_SYS;
protected IocValue parseX(Element element) throws Throwable {
IocValue iocValue = new IocValue();
String type = element.getNodeName();
if (EVN_TAG.equalsIgnoreCase(type)) {
iocValue.setType(EVN_TAG);
iocValue.setValue(element.getTextContent());
} else if (SYS_TAG.equalsIgnoreCase(type)) {
iocValue.setType(SYS_TAG);
iocValue.setValue(element.getTextContent());
} else if (JNDI_TAG.equalsIgnoreCase(type)) {
iocValue.setType(JNDI_TAG);
iocValue.setValue(element.getTextContent());
} else if (JAVA_TAG.equalsIgnoreCase(type)) {
iocValue.setType(JAVA_TAG);
iocValue.setValue(element.getTextContent());
} else if (REFER_TAG.equalsIgnoreCase(type)) {
iocValue.setType(REFER_TAG);
iocValue.setValue(element.getTextContent());
} else if (FILE_TAG.equalsIgnoreCase(type)) {
iocValue.setType(FILE_TAG);
iocValue.setValue(element.getTextContent());
} else if (OBJ_TAG.equalsIgnoreCase(type)) {
iocValue.setType(REFER_TAG);
iocValue.setValue(paserBean(element, true));
} else if (MAP_TAG.equalsIgnoreCase(type)) {
iocValue.setType(null);
iocValue.setValue(paserMap(element));
} else if (LIST_TAG.equalsIgnoreCase(type)) {
iocValue.setType(null);
iocValue.setValue(paserCollection(element));
} else if (ARRAY_TAG.equalsIgnoreCase(type)) {
iocValue.setType(null);
iocValue.setValue(paserCollection(element).toArray());
} else if (SET_TAG.equalsIgnoreCase(type)) {
iocValue.setType(null);
Set<Object> set = new HashSet<Object>();
set.addAll(paserCollection(element));
iocValue.setValue(set);
} else {
iocValue.setType(null);
iocValue.setValue(element.getFirstChild().getTextContent());
}
return iocValue;
}
protected List<IocValue> paserCollection(Element element) throws Throwable {
List<IocValue> list = new ArrayList<IocValue>();
if (element.hasChildNodes()) {
NodeList nodeList = element.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node instanceof Element) {
list.add((IocValue) parseX((Element) node));
}
}
}
return list;
}
protected Map<String, ?> paserMap(Element element) throws Throwable {
Map<String, Object> map = new HashMap<String, Object>();
if (element.hasChildNodes()) {
List<Element> elist = getChildNodesByTagName(element, ITEM_TAG);
for (Element elementItem : elist) {
String key = elementItem.getAttribute("key");
if (map.containsKey(key))
throw new IllegalArgumentException("key is not unique!");
NodeList list = elementItem.getChildNodes();
for (int j = 0; j < list.getLength(); j++) {
if (list.item(j) instanceof Element) {
map.put(key, parseX((Element) list.item(j)));
break;
}
}
if (!map.containsKey(key))
map.put(key, null);
}
}
return map;
}
protected void parseEvents(Element beanElement, IocObject iocObject) {
List<Element> elist = getChildNodesByTagName(beanElement, "events");
if (elist.size() > 0) {
Element eventsElement = elist.get(0);
IocEventSet iocEventSet = new IocEventSet();
elist = getChildNodesByTagName(eventsElement, "fetch");
if (elist.size() > 0)
iocEventSet.setFetch(elist.get(0).getTextContent());
elist = getChildNodesByTagName(eventsElement, "create");
if (elist.size() > 0)
iocEventSet.setCreate(elist.get(0).getTextContent());
elist = getChildNodesByTagName(eventsElement, "depose");
if (elist.size() > 0)
iocEventSet.setDepose(elist.get(0).getTextContent());
if (iocEventSet.getCreate() == null)
if (iocEventSet.getDepose() == null)
if (iocEventSet.getFetch() == null)
return;
iocObject.setEvents(iocEventSet);
}
}
protected void handleParent() {
// parentId.
for (String parentId : parentMap.values())
if (!iocMap.containsKey(parentId))
throw Lang.makeThrow("parent=%s", parentId);
List<String> parentList = new ArrayList<String>();
for (Entry<String, String> entry : parentMap.entrySet()) {
if (!check(parentList, entry.getKey()))
throw Lang.makeThrow("! bean id=%s", entry.getKey());
parentList.clear();
}
while (parentMap.size() != 0) {
Iterator<Entry<String, String>> it = parentMap.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> entry = it.next();
String beanId = entry.getKey();
String parentId = entry.getValue();
if (parentMap.get(parentId) == null) {
IocObject newIocObject = Iocs.mergeWith(iocMap.get(beanId),
iocMap.get(parentId));
iocMap.put(beanId, newIocObject);
it.remove();
}
}
}
}
protected boolean check(List<String> parentList, String currentBeanId) {
if (parentList.contains(currentBeanId))
return false;
String parentBeanId = parentMap.get(currentBeanId);
if (parentBeanId == null)
return true;
parentList.add(currentBeanId);
return check(parentList, parentBeanId);
}
protected String getScanPatten() {
return ".+[.]xml$";
}
protected List<Element> getChildNodesByTagName(Element element, String tagName) {
List<Element> list = new ArrayList<Element>();
NodeList nList = element.getElementsByTagName(tagName);
if(nList.getLength() > 0) {
for (int i = 0; i < nList.getLength(); i++) {
Node node = nList.item(i);
if(node.getParentNode().equals(element) && node instanceof Element)
list.add((Element) node);
}
}
return list;
}
} |
package org.openid4java.server;
import com.google.inject.Inject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openid4java.OpenIDException;
import org.openid4java.association.Association;
import org.openid4java.association.AssociationException;
import org.openid4java.association.AssociationSessionType;
import org.openid4java.association.DiffieHellmanSession;
import org.openid4java.discovery.yadis.YadisResolver;
import org.openid4java.message.*;
import org.openid4java.util.HttpFetcherFactory;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Manages OpenID communications with an OpenID Relying Party (Consumer).
*
* @author Marius Scurtescu, Johnny Bufu
*/
public class ServerManager
{
private static Log _log = LogFactory.getLog(ServerManager.class);
private static final boolean DEBUG = _log.isDebugEnabled();
/**
* Keeps track of the associations established with consumer sites.
*
* MUST be a different store than ServerAssociationStore#_privateAssociations,
* otherwise openid responses can be forged and user accounts hijacked.
*/
private ServerAssociationStore _sharedAssociations = new InMemoryServerAssociationStore();
/**
* Keeps track of private (internal) associations created for signing
* authentication responses for stateless consumer sites.
*
* MUST be a different store than ServerAssociationStore#_sharedAssociations,
* otherwise openid responses can be forged and user accounts hijacked.
*/
private ServerAssociationStore _privateAssociations = new InMemoryServerAssociationStore();
/**
* Flag for checking that shared associations are not accepted as or mixed with
* the private ones.
*
* Default true: check is performed at the expense of one extra association store query
* to ensure that ServerManager#_sharedAssociations and ServerManager#_privateAssociations
* are different store/instances.
*/
private boolean _checkPrivateSharedAssociations = true;
/**
* Nonce generator implementation.
*/
private NonceGenerator _nonceGenerator = new IncrementalNonceGenerator();
/**
* The lowest encryption level session accepted for association sessions
*/
private AssociationSessionType _minAssocSessEnc
= AssociationSessionType.NO_ENCRYPTION_SHA1MAC;
/**
* The preferred association session type; will be attempted first.
*/
private AssociationSessionType _prefAssocSessEnc
= AssociationSessionType.DH_SHA256;
/**
* Expiration time (in seconds) for associations.
*/
private int _expireIn = 1800;
/**
* In OpenID 1.x compatibility mode, the URL at the OpenID Provider where
* the user should be directed when a immediate authentication request
* fails.
* <p>
* If not configured, the OP endpoint URL is used.
*/
private String _userSetupUrl = null;
/**
* List of coma-separated fields to be signed in authentication responses.
*/
private String _signFields;
/**
* Array of extension namespace URIs that the consumer manager will sign,
* if present in auth responses.
*/
private String[] _signExtensions;
/**
* Used to perform verify realms against return_to URLs.
*/
private RealmVerifier _realmVerifier;
/**
* The OpenID Provider's endpoint URL, where it accepts OpenID
* authentication requests.
* <p>
* This is a global setting for the ServerManager; can also be set on a
* per message basis.
*
* @see #authResponse(org.openid4java.message.ParameterList, String, String, boolean, String)
*/
private String _opEndpointUrl;
/**
* Gets the store implementation used for keeping track of the generated
* associations established with consumer sites.
*
* @see ServerAssociationStore
*/
public ServerAssociationStore getSharedAssociations()
{
return _sharedAssociations;
}
/**
* Sets the store implementation that will be used for keeping track of
* the generated associations established with consumer sites.
*
* @param sharedAssociations ServerAssociationStore implementation
* @see ServerAssociationStore
*/
public void setSharedAssociations(ServerAssociationStore sharedAssociations)
{
_sharedAssociations = sharedAssociations;
}
/**
* Gets the store implementation used for keeping track of the generated
* private associations (used for signing responses to stateless consumer
* sites).
*
* @see ServerAssociationStore
*/
public ServerAssociationStore getPrivateAssociations()
{
return _privateAssociations;
}
/**
* Sets the store implementation that will be used for keeping track of
* the generated private associations (used for signing responses to
* stateless consumer sites).
*
* @param privateAssociations ServerAssociationStore implementation
* @see ServerAssociationStore
*/
public void setPrivateAssociations(ServerAssociationStore privateAssociations)
{
_privateAssociations = privateAssociations;
}
/**
* Gets the _checkPrivateSharedAssociations flag.
*
* @see ServerManager#_checkPrivateSharedAssociations
*/
public boolean isCheckPrivateSharedAssociations() {
return _checkPrivateSharedAssociations;
}
/**
* Sets the _checkPrivateSharedAssociations flag.
*
* @see ServerManager#_checkPrivateSharedAssociations
*/
public void setCheckPrivateSharedAssociations(boolean _checkPrivateSharedAssociations) {
this._checkPrivateSharedAssociations = _checkPrivateSharedAssociations;
}
/**
* Gets the minimum level of encryption configured for association sessions.
* <p>
* Default: no-encryption session, SHA1 MAC association
*/
public AssociationSessionType getMinAssocSessEnc()
{
return _minAssocSessEnc;
}
/**
* Gets the NonceGenerator used for generating nonce tokens to uniquely
* identify authentication responses.
*
* @see NonceGenerator
*/
public NonceGenerator getNonceGenerator()
{
return _nonceGenerator;
}
/**
* Sets the NonceGenerator implementation that will be used to generate
* nonce tokens to uniquely identify authentication responses.
*
* @see NonceGenerator
*/
public void setNonceGenerator(NonceGenerator nonceGenerator)
{
_nonceGenerator = nonceGenerator;
}
/**
* Configures the minimum level of encryption accepted for association
* sessions.
* <p>
* Default: no-encryption session, SHA1 MAC association
*/
public void setMinAssocSessEnc(AssociationSessionType minAssocSessEnc)
{
this._minAssocSessEnc = minAssocSessEnc;
}
/**
* Gets the preferred association / session type.
*/
public AssociationSessionType getPrefAssocSessEnc()
{
return _prefAssocSessEnc;
}
/**
* Sets the preferred association / session type.
*
* @see AssociationSessionType
*/
public void setPrefAssocSessEnc(AssociationSessionType type)
throws ServerException
{
if (! Association.isHmacSupported(type.getAssociationType()) ||
! DiffieHellmanSession.isDhSupported(type) )
throw new ServerException("Unsupported association / session type: "
+ type.getSessionType() + " : " + type.getAssociationType());
if (_minAssocSessEnc.isBetter(type) )
throw new ServerException(
"Minimum encryption settings cannot be better than the preferred");
this._prefAssocSessEnc = type;
}
/**
* Gets the expiration time (in seconds) for the generated associations
*/
public int getExpireIn()
{
return _expireIn;
}
/**
* Sets the expiration time (in seconds) for the generated associations
*/
public void setExpireIn(int _expireIn)
{
this._expireIn = _expireIn;
}
/**
* Gets the URL at the OpenID Provider where the user should be directed
* when a immediate authentication request fails.
*/
public String getUserSetupUrl()
{
return _userSetupUrl;
}
/**
* Sets the URL at the OpenID Provider where the user should be directed
* when a immediate authentication request fails.
*/
public void setUserSetupUrl(String userSetupUrl)
{
this._userSetupUrl = userSetupUrl;
}
/**
* Sets the list of parameters that the OpenID Provider will sign when
* generating authentication responses.
* <p>
* The fields in the list must be coma-separated and must not include the
* 'openid.' prefix. Fields that are required to be signed are automatically
* added by the underlying logic, so that a valid message is generated,
* regardles if they are included in the user-supplied list or not.
*/
public void setSignFields(String signFields)
{
this._signFields = signFields;
}
/**
* Gets the list of parameters that the OpenID Provider will sign when
* generating authentication responses.
* <p>
* Coma-separated list.
*/
public String getSignFields()
{
return _signFields;
}
public void setSignExtensions(String[] extensins)
{
_signExtensions = extensins;
}
public String[] getSignExtensions()
{
return _signExtensions;
}
/**
* Gets the RealmVerifier used to verify realms against return_to URLs.
*/
public RealmVerifier getRealmVerifier()
{
return _realmVerifier;
}
/**
* Sets the RealmVerifier used to verify realms against return_to URLs.
*/
public void setRealmVerifier(RealmVerifier realmVerifier)
{
this._realmVerifier = realmVerifier;
}
/**
* Gets the flag that instructs the realm verifier to enforce validation
* of the return URL agains the endpoints discovered from the RP's realm.
*/
public boolean getEnforceRpId()
{
return _realmVerifier.getEnforceRpId();
}
/**
* Sets the flag that instructs the realm verifier to enforce validation
* of the return URL agains the endpoints discovered from the RP's realm.
*/
public void setEnforceRpId(boolean enforceRpId)
{
_realmVerifier.setEnforceRpId(enforceRpId);
}
/**
* Gets OpenID Provider's endpoint URL, where it accepts OpenID
* authentication requests.
* <p>
* This is a global setting for the ServerManager; can also be set on a
* per message basis.
*
* @see #authResponse(org.openid4java.message.ParameterList, String, String, boolean, String)
*/
public String getOPEndpointUrl()
{
return _opEndpointUrl;
}
/**
* Sets the OpenID Provider's endpoint URL, where it accepts OpenID
* authentication requests.
* <p>
* This is a global setting for the ServerManager; can also be set on a
* per message basis.
*
* @see #authResponse(org.openid4java.message.ParameterList, String, String, boolean, String)
*/
public void setOPEndpointUrl(String opEndpointUrl)
{
this._opEndpointUrl = opEndpointUrl;
}
/**
* Constructs a ServerManager with default settings.
*/
public ServerManager() {
this(new RealmVerifierFactory(new YadisResolver(new HttpFetcherFactory())));
}
@Inject
public ServerManager(RealmVerifierFactory factory)
{
// initialize a default realm verifier
_realmVerifier = factory.getRealmVerifierForServer();
_realmVerifier.setEnforceRpId(false);
}
/**
* Processes a Association Request and returns a Association Response
* message, according to the request parameters and the preferences
* configured for the OpenID Provider
*
* @return AssociationResponse upon successfull association,
* or AssociationError if no association
* was established
*
*/
public Message associationResponse(ParameterList requestParams)
{
boolean isVersion2 = requestParams.hasParameter("openid.ns");
_log.info("Processing association request...");
try
{
// build request message from response params (+ integrity check)
AssociationRequest assocReq =
AssociationRequest.createAssociationRequest(requestParams);
isVersion2 = assocReq.isVersion2();
AssociationSessionType type = assocReq.getType();
// is supported / allowed ?
if (! Association.isHmacSupported(type.getAssociationType()) ||
! DiffieHellmanSession.isDhSupported(type) ||
_minAssocSessEnc.isBetter(type))
{
throw new AssociationException("Unable create association for: "
+ type.getSessionType() + " / "
+ type.getAssociationType() );
}
else // all ok, go ahead
{
Association assoc = _sharedAssociations.generate(
type.getAssociationType(), _expireIn);
_log.info("Returning shared association; handle: " + assoc.getHandle());
return AssociationResponse.createAssociationResponse(assocReq, assoc);
}
}
catch (OpenIDException e)
{
// association failed, respond accordingly
if (isVersion2)
{
_log.warn("Cannot establish association, " +
"responding with an OpenID2 association error.", e);
return AssociationError.createAssociationError(
e.getMessage(), _prefAssocSessEnc);
}
else
{
_log.warn("Error processing an OpenID1 association request: " +
e.getMessage() +
" Responding with a dummy association.", e);
try
{
// generate dummy association & no-encryption response
// for compatibility mode
Association dummyAssoc = _sharedAssociations.generate(
Association.TYPE_HMAC_SHA1, 0);
AssociationRequest dummyRequest =
AssociationRequest.createAssociationRequest(
AssociationSessionType.NO_ENCRYPTION_COMPAT_SHA1MAC);
return AssociationResponse.createAssociationResponse(
dummyRequest, dummyAssoc);
}
catch (OpenIDException ee)
{
_log.error("Error creating negative OpenID1 association response.", e);
return null;
}
}
}
}
/**
* Processes a Authentication Request received from a consumer site.
* <p>
* Uses ServerManager's global OpenID Provider endpoint URL.
*
* @return An signed positive Authentication Response if successfull,
* or an IndirectError / DirectError message.
* @see #authResponse(org.openid4java.message.ParameterList, String, String,
* boolean, String, boolean)
*/
public Message authResponse(ParameterList requestParams,
String userSelId,
String userSelClaimed,
boolean authenticatedAndApproved)
{
return authResponse(requestParams, userSelId, userSelClaimed,
authenticatedAndApproved, _opEndpointUrl, true);
}
/**
* Processes a Authentication Request received from a consumer site.
* <p>
* Uses ServerManager's global OpenID Provider endpoint URL.
*
* @return A signed positive Authentication Response if successfull,
* or an IndirectError / DirectError message.
* @see #authResponse(org.openid4java.message.AuthRequest, String, String,
* boolean, String, boolean)
*/
public Message authResponse(AuthRequest authReq,
String userSelId,
String userSelClaimed,
boolean authenticatedAndApproved)
{
return authResponse(authReq, userSelId, userSelClaimed,
authenticatedAndApproved, _opEndpointUrl, true);
}
/**
* Processes a Authentication Request received from a consumer site.
* <p>
* Uses ServerManager's global OpenID Provider endpoint URL.
*
* @return A positive Authentication Response if successfull,
* or an IndirectError / DirectError message.
* @see #authResponse(org.openid4java.message.ParameterList, String, String,
* boolean, String, boolean)
*/
public Message authResponse(ParameterList requestParams,
String userSelId,
String userSelClaimed,
boolean authenticatedAndApproved,
boolean signNow)
{
return authResponse(requestParams, userSelId, userSelClaimed,
authenticatedAndApproved, _opEndpointUrl, signNow);
}
/**
* Processes a Authentication Request received from a consumer site.
* <p>
* Uses ServerManager's global OpenID Provider endpoint URL.
*
* @return A positive Authentication Response if successfull,
* or an IndirectError / DirectError message.
* @see #authResponse(org.openid4java.message.AuthRequest, String, String,
* boolean, String, boolean)
*/
public Message authResponse(AuthRequest authReq,
String userSelId,
String userSelClaimed,
boolean authenticatedAndApproved,
boolean signNow)
{
return authResponse(authReq, userSelId, userSelClaimed,
authenticatedAndApproved, _opEndpointUrl, signNow);
}
/**
* Processes a Authentication Request received from a consumer site.
* <p>
*
* @return A signed positive Authentication Response if successfull,
* or an IndirectError / DirectError message.
* @see #authResponse(org.openid4java.message.ParameterList, String, String,
* boolean, String, boolean)
*/
public Message authResponse(ParameterList requestParams,
String userSelId,
String userSelClaimed,
boolean authenticatedAndApproved,
String opEndpoint)
{
return authResponse(requestParams, userSelId, userSelClaimed,
authenticatedAndApproved, opEndpoint, true);
}
/**
* Processes a Authentication Request received from a consumer site.
* <p>
*
* @return A signed positive Authentication Response if successfull,
* or an IndirectError / DirectError message.
* @see #authResponse(org.openid4java.message.AuthRequest, String, String,
* boolean, String, boolean)
*/
public Message authResponse(AuthRequest auhtReq,
String userSelId,
String userSelClaimed,
boolean authenticatedAndApproved,
String opEndpoint)
{
return authResponse(auhtReq, userSelId, userSelClaimed,
authenticatedAndApproved, opEndpoint, true);
}
/**
* Processes a Authentication Request received from a consumer site,
* after parsing the request parameters into a valid AuthRequest.
* <p>
*
* @return A signed positive Authentication Response if successfull,
* or an IndirectError / DirectError message.
* @see #authResponse(org.openid4java.message.AuthRequest, String, String,
* boolean, String, boolean)
*/
public Message authResponse(ParameterList requestParams,
String userSelId,
String userSelClaimed,
boolean authenticatedAndApproved,
String opEndpoint,
boolean signNow)
{
_log.info("Parsing authentication request...");
AuthRequest authReq;
boolean isVersion2 = Message.OPENID2_NS.equals(
requestParams.getParameterValue("openid.ns"));
try
{
// build request message from response params (+ integrity check)
authReq = AuthRequest.createAuthRequest(
requestParams, _realmVerifier);
return authResponse(authReq, userSelId, userSelClaimed,
authenticatedAndApproved, opEndpoint, signNow);
}
catch (MessageException e)
{
if (requestParams.hasParameter("openid.return_to"))
{
_log.error("Invalid authentication request; " +
"responding with an indirect error message.", e);
return IndirectError.createIndirectError(e,
requestParams.getParameterValue("openid.return_to"),
! isVersion2 );
}
else
{
_log.error("Invalid authentication request; " +
"responding with a direct error message.", e);
return DirectError.createDirectError( e, ! isVersion2 );
}
}
}
/**
* Processes a Authentication Request received from a consumer site.
*
* @param opEndpoint The endpoint URL where the OP accepts OpenID
* authentication requests.
* @param authReq A valid authentication request.
* @param userSelId OP-specific Identifier selected by the user at
* the OpenID Provider; if present it will override
* the one received in the authentication request.
* @param userSelClaimed Claimed Identifier selected by the user at
* the OpenID Provider; if present it will override
* the one received in the authentication request.
* @param authenticatedAndApproved Flag indicating that the OP has
* authenticated the user and the user
* has approved the authentication
* transaction
* @param signNow If true, the returned AuthSuccess will be signed.
* If false, the signature will not be computed and
* set - this will have to be performed later,
* using #sign(org.openid4java.message.Message).
*
* @return <ul><li> AuthSuccess, if authenticatedAndApproved
* <li> AuthFailure (negative response) if either
* of authenticatedAndApproved is false;
* <li> A IndirectError or DirectError message
* if the authentication could not be performed, or
* <li> Null if there was no return_to parameter
* specified in the AuthRequest.</ul>
*/
public Message authResponse(AuthRequest authReq,
String userSelId,
String userSelClaimed,
boolean authenticatedAndApproved,
String opEndpoint,
boolean signNow)
{
_log.info("Processing authentication request...");
boolean isVersion2 = authReq.isVersion2();
if (authReq.getReturnTo() == null)
{
_log.error("No return_to in the received (valid) auth request; "
+ "returning null auth response.");
return null;
}
try
{
if (authenticatedAndApproved) // positive response
{
try
{
new URL(opEndpoint);
}
catch (MalformedURLException e)
{
String errMsg = "Invalid OP-endpoint configured; " +
"cannot issue authentication responses." + opEndpoint;
_log.error(errMsg, e);
return DirectError.createDirectError(
new ServerException(errMsg, e), isVersion2);
}
String id;
String claimed;
if (AuthRequest.SELECT_ID.equals(authReq.getIdentity()))
{
id = userSelId;
claimed = userSelClaimed;
}
else
{
id = userSelId != null ? userSelId : authReq.getIdentity();
claimed = userSelClaimed != null ? userSelClaimed :
authReq.getClaimed();
}
if (id == null)
throw new ServerException(
"No identifier provided by the authentication request " +
"or by the OpenID Provider");
if (DEBUG) _log.debug("Using ClaimedID: " + claimed +
" OP-specific ID: " + id);
Association assoc = null;
String handle = authReq.getHandle();
String invalidateHandle = null;
if (handle != null)
{
assoc = _sharedAssociations.load(handle);
if (assoc == null)
{
_log.info("Invalidating handle: " + handle);
invalidateHandle = handle;
}
else
_log.info("Loaded shared association; handle: " + handle);
}
if (assoc == null)
{
assoc = _privateAssociations.generate(
_prefAssocSessEnc.getAssociationType(),
_expireIn);
_log.info("Generated private association; handle: "
+ assoc.getHandle());
}
AuthSuccess response = AuthSuccess.createAuthSuccess(
opEndpoint, claimed, id, !isVersion2,
authReq.getReturnTo(),
isVersion2 ? _nonceGenerator.next() : null,
invalidateHandle, assoc, false);
if (_signFields != null)
response.setSignFields(_signFields);
if (_signExtensions != null)
response.setSignExtensions(_signExtensions);
if (signNow)
response.setSignature(assoc.sign(response.getSignedText()));
_log.info("Returning positive assertion for " +
response.getReturnTo());
return response;
}
else // negative response
{
if (authReq.isImmediate())
{
_log.error("Responding with immediate authentication " +
"failure to " + authReq.getReturnTo());
authReq.setImmediate(false);
String userSetupUrl = _userSetupUrl == null ? opEndpoint : _userSetupUrl;
userSetupUrl += (userSetupUrl.contains("?") ? "&" : "?") + authReq.wwwFormEncoding();
return AuthImmediateFailure.createAuthImmediateFailure(
userSetupUrl, authReq.getReturnTo(), ! isVersion2);
}
else
{
_log.error("Responding with authentication failure to " +
authReq.getReturnTo());
return new AuthFailure(! isVersion2, authReq.getReturnTo());
}
}
}
catch (OpenIDException e)
{
if (authReq.hasParameter("openid.return_to"))
{
_log.error("Error processing authentication request; " +
"responding with an indirect error message.", e);
return IndirectError.createIndirectError(e,
authReq.getReturnTo(),
! isVersion2 );
}
else
{
_log.error("Error processing authentication request; " +
"responding with a direct error message.", e);
return DirectError.createDirectError( e, ! isVersion2 );
}
}
}
/**
* Signs an AuthSuccess message, using the association identified by the
* handle specified within the message.
*
* @param authSuccess The Authentication Success message to be signed.
*
* @throws ServerException If the Association corresponding to the handle
* in the @authSuccess cannot be retrieved from
* the store.
* @throws AssociationException If the signature cannot be computed.
*
*/
public void sign(AuthSuccess authSuccess)
throws ServerException, AssociationException
{
String handle = authSuccess.getHandle();
// try shared associations first, then private
Association assoc = _sharedAssociations.load(handle);
if (assoc == null)
assoc = _privateAssociations.load(handle);
if (assoc == null) throw new ServerException(
"No association found for handle: " + handle);
authSuccess.setSignature(assoc.sign(authSuccess.getSignedText()));
}
/**
* Responds to a verification request from the consumer.
*
* @param requestParams ParameterList containing the parameters received
* in a verification request from a consumer site.
* @return VerificationResponse to be sent back to the
* consumer site.
*/
public Message verify(ParameterList requestParams)
{
_log.info("Processing verification request...");
boolean isVersion2 = true;
try
{
// build request message from response params (+ ntegrity check)
VerifyRequest vrfyReq = VerifyRequest.createVerifyRequest(requestParams);
isVersion2 = vrfyReq.isVersion2();
String handle = vrfyReq.getHandle();
boolean verified = false;
Association assoc = _privateAssociations.load(handle);
if (_checkPrivateSharedAssociations && _sharedAssociations.load(handle) != null)
{
_log.warn("association for handle: " + handle + " expected to be private " +
"but was found in shared association store, denying direct verification request; " +
"please configure different association store/instances for private vs shared associations");
}
else if (assoc != null)
{
// verify the signature
_log.info("Loaded private association; handle: " + handle);
verified = assoc.verifySignature(
vrfyReq.getSignedText(),
vrfyReq.getSignature());
// remove the association so that the request
// cannot be verified more than once
_privateAssociations.remove(handle);
}
VerifyResponse vrfyResp =
VerifyResponse.createVerifyResponse(! vrfyReq.isVersion2());
vrfyResp.setSignatureVerified(verified);
if (verified)
{
String invalidateHandle = vrfyReq.getInvalidateHandle();
if (invalidateHandle != null &&
_sharedAssociations.load(invalidateHandle) == null) {
_log.info("Confirming shared association invalidate handle: "
+ invalidateHandle);
vrfyResp.setInvalidateHandle(invalidateHandle);
}
}
else
_log.error("Signature verification failed, handle: " + handle);
_log.info("Responding with " + (verified? "positive" : "negative")
+ " verification response");
return vrfyResp;
}
catch (OpenIDException e)
{
_log.error("Error processing verification request; " +
"responding with verification error.", e);
return DirectError.createDirectError(e, ! isVersion2);
}
}
} |
package org.traccar.protocol;
import java.nio.ByteOrder;
import org.jboss.netty.buffer.ChannelBuffers;
import static org.junit.Assert.assertNull;
import org.junit.Test;
import org.traccar.helper.ChannelBufferTools;
import static org.traccar.helper.DecoderVerifier.verify;
import org.traccar.helper.TestIdentityManager;
public class RitiProtocolDecoderTest extends ProtocolDecoderTest {
@Test
public void testDecode() throws Exception {
RitiProtocolDecoder decoder = new RitiProtocolDecoder(new RitiProtocol());
verify(decoder.decode(null, null, ChannelBuffers.wrappedBuffer(ByteOrder.LITTLE_ENDIAN, ChannelBufferTools.convertHexString(
"3b28a2a2056315316d4000008100000000000000005f710000244750524d432c3138303535332e3030302c412c353532342e383437312c4e2c30313133342e313837382c452c302e30302c2c3032313231332c2c2c412a37340d0a00000000000000000000000000000000040404"))));
verify(decoder.decode(null, null, ChannelBuffers.wrappedBuffer(ByteOrder.LITTLE_ENDIAN, ChannelBufferTools.convertHexString(
"3b2864a3056300006d40000003000000000000000000000000244750524d432c3231313734332e3030302c412c313335372e333637352c4e2c31303033362e363939322c452c302e30302c2c3031303931342c2c2c412a37380d0a00000000000000000000000000000000040404"))));
}
} |
package org.uct.cs.simplify;
import org.apache.commons.cli.*;
import org.uct.cs.simplify.img.BluePrintGenerator;
import org.uct.cs.simplify.ply.header.PLYHeader;
import org.uct.cs.simplify.ply.reader.ImprovedPLYReader;
import org.uct.cs.simplify.util.Timer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class BlueprintifyMain
{
private static final String format = "png";
public static void main(String[] args)
{
CommandLine cmd = parseArgs(args);
try (Timer ignored = new Timer("Elapsed:"))
{
// process arguments
int resolution = (cmd.hasOption("resolution") ? (int) cmd.getParsedOptionValue("resolution") : 1024);
float alphamod = (cmd.hasOption("alphamod") ? (float) cmd.getParsedOptionValue("alphamod") : 0.1f);
String filename = cmd.getOptionValue("filename");
String outputDirectory = cmd.getOptionValue("output");
// process output dir
File outputDir = new File(new File(outputDirectory).getCanonicalPath());
if (!outputDir.exists() && !outputDir.mkdirs())
throw new IOException("Could not create output directory " + outputDir);
File inputFile = new File(filename);
PLYHeader header = new PLYHeader(inputFile);
ImprovedPLYReader r = new ImprovedPLYReader(header, inputFile);
// process input model to find output name
File outputFile = new File(outputDir, inputFile.getName() + "." + format);
BufferedImage bi = BluePrintGenerator.CreateImage(r, resolution, alphamod);
ImageIO.write(bi, format, outputFile);
System.out.println("Saved blueprint to " + outputFile);
}
catch (ParseException | IOException e)
{
e.printStackTrace();
}
}
private static CommandLine parseArgs(String[] args)
{
CommandLineParser clp = new BasicParser();
Options options = new Options();
Option o1 = new Option("f", "filename", true, "Path to PLY model to process");
o1.setRequired(true);
options.addOption(o1);
Option o2 = new Option("o", "output", true, "Destination directory of blueprint");
o2.setRequired(true);
options.addOption(o2);
Option o3 = new Option("r", "resolution", true, "Resolution of image to output (default 1024)");
o3.setType(Short.class);
options.addOption(o3);
Option o4 = new Option("a", "alphamod", true, "Translucency of applied pixels (default 0.1f)");
o4.setType(Float.class);
options.addOption(o4);
try
{
return clp.parse(options, args);
}
catch (ParseException e)
{
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("BlueprintifyPLY --filename <path> --output <path>", options);
System.exit(1);
return null;
}
}
} |
package org.uefiide.wizards;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.dialogs.WizardNewProjectCreationPage;
import org.uefiide.projectmanip.ProjectSettingsManager;
public class NewProjectWizard extends Wizard implements INewWizard {
private WizardNewProjectCreationPage edk2RootSelectionPage;
private WizardSelectModulesPage wizardSelectModulesPage;
public NewProjectWizard() {
setWindowTitle("New EDK2 Project");
}
@Override
public void init(IWorkbench workbench, IStructuredSelection selection) {
}
@Override
public boolean performFinish() {
System.out.println(edk2RootSelectionPage.getLocationPath().toString());
System.out.println(edk2RootSelectionPage.getProjectName());
IProject cdtProject = ResourcesPlugin.getWorkspace().getRoot().getProject("MyCProject");
ProjectSettingsManager manager = new ProjectSettingsManager(cdtProject);
List<String> includePaths = new ArrayList<>();
includePaths.add("/home/felipe/Desktop/dummy_include_path");
manager.setIncludePaths(includePaths);
for(String p : manager.getIncludePaths()) {
System.out.println(p);
}
return false;
}
@Override
public void addPages() {
super.addPages();
edk2RootSelectionPage = new WizardNewProjectCreationPage("EDK2 root selection page");
edk2RootSelectionPage.setTitle("EDK2 root selection");
edk2RootSelectionPage.setDescription("Select the path to the EDK2 root");
addPage(edk2RootSelectionPage);
wizardSelectModulesPage = new WizardSelectModulesPage("EDK Modules selection page");
wizardSelectModulesPage.setTitle("EDK Modules selection page");
wizardSelectModulesPage.setDescription("Select the EDK2 modules that will be used in the new project");
addPage(wizardSelectModulesPage);
}
} |
package org.usfirst.frc.team1306.robot;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Robot extends IterativeRobot {
Command autonomousCommand;
SendableChooser chooser;
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
chooser = new SendableChooser();
// chooser.addObject("My Auto", new MyAutoCommand());
SmartDashboard.putData("Auto mode", chooser);
}
/**
* This function is called once each time the robot enters Disabled mode.
* You can use it to reset any subsystem information you want to clear when
* the robot is disabled.
*/
public void disabledInit(){
}
public void disabledPeriodic() {
Scheduler.getInstance().run();
}
/**
* This autonomous (along with the chooser code above) shows how to select between different autonomous modes
* using the dashboard. The sendable chooser code works with the Java SmartDashboard. If you prefer the LabVIEW
* Dashboard, remove all of the chooser code and uncomment the getString code to get the auto name from the text box
* below the Gyro
*
* You can add additional auto modes by adding additional commands to the chooser code above (like the commented example)
* or additional comparisons to the switch structure below with additional strings & commands.
*/
public void autonomousInit() {
autonomousCommand = (Command) chooser.getSelected();
/* String autoSelected = SmartDashboard.getString("Auto Selector", "Default");
switch(autoSelected) {
case "My Auto":
autonomousCommand = new MyAutoCommand();
break;
case "Default Auto":
default:
autonomousCommand = new ExampleCommand();
break;
} */
// schedule the autonomous command (example)
if (autonomousCommand != null) autonomousCommand.start();
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
Scheduler.getInstance().run();
}
public void teleopInit() {
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
if (autonomousCommand != null) autonomousCommand.cancel();
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
Scheduler.getInstance().run();
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
LiveWindow.run();
}
} |
package org.usfirst.frc.team3335.robot;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.usfirst.frc.team3335.robot.commands.ExampleCommand;
import org.usfirst.frc.team3335.robot.subsystems.ExampleSubsystem;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Robot extends IterativeRobot {
public static final ExampleSubsystem exampleSubsystem = new ExampleSubsystem();
public static OI oi;
Command autonomousCommand;
SendableChooser<Command> chooser = new SendableChooser<>();
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
@Override
public void robotInit() {
oi = new OI();
chooser.addDefault("Default Auto", new ExampleCommand());
// chooser.addObject("My Auto", new MyAutoCommand());
SmartDashboard.putData("Auto mode", chooser);
}
/**
* This function is called once each time the robot enters Disabled mode.
* You can use it to reset any subsystem information you want to clear when
* the robot is disabled.
*/
@Override
public void disabledInit() {
}
@Override
public void disabledPeriodic() {
Scheduler.getInstance().run();
}
/**
* This autonomous (along with the chooser code above) shows how to select
* between different autonomous modes using the dashboard. The sendable
* chooser code works with the Java SmartDashboard. If you prefer the
* LabVIEW Dashboard, remove all of the chooser code and uncomment the
* getString code to get the auto name from the text box below the Gyro
*
* You can add additional auto modes by adding additional commands to the
* chooser code above (like the commented example) or additional comparisons
* to the switch structure below with additional strings & commands.
*/
@Override
public void autonomousInit() {
autonomousCommand = chooser.getSelected();
/*
* String autoSelected = SmartDashboard.getString("Auto Selector",
* "Default"); switch(autoSelected) { case "My Auto": autonomousCommand
* = new MyAutoCommand(); break; case "Default Auto": default:
* autonomousCommand = new ExampleCommand(); break; }
*/
// schedule the autonomous command (example)
if (autonomousCommand != null)
autonomousCommand.start();
}
/**
* This function is called periodically during autonomous
*/
@Override
public void autonomousPeriodic() {
Scheduler.getInstance().run();
}
@Override
public void teleopInit() {
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
if (autonomousCommand != null)
autonomousCommand.cancel();
}
/**
* This function is called periodically during operator control
*/
@Override
public void teleopPeriodic() {
Scheduler.getInstance().run();
}
/**
* This function is called periodically during test mode
*/
@Override
public void testPeriodic() {
LiveWindow.run();
}
} |
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
// FILE NAME: Autonomous.java (Team 339 - Kilroy)
// ABSTRACT:
// This file is where almost all code for Kilroy will be
// written. All of these functions are functions that should
// override methods in the base class (IterativeRobot). The
// functions are as follows:
// Init() - Initialization code for teleop mode
// should go here. Will be called each time the robot enters
// teleop mode.
// Periodic() - Periodic code for teleop mode should
// go here. Will be called periodically at a regular rate while
// the robot is in teleop mode.
// Team 339.
package org.usfirst.frc.team339.robot;
import com.ctre.CANTalon;
import com.ctre.CANTalon.FeedbackDevice;
import com.ctre.CANTalon.TalonControlMode;
import org.usfirst.frc.team339.Hardware.Hardware;
import org.usfirst.frc.team339.Utils.Drive;
import org.usfirst.frc.team339.Utils.Shooter;
import org.usfirst.frc.team339.Utils.pidTuning.CanTalonPIDTuner;
import org.usfirst.frc.team339.Utils.pidTuning.SmartDashboardPIDTunerDevice;
import edu.wpi.cscore.VideoCamera;
import edu.wpi.first.wpilibj.Relay.Value;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* This class contains all of the user code for the Autonomous part of the
* match, namely, the Init and Periodic code
*
* @author Nathanial Lydick
* @written Jan 13, 2015
*/
public class Teleop
{
/**
* User Initialization code for teleop mode should go here. Will be called
* once when the robot enters teleop mode.
*
* @author Nathanial Lydick
* @written Jan 13, 2015
*/
public static void init ()
{
// initialize all encoders here
Hardware.leftFrontEncoder.reset();
Hardware.rightFrontEncoder.reset();
Hardware.rightRearEncoder.reset();
Hardware.leftRearEncoder.reset();
// initialize all motors here
Hardware.leftRearMotor.set(0.0);
Hardware.rightRearMotor.set(0.0);
Hardware.rightFrontMotor.set(0.0);
Hardware.leftFrontMotor.set(0.0);
Hardware.newClimberMotor.set(0.0);
Hardware.gearIntakeMotor.set(0.0);
// Solenoid Init
Hardware.gearIntakeSolenoid.setReverse(false);
// Servo init
// Hardware.cameraservoX.setAngle(HIGHER_CAMERASERVO_POSITIONX);
// Hardware.cameraservoY.setAngle(HIGHER_CAMERASERVO_POSITIONY);
// gimbal motors
// Hardware.gimbalMotor
// .setFeedbackDevice(FeedbackDevice.CtreMagEncoder_Relative);
// Hardware.gimbalMotor.setEncPosition(0);
// mecanum
Hardware.mecanumDrive
.setFirstGearPercentage(
Robot.KILROY_XVIII_FIRST_GEAR_PERCENTAGE);
Hardware.tankDrive
.setGearPercentage(1,
Robot.KILROY_XVIII_FIRST_GEAR_PERCENTAGE);
if (Hardware.isRunningOnKilroyXVIII == true)
{
// tank drive values
Hardware.tankDrive.setGear(2);
// auto drive values
Hardware.autoDrive.setDriveCorrection(.3);
Hardware.autoDrive.setEncoderSlack(1);
// mecanum values
Hardware.mecanumDrive.setGear(1);
}
else
// kilroy XVII
{
Hardware.autoDrive.setDebugStatus(false);
// tank drive values
Hardware.tankDrive.setGear(1);
// auto drive values
Hardware.autoDrive.setDriveCorrection(.3);
Hardware.autoDrive.setEncoderSlack(1);
}
// PID smartdashboard
// if (tunePIDLoop == true)
// SmartDashboard.putNumber("P", Robot.shooterP);
// SmartDashboard.putNumber("I", Robot.shooterI);
// SmartDashboard.putNumber("D", Robot.shooterD);
// SmartDashboard.putNumber("Setpoint", tempSetpoint);
// // SmartDashboard.putNumber("Err",
// // Hardware.shooterMotor.getError());
// Hardware.shooterMotor.changeControlMode(TalonControlMode.Speed);
// // put back in once finished testing!!!
// Hardware.shooterMotor.configPeakOutputVoltage(12f, 0f);
// Hardware.shooterMotor.configNominalOutputVoltage(0f, 0f);
// Hardware.shooterMotor
// .setFeedbackDevice(FeedbackDevice.CtreMagEncoder_Relative);
// Hardware.shooterMotor.configEncoderCodesPerRev(1024);
// Hardware.shooterMotor.setPID(shooterP, shooterI, shooterD);
// Hardware.shooterMotor.setSetpoint(0.0);
// Hardware.shooterMotor.reverseSensor(true);
// testingTalon.setProfile(0);
CanTuner.setupMotorController(FeedbackDevice.QuadEncoder,
TalonControlMode.Speed, 1024, false);
testingTalon.setPID(0.0, 0.0, 0.0);
testingTalon.setSetpoint(0.0);
// put stuff on smartdashboard
SmartDashboard.putNumber("DB/Slider 0", 0);
SmartDashboard.putNumber("DB/Slider 1", 0);
SmartDashboard.putNumber("DB/Slider 2", 0);
SmartDashboard.putNumber("DB/Slider 3", 0);
// thread1.start();
// System.out.println("Got here 1");
// System.out.println("Thread 1 'return' : " + thread1.valueForTeleop);
// System.out
// .println("Thread 1 State Pre Join: " + thread1.getState());
// thread1.join();
// System.out
// .println("Thread 1 State Post Join: " + thread1.getState());
// thread2.start();
// Hardware.driveGyro.calibrate();
// Hardware.driveGyro.reset();
Hardware.transmission.setGear(0);
} // end Init
static double tempSetpoint = 0.0;
static CANTalon testingTalon = new CANTalon(12);
private static CanTalonPIDTuner CanTuner = new CanTalonPIDTuner(
testingTalon, 0);
private static SmartDashboardPIDTunerDevice PIDTuner = new SmartDashboardPIDTunerDevice(
CanTuner);
// tune pid loop
/**
* User Periodic code for teleop mode should go here. Will be called
* periodically at a regular rate while the robot is in teleop mode.
*
* @author Nathanial Lydick
* @written Jan 13, 2015
*/
public static void periodic ()
{
double testDashboard = 0.0;
double testDashboard2 = 0.0;
testDashboard = SmartDashboard.getNumber("DB/Slider 0", 0.0);
testDashboard2 = SmartDashboard.getNumber("DB/Slider 1", 0.0);
// ADD IN???
// System.out.println(testDashboard);
// System.out.println(testDashboard);
// System.out.println(testDashboard);
// print values from hardware items
printStatements();
// tune pid loop
if (tunePIDLoop == true)
{
Robot.shooterP = SmartDashboard.getNumber("P", Robot.shooterP);
Robot.shooterI = SmartDashboard.getNumber("I", Robot.shooterI);
Robot.shooterD = SmartDashboard.getNumber("D", Robot.shooterD);
tempSetpoint = SmartDashboard.getNumber("Setpoint",
tempSetpoint);
// SmartDashboard.putNumber("Err",
// Hardware.shooterMotor.getError());
// Hardware.shooterMotor.setPID(Robot.shooterP, Robot.shooterI,
// Robot.shooterD);
// Hardware.shooterMotor
// .set(tempSetpoint);
}
// Hardware.shooterMotor
// .set(tempSetpoint);
// printStatements();
// printStatements();
// previousFireButton = Hardware.leftDriver.getTrigger();
// if (fireCount > 0)
// if (Hardware.shooter.fire())
// fireCount--;
// else if (preparingToFire == false)
// Hardware.shooter.stopFlywheelMotor();
/*
* System.out.println("Firecount: " + fireCount);
*
* System.out.println( "Flywheel speed: " +
* Hardware.shooterMotor.getSpeed());
*/
if (tunePIDLoop == true)
{
PIDTuner.update();
System.out.println("Error: " + testingTalon.getError());
System.out.println("Setpoint: " + testingTalon.getSetpoint());
System.out.println("Velocity: " + testingTalon.getSpeed());
System.out.println("P, I, D: " + testingTalon.getP() + ", "
+ testingTalon.getI() + ", " + testingTalon.getD());
}
// Hardware.shooterMotor
// .set(tempSetpoint);
// gear servo set angles
// Hardware.gearServo.setAngle(200);
// Hardware.gearServo.getAngle();
// TODO delete this shortcut
// Hardware.leftRearTest.watchJoystick(Hardware.leftOperator.getY());
// Hardware.leftFrontTest.watchJoystick(Hardware.leftOperator.getY());
// Hardware.rightRearTest.watchJoystick(Hardware.rightOperator.getY());
// Hardware.rightFrontTest
// .watchJoystick(Hardware.rightOperator.getY());
// System.out.println("Left Rear Amps: " +
// Hardware.pdp.getCurrent(14));
// System.out.println("Left Front Amps: " +
// Hardware.pdp.getCurrent(12));
// System.out.println("Right Rear Amps: " +
// Hardware.pdp.getCurrent(15));
// System.out.println("Right Front Amps: " +
// Hardware.pdp.getCurrent(13));
// OPERATOR CONTROLS
if (Hardware.ringlightSwitch.isOnCheckNow())
{
Hardware.ringlightRelay.set(Value.kOn);
}
else
{
Hardware.ringlightRelay.set(Value.kOff);
}
// @ANE Updated motor names
// rightOperator stuffs
// If the operator is pressing right button 10
// @ANE add back in
if (Hardware.rightOperator.getTrigger() == true
/* Hardware.rightOperator.getRawButton(10) */)
{
// Climb climb climb!
Hardware.newClimberMotor.set(climbingSpeed);
// System.out.println("climber speed = "
// + Hardware.newClimberMotor.getSpeed());
}
else if (Hardware.rightOperator.getRawButton(6) == true
&& Hardware.rightOperator.getRawButton(7) == true)
{
Hardware.newClimberMotor.set(reverseClimbingSpeed);
}
else// They're not pressing it
{
Hardware.newClimberMotor.set(0.0);// STOP THE MOTOR
}
// Calibration code
// Hardware.newClimberMotor.set(Hardware.rightOperator.getY());
// @ANE Gear Intake Mechanism
// should set rightOperator button 3 to reverse gearintake,
// sets rightOperator button 2 to run intake as long as nothing is
// setting off the photoswitch, if something is setting off the
// photoswitch and the trigger is pressed then set solenoid to the
// "down" position and run the motors in reverse at half speed.
if (Hardware.rightOperator.getRawButton(3) == true)
{
Hardware.gearIntakeMotor.set(-1.0);
}
else if ((Hardware.photoSwitch.isOn() == false)
&& (Hardware.rightOperator.getRawButton(2) == true))
{
Hardware.gearIntakeMotor.set(1.0);
}
else if (Hardware.photoSwitch.isOn() == true)
{
Hardware.gearIntakeMotor.set(0.0);
System.out.println("Something in gear intake!?");
}
if (Hardware.leftOperator.getTrigger() == true)
{
Hardware.gearIntakeSolenoid.setReverse(true);
// Hardware.gearIntakeMotor.set(-.5);
}
else
{
Hardware.gearIntakeSolenoid.setReverse(false);
}
// TESTING SHOOTER
if (Hardware.rightOperator.getTrigger() == true)
{
// Hardware.shooter.turnToGoalRaw();
// Hardware.shooter.fire(-200 * Hardware.rightOperator.getZ());
// System.out.println(
// Hardware.shooterMotor.set(
// Hardware.shooter.calculateRPMToMakeGoal(12.25) / 2.0);
}
else if (Hardware.leftOperator.getTrigger() == true)
{
// Hardware.shooter.fire(-200 * Hardware.rightOperator.getZ());
// Hardware.shooter.loadBalls();
}
else
{
// Hardware.shooter.stopFlywheelMotor();
}
// END SHOOTER TESTING
// TURRET OVERRIDE
if (Hardware.rightOperator.getRawButton(2) == true
&& Math.abs(Hardware.rightOperator.getX()) > .2)
{
if (Hardware.rightOperator.getX() > 0)
{
// Hardware.shooter.turnGimbalSlow(1);
}
else
{
// Hardware.shooter
// .turnGimbalSlow(-1);
}
}
else if (isTurningGimbal == false && isTurningToGoal == false)
{
// Hardware.shooter.stopGimbal();
}
// END TURRET OVERRIDE
// SET TURRET TO 0
if (Hardware.rightOperator.getRawButton(5) == true)
isTurningGimbal = true;
if (isTurningGimbal == true
|| turnValue == Shooter.turnReturn.WORKING)
{
// turnValue = Hardware.shooter.turnToBearing(0);
isTurningGimbal = false;
}
// END SET TURRET TO 0
// ELEVATOR OVERRIDE
// if (Hardware.rightOperator.getRawButton(3) == true)
// Hardware.shooter.loadBalls();
// else if (Hardware.rightOperator.getRawButton(4) == true)
// Hardware.shooter.reverseLoader();
// else if (Hardware.leftOperator.getRawButton(3) == false)
// Hardware.shooter.stopLoader();
// END ELEVATOR OVERRIDE
// leftOperator stuffs
// ALIGN TURRET
if (Hardware.leftOperator.getRawButton(4) == true)
isTurningToGoal = true;
if (isTurningToGoal == true)
{
// turnToGoalValue = Hardware.shooter.turnToGoal();
// isTurningToGoal = !Hardware.shooter.turnToGoalRaw();
}
// @ANE removed for sanity's sake
// INTAKE CONTROLS
// if (Hardware.leftOperator.getRawButton(2) == true)
// Hardware.intake.startIntake();
// else if (Hardware.leftOperator.getRawButton(3) == true)
// Hardware.intake.reverseIntake();
// else if (Hardware.rightOperator.getRawButton(3) == false)
// Hardware.intake.stopIntake();
// END INTAKE CONTROLS
// OLD CLIMBER CODE
// if (Hardware.rightOperator.getRawButton(10))
// Hardware.climberMotor.set(-1);
// else
// Hardware.climberMotor.set(0);
// END CLIMBER
// CAMERA CODE
if (Hardware.rightOperator.getRawButton(11))
{
Hardware.testingProcessor.setCameraSettings(0,
VideoCamera.WhiteBalance.kFixedIndoor, 50);
}
else if (Hardware.rightOperator.getRawButton(10))
{
Hardware.testingProcessor.setDefaultCameraSettings();
}
Hardware.axisCamera
.takeSinglePicture(Hardware.leftOperator.getRawButton(8)
|| Hardware.rightOperator.getRawButton(8)
|| Hardware.leftOperator.getRawButton(11));
// Driving code
if (isTestingDrive == false)
{
Hardware.transmission.drive(Hardware.leftDriver);
}
if (Hardware.leftDriver.getRawButton(9) == true)
{
isTestingDrive = true;
}
if (isTestingDrive == true)
{
isTestingDrive = !Hardware.newDrive.driveToGear(.25);
if (Hardware.leftDriver.getRawButton(10) == true)
{
isTestingDrive = false;
}
}
}
// end
// Periodic
private static Drive.AlignReturnType alignValue = Drive.AlignReturnType.MISALIGNED;
private static Shooter.turnReturn turnValue = Shooter.turnReturn.SUCCESS;
private static boolean isTurningToGoal = false;
private static double rotationValue = 0.0;
private static boolean isTurningGimbal = false;
private static boolean isTestingCamera = false;
private static boolean isTestingDrive = false;
/**
* stores print statements for future use in the print "bank", statements
* are commented out when not in use, when you write a new print statement,
* "deposit" the statement in the correct "bank" do not "withdraw"
* statements, unless directed to.
*
* NOTE: Keep the groupings below, which coorespond in number and order as
* the hardware declarations in the HARDWARE class
*
* @author Ashley Espeland
* @written 1/28/16
*
* Edited by Ryan McGee Also Edited by Josef Liebl
*
*/
public static void printStatements ()
{
// Hardware.imageProcessor.processImage();
// if (Hardware.imageProcessor.getLargestBlob() != null)
// System.out.println("Camera: " + Hardware.imageProcessor
// .getLargestBlob().center_mass_x);
// Motor controllers
// prints value of the motors
// System.out.println("Delay Pot: " + Hardware.delayPot.get(0, 5));
// System.out.println("Left Front Motor Controller: " +
// Hardware.leftFrontMotor.get());
// System.out.println("Right Rear Motor Controller: " +
// Hardware.rightRearMotor.get());
// System.out.println("Left Rear Motor Controller: " +
// Hardware.leftRearMotor.get());
// System.out.println("Right Front Motor Controller: "
// + Hardware.rightFrontMotor.get());
// System.out.println("Flywheel thingy thing: "
// + Hardware.shooter.calculateRPMToMakeGoal(9.25) * .5);
// System.out.println("Flywheel thingy thing speed really: "
// + Hardware.shooterMotor.get());
// System.out.println(Hardware.backupOrFireOrHopper.isOn());
// System.out
// .println("Flywheel Motor: " + Hardware.shooterMotor.get());
// System.out.println("Intake Motor: " + Hardware.intakeMotor.get());
// if (Hardware.rightOperator.getRawButton(11)) {
// Hardware.elevatorMotor.setSpeed(1);
// System.out.println("Elevator Motor: " +
// Hardware.elevatorMotor.get());
// System.out.println("Turret Spark: " + Hardware.gimbalMotor.get());
// CAN items
// prints value of the CAN controllers
// Hardware.CAN.printAllPDPChannels();
// Relay
// prints value of the relay states
// if (Hardware.ringlightSwitch.isOnCheckNow())
// System.out.println("Ring light relay is On");
// else if (!Hardware.ringlightSwitch.isOnCheckNow())
// System.out.println("Ring light relay is Off");
// Digital Inputs
// Switches
// prints state of switches
// System.out.println("Gear Limit Switch: "
// + Hardware.gearLimitSwitch.isOn());
// System.out.println("Backup or fire: " +
// Hardware.backupOrFireOrHopper.isOn());
// System.out.println("Enable Auto: " +
// Hardware.enableAutonomous.isOn());
// System.out.println(
// "Path Selector: " + Hardware.pathSelector.getPosition());
// System.out.println(
// "Base Line Path: " + Hardware.autoBaseLinePath.isOn());
// System.out
// .println("Side Gear Path: " + Hardware.sideGearPath.isOn());
System.out.println("UltraSonic distance from bumper: "
+ Hardware.ultraSonic.getDistanceFromNearestBumper());
// System.out.println("Right UltraSonic refined distance: "
// + Hardware.ultraSonic.getRefinedDistanceValue());
// System.out.println("Right UltraSonic raw distance: "
// + Hardware.ultraSonic.getValue());
// System.out.println("IR 1: " + Hardware.gearSensor1.isOn());
// System.out.println("IR 2: " + Hardware.gearSensor2.isOn());
// Encoders
// prints the distance from the encoders
// System.out.println("Right Front Encoder: " +
// Hardware.rightFrontEncoder.get());
// System.out.println("Right Front Distance: " +
// Hardware.autoDrive.getRightFrontEncoderDistance());
// System.out.println("Right Rear Encoder: " +
// Hardware.rightRearEncoder.get());
// System.out.println("Right Rear Encoder Distance: " +
// Hardware.autoDrive.getRightRearEncoderDistance());
// System.out.println("Left Front Encoder: " +
// Hardware.leftFrontEncoder.get());
// System.out.println("Left Front Encoder Distance: " +
// Hardware.autoDrive.getLeftFrontEncoderDistance());
// System.out.println("Left Rear Encoder: " +
// Hardware.leftRearEncoder.get());
// System.out.println("Left Rear Encoder Distance: " +
// Hardware.autoDrive.getLeftRearEncoderDistance());
// Hardware.rightFrontEncoder.get());
// System.out.println("Right Front Encoder Distance: " +
// Hardware.autoDrive.getRightRearEncoderDistance());
// System.out.println("Right Rear Encoder: " +
// Hardware.rightRearEncoder.get());
// System.out.println("Right Rear Encoder Distance: " +
// Hardware.autoDrive.getRightRearEncoderDistance());
// System.out.println("Left Front Encoder: " +
// Hardware.leftFrontEncoder.get());
// System.out.println("Left Front Encoder Distance: " +
// Hardware.autoDrive.getLeftFrontEncoderDistance());
// System.out.println("Left Rear Encoder: " +
// Hardware.leftRearEncoder.get());
// System.out.println("Left Rear Encoder Distance: " +
// Hardware.autoDrive.getLeftFrontEncoderDistance());
// Red Light/IR Sensors
// prints the state of the sensor
// System.out.println("Ball IR: " + Hardware.ballLoaderSensor.isOn());
// Pneumatics
// Compressor
// prints information on the compressor
// There isn't one at the moment
// Solenoids
// prints the state of solenoids
// There are none at the moment
// That seems familiar...
// Analogs
// Servos
// System.out.println(
// "camera servo Y" + Hardware.cameraservoY.getAngle());
// System.out.println(
// "camera servo X" + Hardware.cameraservoX.getAngle());
// GYRO
// System.out.println("Gyro: " + Hardware.driveGyro.getAngle());
// System.out.println(
// "Init Gyro Val: " + Hardware.driveGyro.getRate());
// System.out.println(
// "Gyro Is Connected: " + Hardware.driveGyro.isConnected());
// System.out.println("Ultrasonic = "
// + Hardware.ultraSonic.getRefinedDistanceValue());
// System.out.println("Ultrasonic = "
// + Hardware.ultraSonic2.getRefinedDistanceValue());
// System.out.println("Ultrasonic refined: "
// + Hardware.ultraSonic.getRefinedDistanceValue());
// System.out.println("Delay Pot: " + Hardware.delayPot.get());
// pots
// where the pot is turned to
// System.out.println("Delay Pot Degrees" + Hardware.delayPot.get());
// Connection Items
// Cameras
// prints any camera information required
// Hardware.testingProcessor.processImage();
// if (Hardware.testingProcessor.getParticleReports().length > 1)
// System.out.println("Blob 1: "
// + Hardware.testingProcessor.getNthSizeBlob(0).center.x);
// System.out.println("Blob 2: "
// + Hardware.testingProcessor.getNthSizeBlob(1).center.x);
// Driver station
// Joysticks
// information about the joysticks
// System.out.println("Right Joystick: " +
// Hardware.rightDriver.getDirectionDegrees());
// System.out.println("Left Operator: " +
// Hardware.leftOperator.getDirectionDegrees());
// System.out.println("Right Operator: " +
// Hardware.rightOperator.getDirectionDegrees());
// System.out.println("Twist: " + Hardware.leftDriver.getTwist());
// Driver station
// Joysticks
// information about the joysticks
// System.out.println("Left Joystick Direction: " +
// Hardware.leftDriver.getDirectionDegrees());
// if (Hardware.leftDriver.getTrigger())
// System.out.println("Twist: " + Hardware.leftDriver.getTwist());
// System.out.println("Left Joystick: " + Hardware.leftDriver.getY());
// System.out.println("Right Joystick: " + Hardware.rightDriver.getY());
// System.out.println("Left Operator: " + Hardware.leftOperator.getY());
// System.out.println("Right Operator: " +
// Hardware.rightOperator.getY());
// Kilroy ancillary items
// timers
// what time does the timer have now
} // end printStatements
private static double LFVal = Hardware.autoDrive
.getLeftFrontEncoderDistance();
//// The dead zone for the aligning TODO
private final static double CAMERA_ALIGN_DEADBAND = 10.0 // +/- Pixels
/ Hardware.axisCamera.getHorizontalResolution();
private static boolean tunePIDLoop = false;
// TODO find actual value
private final static double HIGHER_CAMERASERVO_POSITIONY = 90;// TODO find
// actual value
private final static double HIGHER_CAMERASERVO_POSITIONX = 90;// TODO find
// actual value
public static boolean changeCameraServoPosition = false;
public static boolean changeGearServoPosition = false;
public static boolean cameraPositionHasChanged = false;
public static boolean cancelAgitator = false;
public static boolean hasCanceledAgitator = false;
public static double testingSpeed;
public static double climbingSpeed = -1;
public static double reverseClimbingSpeed = .5;
// temporary variable to test the ability to send information from a
// separate thread to teleop
public static int valueFromThread;
} // end class |
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
// FILE NAME: Autonomous.java (Team 339 - Kilroy)
// ABSTRACT:
// This file is where almost all code for Kilroy will be
// written. All of these functions are functions that should
// override methods in the base class (IterativeRobot). The
// functions are as follows:
// Init() - Initialization code for teleop mode
// should go here. Will be called each time the robot enters
// teleop mode.
// Periodic() - Periodic code for teleop mode should
// go here. Will be called periodically at a regular rate while
// the robot is in teleop mode.
// Team 339.
package org.usfirst.frc.team339.robot;
import com.ctre.CANTalon.FeedbackDevice;
import org.usfirst.frc.team339.Hardware.Hardware;
import org.usfirst.frc.team339.Utils.Drive;
import org.usfirst.frc.team339.Utils.Shooter;
import edu.wpi.first.wpilibj.Relay;
/**
* This class contains all of the user code for the Autonomous part of the
* match, namely, the Init and Periodic code
*
* @author Nathanial Lydick
* @written Jan 13, 2015
*/
public class Teleop
{
/**
* User Initialization code for teleop mode should go here. Will be called
* once when the robot enters teleop mode.
*
* @author Nathanial Lydick
* @written Jan 13, 2015
*/
public static void init ()
{
// initialize all encoders here
Hardware.leftFrontEncoder.reset();
Hardware.rightFrontEncoder.reset();
Hardware.rightRearEncoder.reset();
Hardware.leftRearEncoder.reset();
// initialize all motors here
Hardware.leftRearMotor.set(0.0);
Hardware.rightRearMotor.set(0.0);
Hardware.rightFrontMotor.set(0.0);
Hardware.leftFrontMotor.set(0.0);
// Servo init
Hardware.cameraServo.setAngle(LOWER_CAMERASERVO_POSITION);
Hardware.gimbalMotor
.setFeedbackDevice(FeedbackDevice.CtreMagEncoder_Relative);
Hardware.gimbalMotor.setEncPosition(0);
if (Hardware.isRunningOnKilroyXVIII == true)
{
Hardware.rightFrontEncoder.setReverseDirection(true);
Hardware.rightRearEncoder.setReverseDirection(false);
Hardware.leftFrontEncoder.setReverseDirection(true);
Hardware.leftRearEncoder.setReverseDirection(false);
Hardware.rightRearEncoder.setDistancePerPulse(
Robot.ENCODER_DISTANCE_PER_PULSE_KILROY_XVIII);
Hardware.leftRearEncoder.setDistancePerPulse(
Robot.ENCODER_DISTANCE_PER_PULSE_KILROY_XVIII);
Hardware.rightFrontEncoder.setDistancePerPulse(
Robot.ENCODER_DISTANCE_PER_PULSE_KILROY_XVIII);
Hardware.leftFrontEncoder.setDistancePerPulse(
Robot.ENCODER_DISTANCE_PER_PULSE_KILROY_XVIII);
Hardware.tankDrive.setGearPercentage(1,
Robot.KILROY_XVIII_FIRST_GEAR_PERCENTAGE);
Hardware.tankDrive.setGearPercentage(2,
Robot.KILROY_XVIII_SECOND_GEAR_PERCENTAGE);
Hardware.mecanumDrive.setFirstGearPercentage(
Robot.KILROY_XVIII_FIRST_GEAR_PERCENTAGE);
Hardware.rightFrontMotor.setInverted(false);
Hardware.rightRearMotor.setInverted(false);
Hardware.leftFrontMotor.setInverted(false);
Hardware.leftRearMotor.setInverted(true);
Hardware.intakeMotor.setInverted(true);
Hardware.mecanumDrive
.setDeadbandPercentageZone(Hardware.joystickDeadzone);
Hardware.mecanumDrive.setMecanumJoystickReversed(false);
// Hardware.rightFrontMotorSafety.setExpiration(.5);
// Hardware.rightRearMotorSafety.setExpiration(.5);
// Hardware.leftFrontMotorSafety.setExpiration(.5);
// Hardware.leftRearMotorSafety.setExpiration(1.0);
Hardware.rightUS.setScalingFactor(
Hardware.KILROY_XVIII_US_SCALING_FACTOR);
Hardware.rightUS.setOffsetDistanceFromNearestBummper(3);
Hardware.rightUS.setNumberOfItemsToCheckBackwardForValidity(3);
Hardware.tankDrive.setGear(1);
Hardware.autoDrive.setDriveCorrection(.3);
Hardware.autoDrive.setEncoderSlack(1);
// Hardware.mecanumDrive.setDirectionalDeadzone(0.2);
// Hardware.tankDrive.setRightMotorDirection(MotorDirection.REVERSED);
}
else
{
// Hardware.rightFrontEncoder.setReverseDirection(true);
// Hardware.rightRearEncoder.setReverseDirection(false);
// Hardware.leftFrontEncoder.setReverseDirection(true);
// Hardware.leftRearEncoder.setReverseDirection(false);
Hardware.rightRearEncoder.setDistancePerPulse(
Robot.ENCODER_DISTANCE_PER_PULSE_KILROY_XVII);
Hardware.leftRearEncoder.setDistancePerPulse(
Robot.ENCODER_DISTANCE_PER_PULSE_KILROY_XVII);
Hardware.leftFrontEncoder.setDistancePerPulse(
Robot.ENCODER_DISTANCE_PER_PULSE_KILROY_XVII);
Hardware.rightFrontEncoder.setDistancePerPulse(
Robot.ENCODER_DISTANCE_PER_PULSE_KILROY_XVII);
Hardware.tankDrive.setGearPercentage(1,
Robot.KILROY_XVII_FIRST_GEAR_PERCENTAGE);
Hardware.tankDrive.setGearPercentage(2,
Robot.KILROY_XVII_SECOND_GEAR_PERCENTAGE);
Hardware.mecanumDrive
.setFirstGearPercentage(
Robot.KILROY_XVII_FIRST_GEAR_PERCENTAGE);
// Hardware.tankDrive.setRightMotorDirection(MotorDirection.REVERSED);
Hardware.rightFrontMotor.setInverted(true);
Hardware.rightRearMotor.setInverted(false);
Hardware.leftFrontMotor.setInverted(false);
Hardware.leftRearMotor.setInverted(false);
Hardware.intakeMotor.setInverted(true);
// Hardware.mecanumDrive
// .setDeadbandPercentageZone(Hardware.joystickDeadzone);
Hardware.mecanumDrive.setMecanumJoystickReversed(false);
Hardware.rightUS
.setScalingFactor(
Hardware.KILROY_XVII_US_SCALING_FACTOR);
Hardware.rightUS.setOffsetDistanceFromNearestBummper(3);
Hardware.rightUS.setNumberOfItemsToCheckBackwardForValidity(3);
Hardware.tankDrive.setGear(1);
Hardware.autoDrive.setDriveCorrection(.3);
Hardware.autoDrive.setEncoderSlack(1);
// Hardware.mecanumDrive.setDirectionalDeadzone(0.2);
}
} // end Init
/**
* User Periodic code for teleop mode should go here. Will be called
* periodically at a regular rate while the robot is in teleop mode.
*
* @author Nathanial Lydick
* @written Jan 13, 2015
*/
public static void periodic ()
{
if (Hardware.leftDriver.getTrigger() && !previousFireButton)
{
firing = !firing;
}
if (firing)
Hardware.shooter.fire();
// previousFireButton = Hardware.leftDriver.getTrigger();
// if (fireCount > 0)
// if (Hardware.shooter.fire())
// fireCount--;
// else if (preparingToFire == false)
// Hardware.shooter.stopFlywheelMotor();
/*
* System.out.println("Firecount: " + fireCount);
*
* System.out.println( "Flywheel speed: " +
* Hardware.shooterMotor.getSpeed());
*/
if (Hardware.ringlightSwitch.isOnCheckNow())
{
Hardware.ringlightRelay.set(Relay.Value.kOn);
}
else
{
Hardware.ringlightRelay.set(Relay.Value.kOff);
}
// Hardware.gearServo.setAngle(200);
// Hardware.gearServo.getAngle();
// Print out any data we want from the hardware elements.
printStatements();
if (Hardware.rightOperator.getRawButton(2))
Hardware.intake.startIntake();
else if (Hardware.rightOperator.getRawButton(3))
Hardware.intake.reverseIntake();
else
Hardware.intake.stopIntake();
// Driving code
// rotate only when we are pulling the trigger
if (Hardware.leftDriver.getTrigger())
{
rotationValue = Hardware.leftDriver.getTwist();
}
else
rotationValue = 0.0;
if (!isTestingDriveCode && !isAligning && !isStrafingToTarget) // Main
// driving
// function
{
if (Hardware.isUsingMecanum == true)
Hardware.mecanumDrive.drive(
Hardware.leftDriver.getMagnitude(),
Hardware.leftDriver.getDirectionDegrees(),
rotationValue);
else
Hardware.tankDrive.drive(Hardware.rightDriver.getY(),
Hardware.leftDriver.getY());
}
// Test code for break
if (Hardware.leftDriver.getRawButton(9) == true)
{
Hardware.autoDrive.driveStraightInches(12, .5);
}
// OPERATOR CONTROLS
// INTAKE CONTROLS
if (Hardware.leftOperator.getRawButton(2))
Hardware.intake.startIntake();
else if (Hardware.leftOperator.getRawButton(3))
Hardware.intake.reverseIntake();
else
Hardware.intake.stopIntake();
// END INTAKE CONTROLS
// TURRET OVERRIDE
if (Hardware.rightOperator.getRawButton(2)
&& Math.abs(Hardware.rightOperator.getX()) > .2)
Hardware.shooter
.turnGimbalSlow(
Hardware.rightOperator.getX() > 0 ? -1 : 1);
else
Hardware.shooter.stopGimbal();
// END TURRET OVERRIDE
// ELEVATOR OVERRIDE
if (Hardware.rightOperator.getRawButton(3))
Hardware.shooter.loadBalls();
else if (Hardware.rightOperator.getRawButton(4))
Hardware.shooter.reverseLoader();
else
Hardware.shooter.stopLoader();
// END ELEVATOR OVERRIDE
// TESTING SHOOTER
if (Hardware.rightOperator.getTrigger())
{
Hardware.shooter.loadBalls();
Hardware.shooterMotor.set(1000);
}
else if (Hardware.rightOperator.getRawButton(9))
Hardware.shooterMotor.set(1000);
else
Hardware.shooterMotor.set(0.0);
// END SHOOTER TESTING
// CAMERA CODE
Hardware.axisCamera
.takeSinglePicture(Hardware.leftOperator.getRawButton(8)
|| Hardware.rightOperator.getRawButton(8)
|| Hardware.leftOperator.getRawButton(11));
// Written by Ashley Espeland, has not been tested
// cameraServo code setting to either the higher or the lower angle
// position
// if button 9 equals true and this method had not been called
// since the last time the button read false (cameraPositionHasChanged)
if (Hardware.rightOperator.getRawButton(5) == true
&& cameraPositionHasChanged == false)
{
// set changeCameraServoPosition to true
changeCameraServoPosition = true;
}
// if changeCamerServoPosition equals true
if (changeCameraServoPosition == true)
{
// if the servo is in the lower position
if (Hardware.cameraServo
.getAngle() == LOWER_CAMERASERVO_POSITION)
{
// then set the servo to the higher position and change
// cameraPositionHasChanged to true
Hardware.cameraServo
.setAngle(HIGHER_CAMERASERVO_POSITION);
cameraPositionHasChanged = true;
}
// if the cameraServo is in the higher position
else if (Hardware.cameraServo
.getAngle() == HIGHER_CAMERASERVO_POSITION)
{
// set the servo to the lower position and change
// cameraPositionHasChanged to true
Hardware.cameraServo
.setAngle(LOWER_CAMERASERVO_POSITION);
cameraPositionHasChanged = true;
}
}
// if camera servo position has been changed and the button equals false
if (changeCameraServoPosition == true
&& Hardware.leftOperator.getRawButton(4) == false)
{
// set the cameraPositionHasChanged to false to be able to change
// the position again when the button is pushed again
cameraPositionHasChanged = false;
}
Hardware.axisCamera
.takeSinglePicture(Hardware.leftOperator.getRawButton(8)
|| Hardware.rightOperator.getRawButton(8)
|| Hardware.leftOperator.getRawButton(11));
} // end
// Periodic
private static Drive.AlignReturnType alignValue = Drive.AlignReturnType.MISALIGNED;
private static Shooter.turnReturn turnValue = Shooter.turnReturn.SUCCESS;
private static double rotationValue = 0.0;
private static boolean isTurningGimbal = false;
private static boolean isAligning = false;
private static boolean previousFireButton = false;
private static boolean isStrafingToTarget = false;
private static boolean preparingToFire = false;
private static double movementSpeed = 0.3;
private static boolean firing = false;
private static boolean hasPressedFour = false;
/**
* stores print statements for future use in the print "bank", statements
* are commented out when not in use, when you write a new print statement,
* "deposit" the statement in the correct "bank" do not "withdraw"
* statements, unless directed to.
*
* NOTE: Keep the groupings below, which coorespond in number and order as
* the hardware declarations in the HARDWARE class
*
* @author Ashley Espeland
* @written 1/28/16
*
* Edited by Ryan McGee Also Edited by Josef Liebl
*
*/
public static void printStatements ()
{
// Motor controllers
// prints value of the motors
// System.out.println("Right Front Motor Controller: "
// + Hardware.rightFrontMotor.get());
// System.out.println("Left Front Motor Controller: " +
// Hardware.leftFrontMotor.get());
// System.out.println("Right Rear Motor Controller: " +
// Hardware.rightRearMotor.get());
// System.out.println("Left Rear Motor Controller: " +
// Hardware.leftRearMotor.get());
// System.out
// .println("Flywheel Motor: " + Hardware.shooterMotor.get());
// System.out.println("Intake Motor: " + Hardware.intakeMotor.get());
// if (Hardware.rightOperator.getRawButton(11)) {
// Hardware.elevatorMotor.setSpeed(1);
// System.out.println("Elevator Motor: " +
// Hardware.elevatorMotor.get());
// System.out.println("Turret Spark: " + Hardware.gimbalMotor.get());
// CAN items
// prints value of the CAN controllers
// Hardware.CAN.printAllPDPChannels();
// Relay
// prints value of the relay states
// if (Hardware.ringlightSwitch.isOnCheckNow())
// System.out.println("Ring light relay is On");
// else if (!Hardware.ringlightSwitch.isOnCheckNow())
// System.out.println("Ring light relay is Off");
// Digital Inputs
// Switches
// prints state of switches
// System.out.println("Gear Limit Switch: "
// + Hardware.gearLimitSwitch.isOn());
// System.out.println("Backup or fire: " +
// Hardware.backupOrFire.isOn());
// System.out.println("Enable Auto: " +
// Hardware.enableAutonomous.isOn());
// System.out.println(
// "Path Selector: " + Hardware.pathSelector.getPosition());
// System.out.println("Right UltraSonic distance from bumper: "
// + Hardware.rightUS.getDistanceFromNearestBumper());
// Encoders
// prints the distance from the encoders
// System.out.println("Right Front Encoder: " +
// Hardware.rightFrontEncoder.get());
// System.out.println("Right Front Encoder Distance: " +
// Hardware.autoDrive.getRightRearEncoderDistance());
// System.out.println("Right Rear Encoder: " +
// Hardware.rightRearEncoder.get());
// System.out.println("Right Rear Encoder Distance: " +
// Hardware.autoDrive.getRightRearEncoderDistance());
// System.out.println("Left Front Encoder: " +
// Hardware.leftFrontEncoder.get());
// System.out.println("Left Front Encoder Distance: " +
// Hardware.autoDrive.getLeftFrontEncoderDistance());
// System.out.println("Left Rear Encoder: " +
// Hardware.leftRearEncoder.get());
// System.out.println("Left Rear Encoder Distance: " +
// Hardware.autoDrive.getLeftFrontEncoderDistance());
// System.out.println("Right Front Encoder: " +
// Hardware.rightFrontEncoder.get());
System.out.println("Right Front Encoder Distance: " +
Hardware.autoDrive.getRightRearEncoderDistance());
// System.out.println("Right Rear Encoder: " +
// Hardware.rightRearEncoder.get());
System.out.println("Right Rear Encoder Distance: " +
Hardware.autoDrive.getRightRearEncoderDistance());
// System.out.println("Left Front Encoder: " +
// Hardware.leftFrontEncoder.get());
System.out.println("Left Front Encoder Distance: " +
Hardware.autoDrive.getLeftFrontEncoderDistance());
// System.out.println("Left Rear Encoder: " +
// Hardware.leftRearEncoder.get());
System.out.println("Left Rear Encoder Distance: " +
Hardware.autoDrive.getLeftFrontEncoderDistance());
// Red Light/IR Sensors
// prints the state of the sensor
// if (Hardware.ballLoaderSensor.isOn() == true)
// System.out.println("Ball IR Sensor is On");
// else if (Hardware.ballLoaderSensor.isOn() == false)
// System.out.println("Ball IR Sensor is Off");
// Pneumatics
// Compressor
// prints information on the compressor
// There isn't one at the moment
// Solenoids
// prints the state of solenoids
// There are none at the moment
// That seems familiar...
// Analogs
// We don't want the print statements to flood everything and go ahhhhhhhh
// if (Hardware.rightOperator.getRawButton(11))
// System.out.println("LeftUS = "
// + Hardware.leftUS.getDistanceFromNearestBumper());
// System.out.println("RightUS = "
// + Hardware.rightUS.getDistanceFromNearestBumper());
// System.out.println("Delay Pot: " + Hardware.delayPot.get());
// pots
// where the pot is turned to
// System.out.println("Delay Pot Degrees" + Hardware.delayPot.get());
// Connection Items
// Cameras
// prints any camera information required
// System.out.println("Expected center: " + CAMERA_ALIGN_CENTER);
// Hardware.imageProcessor.processImage();
// System.out.println("Number of blobs: " + Hardware.imageProcessor
// .getParticleAnalysisReports().length);
// if (Hardware.imageProcessor.getNthSizeBlob(1) != null)
// System.out
// .println("Actual center: " + ((Hardware.imageProcessor
// .getNthSizeBlob(0).center_mass_x
// + Hardware.imageProcessor
// .getNthSizeBlob(1).center_mass_x)
// / Hardware.axisCamera
// .getHorizontalResolution());
// System.out.println("Deadband: " + CAMERA_ALIGN_DEADBAND);
// Driver station
// Joysticks
// information about the joysticks
// System.out.println("Right Joystick: " +
// Hardware.rightDriver.getDirectionDegrees());
// System.out.println("Left Operator: " +
// Hardware.leftOperator.getDirectionDegrees());
// System.out.println("Right Operator: " +
// Hardware.rightOperator.getDirectionDegrees());
// System.out.println("Twist: " + Hardware.leftDriver.getTwist());
// Driver station
// Joysticks
// information about the joysticks
// System.out.println("Left Joystick: " +
// Hardware.leftDriver.getDirectionDegrees());
// System.out.println("Twist: " + Hardware.leftDriver.getTwist());
// System.out.println("Left Joystick: " + Hardware.leftDriver.getY());
// System.out.println("Right Joystick: " + Hardware.rightDriver.getY());
// System.out.println("Left Operator: " + Hardware.leftOperator.getY());
// System.out.println("Right Operator: " +
// Hardware.rightOperator.getY());
// Kilroy ancillary items
// timers
// what time does the timer have now
} // end printStatements
private final static double CAMERA_ALIGN_SPEED = .5;
//// The dead zone for the aligning TODO
private final static double CAMERA_ALIGN_DEADBAND = 10.0 // +/- Pixels
/ Hardware.axisCamera.getHorizontalResolution();
private final static double CAMERA_ALIGN_CENTER = .478; // Relative coordinates
// TUNEABLES
private final static double LOWER_CAMERASERVO_POSITION = 65; // TODO
// find
// actual value
private final static double HIGHER_CAMERASERVO_POSITION = 90;// TODO find
// actual
// actual value
public static boolean changeCameraServoPosition = false;
public static boolean changeGearServoPosition = false;
public static boolean cameraPositionHasChanged = false;
public static boolean cancelAgitator = false;
public static boolean hasCanceledAgitator = false;
private static boolean prevState = false; // TODO Testing take out
private static boolean isTestingDriveCode = true;
} // end class |
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by RobotBuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc2832.Robot_2016;
import java.nio.ByteBuffer;
import org.usfirst.frc2832.Robot_2016.HID.GamepadState;
import org.usfirst.frc2832.Robot_2016.commands.Intake;
import org.usfirst.frc2832.Robot_2016.commands.InterfaceFlip;
import org.usfirst.frc2832.Robot_2016.commands.MoveAimerDown;
import org.usfirst.frc2832.Robot_2016.commands.MoveAimerUp;
import org.usfirst.frc2832.Robot_2016.commands.Shoot;
import org.usfirst.frc2832.Robot_2016.commands.SpinShooterWheels;
import org.usfirst.frc2832.Robot_2016.commands.StopAimer;
import org.usfirst.frc2832.Robot_2016.commands.StopBallMotors;
import org.usfirst.frc2832.Robot_2016.commands.autonomous.ConstructedAutonomous;
import org.usfirst.frc2832.Robot_2016.commands.autonomous.MoveForward;
import org.usfirst.frc2832.Robot_2016.commands.autonomous.ParseInput;
import org.usfirst.frc2832.Robot_2016.commands.autonomous.RotateAngle;
import com.ni.vision.VisionException;
import edu.wpi.first.wpilibj.CameraServer;
import edu.wpi.first.wpilibj.GenericHID;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.CommandGroup;
import edu.wpi.first.wpilibj.command.Scheduler;
import edu.wpi.first.wpilibj.livewindow.LiveWindow;
import edu.wpi.first.wpilibj.networktables.NetworkTable;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj.vision.USBCamera;
import edu.wpi.first.wpilibj.can.CANJNI;
import edu.wpi.first.wpilibj.can.CANExceptionFactory;
import java.nio.IntBuffer;
import java.util.Arrays;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.DriverStation.Alliance;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Robot extends IterativeRobot {
private static boolean recordedAuton = false;
Command autonomousCommand;
public static NetworkTable table;
public static OI oi;
public static BallMotors ballMotors = new BallMotors();
public static Aimer aimer = new Aimer();
public static double defaultAngle;
public static USBCamera camera1, camera2;
public boolean leftTriggerPressed = false;
public boolean rightTriggerPressed = false;
public boolean shooterNotActive = true;
public boolean povPressed = false;
private long lastRunTime = System.currentTimeMillis();
private long timer = 0;
private String recordedID;
public static SendableChooser auto_Movement, auto_Reverse, auto_isHighGoal;
// public static int gameMode; // 0 is autonDrive, 1 teleopDrive, 2 ingesting, 3 shooting
// public static boolean isAuton;
public static boolean isBlue;
public static boolean isSpinning;
public static boolean isShooting;
public static boolean isExpelling;
public static boolean isIngesting;
private IntBuffer CAN_status = ByteBuffer.allocateDirect(4).asIntBuffer();
private IntBuffer CAN_messageId = ByteBuffer.allocateDirect(4).asIntBuffer();
private ByteBuffer CAN_data = ByteBuffer.allocateDirect(8);
private ByteBuffer CAN_timestamp = ByteBuffer.allocate(4);
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
RobotMap.init();
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTORS
// OI must be constructed after subsystems. If the OI creates Commands
//(which it very likely will), subsystems are not guaranteed to be
// constructed yet. Thus, their requires() statements may grab null
// pointers. Bad news. Don't move it.
oi = new OI();
try {
camera1 = new USBCamera("cam0");
camera2 = new USBCamera("cam1");
camera1.setFPS(15);
camera1.setSize(320, 240);
camera2.setFPS(15);
camera2.setSize(320, 240);
CameraServer2832 cameraServer = CameraServer2832.getInstance();
cameraServer.startAutomaticCapture(camera1, camera2);
} catch (VisionException e) {
e.printStackTrace();
}
auto_Movement = new SendableChooser();
auto_Movement.addObject("Do nothing at all", "0");
auto_Movement.addObject("Rotate 45", "r45");
auto_Movement.addObject("Rotate -45", "r-45");
auto_Movement.addObject("Move Forward 3", "f3");
auto_Movement.addDefault("Move Forward 5", "f5");
auto_Movement.addObject("Move Forward 6.5", "f6.5");
auto_Movement.addObject("Spy Bot", "s");
SmartDashboard.putData("Autonomous Selection", auto_Movement);
auto_Reverse = new SendableChooser();
auto_Reverse.addDefault("Just move forward", false);
auto_Reverse.addObject("Go backwards after", true);
SmartDashboard.putData("Add backwards motion", auto_Reverse);
auto_isHighGoal = new SendableChooser();
auto_isHighGoal.addDefault("No shot", 0);
auto_isHighGoal.addObject("Low Goal", 1);
auto_isHighGoal.addObject("High Goal", 2);
SmartDashboard.putData("Shooting", auto_isHighGoal);
isBlue = false;
isSpinning = false;
isShooting = false;
isExpelling = false;
isIngesting = false;
RobotMap.winchMotor.setEncPosition(0);
table = NetworkTable.getTable("GRIP/contours");
}
/**
* This function is called when the disabled button is hit.
* You can use it to reset subsystems before shutting down.
*/
public void disabledInit(){
if (recordedAuton)
oi.gamepad.loadVirtualGamepad(recordedID);
RobotMap.winchMotor.setEncPosition(0);
}
public void disabledPeriodic() {
Scheduler.getInstance().run();
recordedID = (String) (oi.index.getSelected());
recordedAuton = SmartDashboard.getBoolean("Use Recorded Autonomous");
Aimer.toPositionMode();
RobotMap.winchMotor.setEncPosition(0);
RobotMap.winchMotor.setPosition(0);
RobotMap.winchMotor.set(0);
DashboardOutput.putPeriodicData();
isBlue = (DriverStation.getInstance().getAlliance() == Alliance.Blue);
sendStateToLights(false, false);
}
public void autonomousInit() {
if (recordedAuton) {
oi.gamepad.startVirtualGamepad();
} else {
// schedule the autonomous command (example)
autonomousCommand = (CommandGroup) new ConstructedAutonomous(ParseInput.takeInput((String)auto_Movement.getSelected(),
(boolean)auto_Reverse.getSelected(), (int)auto_isHighGoal.getSelected()));
if(autonomousCommand != null)
autonomousCommand.start();
}
}
/**
* This function is called periodically during autonomous
*/
public void autonomousPeriodic() {
if (recordedAuton)
handleInput(oi.gamepad);
Scheduler.getInstance().run();
DashboardOutput.putPeriodicData();//this is a method to contain all the "putNumber" crap we put to the Dashboard
sendStateToLights(true, true);
}
public void teleopInit() {
// This makes sure that the autonomous stops running when
// teleop starts running. If you want the autonomous to
// continue until interrupted by another command, remove
// this line or comment it out.
//if (autonomousCommand != null) autonomousCommand.cancel();
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
// Recordable Autonomous
oi.gamepad.updateRecordStatus();
DashboardOutput.putPeriodicData();
handleInput(oi.gamepad);
Scheduler.getInstance().run();
sendStateToLights(true, false);
//D-Pad Controls
}
/**
* This function is called periodically during test mode
*/
public void testPeriodic() {
LiveWindow.run();
}
private void handleInput(GenericHID g) {
RobotMap.driveTrain.arcadeDrive(
g.getRawAxis(GamepadState.AXIS_LY) * (InterfaceFlip.isFlipped ? 1 : -1),
g.getRawAxis(GamepadState.AXIS_RX));
//D-Pad Controls
switch (oi.gamepad.getPOV()) {
//D-pad right
case 90:
if (!povPressed) {
Scheduler.getInstance().add(null);
}
povPressed = true;
break;
//D-pad left
case 270:
if (!povPressed) {
Scheduler.getInstance().add(null);
}
povPressed = true;
break;
//D-pad up
case 0:
// Use speed mode if not currently used
if (!povPressed) {
Scheduler.getInstance().add(new MoveAimerUp());
}
povPressed = true;
break;
//D-pad down
case 180:
if (!povPressed) {
Scheduler.getInstance().add(new MoveAimerDown());
}
povPressed = true;
break;
case -1:
if (povPressed == true) {
Scheduler.getInstance().add(new StopAimer());
}
povPressed = false;
break;
}
//left Trigger Code
if (oi.gamepad.getRawAxis(GamepadState.AXIS_LT) >= .2) {
Scheduler.getInstance().add(new Intake());
leftTriggerPressed = true;
} else {
leftTriggerPressed = false;
}
//right Trigger Code
if (oi.gamepad.getRawAxis(GamepadState.AXIS_RT) >= .2) {
Scheduler.getInstance().add(new SpinShooterWheels());
rightTriggerPressed = true;
} else if (rightTriggerPressed){
rightTriggerPressed = false;
shooterNotActive = true;
Scheduler.getInstance().add(new StopBallMotors());
}
// if (rightTriggerPressed && shooterNotActive) {
// gameMode = 3;
// Scheduler.getInstance().add(new SpinShooterWheels());
// shooterNotActive = false;
}
void sendStateToLights(boolean isEnabled, boolean isAutonomous)
{
// final int MSGID_FOR_LIGHTS = CANJNI.LM_API_ICTRL_T_SET | 0x30; // ID=59
// LM_API_ICTRL_T_SET =((0x00020000 | 0x02000000 | 0x00001000) | (7 << 6));
// Final ID: 0x020211FB
// (7 < 6) => 111000000 => 0x1C0
// Decoded on Ardinio as 0x1F02033B
// Random: 0x2041441
// DO NOT CHANGE THIS NUMBER
// Doug and Justin worked for a long while to find an ID that works.
// We are using CAN ID 16 (0x10) Bigger IDs don't seem to work.
final int MSGID_FOR_LIGHTS = 0x02021450;
timer = System.currentTimeMillis();
if ( timer > lastRunTime + 100 ) // At least 100 ms difference.
{
lastRunTime = timer;
CAN_data.put(0, (byte)(isAutonomous ? 0 : 1) );
CAN_data.put(1, (byte)(isBlue ? 0 : 1) );
CAN_data.put(2, (byte)(isEnabled ? 1 : 0) );
CAN_data.put(3, (byte)(isSpinning ? 1 : 0) );
CAN_data.put(4, (byte)(isShooting ? 1 : 0) );
CAN_data.put(5, (byte)(isExpelling ? 1 : 0) );
CAN_data.put(6, (byte)(isIngesting ? 1 : 0) );
CAN_data.put(7, (byte)0);
try
{
CANJNI.FRCNetworkCommunicationCANSessionMuxSendMessage(MSGID_FOR_LIGHTS, CAN_data, CANJNI.CAN_SEND_PERIOD_NO_REPEAT);
}
catch (Exception e)
{
// e.printStackTrace();
}
}
}
} |
package org.yuanheng.cookcc.lexer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.yuanheng.cookcc.doc.ShortcutDoc;
import org.yuanheng.cookcc.exception.*;
/**
* Hand written rule parser.
*
* @author Heng Yuan
* @version $Id$
*/
public class RuleParser
{
private final static Pattern m_replaceName = Pattern.compile ("\\{[a-zA-Z_][a-zA-Z0-9_-]*[}]");
private final Lexer m_lexer;
private final NFAFactory m_nfaFactory;
private final CCL m_ccl;
private final boolean m_nocase;
private int m_trailContext;
private boolean m_varLen;
private int m_ruleLen;
private boolean m_bol;
private boolean[] m_singletonCharSet;
private boolean[] m_cclCharSet;
private boolean[] m_quoteCharSet;
private RuleLexer m_lex;
private int m_lineNumber;
private class RuleLexer
{
private String m_input;
private String m_currentStr;
private int m_pos;
public RuleLexer (String input)
{
m_input = input;
m_currentStr = input;
m_pos = 0;
}
public boolean isEmpty ()
{
return m_pos == m_currentStr.length ();
}
public Character ifMatchEsc ()
{
if (!ifMatch ('\\'))
return null;
--m_pos;
int[] escPos = new int[]{ m_pos };
char ch = CCL.esc (m_currentStr, escPos);
m_pos = escPos[0];
return new Character (ch);
}
public boolean ifMatchReplaceName ()
{
if (!ifMatch ('{'))
return false;
--m_pos; // rewind the forward;
m_currentStr = m_currentStr.substring (m_pos);
m_pos = 0;
Matcher matcher = m_replaceName.matcher (m_currentStr);
if (!matcher.find (0) || matcher.start () != 0)
return false;
int index = m_currentStr.indexOf ('}');
String name = m_currentStr.substring (1, index);
ShortcutDoc shortcut = m_lexer.getDocument ().getLexer ().getShortcut (name);
if (shortcut == null)
throw new UnknownNameException (m_lineNumber, name, m_input);
m_currentStr = "(" + shortcut.getPattern () + ")" + m_currentStr.substring (index + 1);
return true;
}
public void unread (String str)
{
m_currentStr = str + m_currentStr.substring (m_pos);
m_pos = 0;
}
public boolean ifMatch (String str)
{
if ((m_currentStr.length () - m_pos) < str.length ())
return false;
int len = str.length ();
int offset = m_pos;
for (int i = 0; i < len; ++i)
if (m_currentStr.charAt (offset++) != str.charAt (i))
return false;
m_pos = offset;
return true;
}
public boolean ifMatch (char ch)
{
if (m_pos >= m_currentStr.length () || m_currentStr.charAt (m_pos) != ch)
return false;
++m_pos;
return true;
}
public Character ifMatch (boolean[] charSet)
{
Character ch;
if (m_pos >= m_currentStr.length () || !charSet[m_currentStr.charAt (m_pos)])
return null;
ch = new Character (m_currentStr.charAt (m_pos));
++m_pos;
return ch;
}
public void match (char ch)
{
if (m_pos >= m_currentStr.length () || m_currentStr.charAt (m_pos) != ch)
throw new LookaheadException (m_lineNumber, m_ccl, ch, m_input, m_pos);
++m_pos;
}
public String getInput ()
{
return m_input;
}
public int getPos ()
{
return m_pos;
}
}
public RuleParser (Lexer lexer, NFAFactory nfaFactory)
{
this (lexer, nfaFactory, false);
}
public RuleParser (Lexer lexer, NFAFactory nfaFactory, boolean nocase)
{
m_lexer = lexer;
m_nfaFactory = nfaFactory;
m_ccl = nfaFactory.getCCL ();
m_nocase = nocase;
m_trailContext = 0;
m_varLen = false;
m_ruleLen = 0;
m_bol = false;
m_singletonCharSet = CCL.subtract (m_ccl.ANY.clone (), m_ccl.parseCCL ("[$/|*+?.(){}]]"));
m_cclCharSet = CCL.subtract (m_ccl.ANY.clone (), m_ccl.parseCCL ("[-\\]\\n]"));
m_quoteCharSet = m_ccl.parseCCL ("[^\"\\n]");
}
public boolean isBOL ()
{
return m_bol;
}
public NFA parse (int lineNumber, String input)
{
m_lineNumber = lineNumber;
m_lex = new RuleLexer (input);
if (m_lex.ifMatch ('^'))
m_bol = true;
NFA head = parseRegex ();
if (head == null)
throw new InvalidRegExException (lineNumber, input);
if (m_lex.ifMatch ('/'))
{
if (NFA.hasTrail (m_trailContext))
throw new MultipleTrailContextException (lineNumber, input);
if (m_varLen)
m_ruleLen = 0;
m_trailContext = NFA.setTrailContext (m_ruleLen, !m_varLen, false);
NFA tail = parseRegex ();
if (m_lex.ifMatch ('$'))
{
NFA eol = m_nfaFactory.createNFA ('\n', null);
tail = tail == null ? eol : tail.cat (eol);
++m_ruleLen;
}
if (tail == null)
throw new ParserException (lineNumber, "unexpected '/'");
if ((m_trailContext & NFA.TRAIL_MASK) != NFA.TRAIL_FIXHEAD)
{
if (m_varLen)
throw new VariableTrailContextException (lineNumber, input);
else
m_trailContext = NFA.setTrailContext (m_ruleLen, false, true);
}
head = head.cat (tail);
}
else if (m_lex.ifMatch ('$'))
{
if (NFA.hasTrail (m_trailContext))
throw new MultipleTrailContextException (lineNumber, input);
m_trailContext = NFA.setTrailContext (1, false, true);
head = head.cat (m_nfaFactory.createNFA ('\n', null));
}
head.setState (m_lexer.incCaseCounter (), lineNumber, m_trailContext);
return head;
}
private NFA parseRegex ()
{
m_varLen = false;
m_ruleLen = 0;
NFA head = parseSeries ();
if (head == null)
throw new InvalidRegExException (m_lineNumber, m_lex.getInput ());
while (m_lex.ifMatch ('|'))
{
NFA tail = parseSeries ();
if (tail == null)
throw new InvalidRegExException (m_lineNumber, m_lex.getInput ());
head = head.or (tail);
}
return head;
}
private NFA parseSeries ()
{
NFA head = parseSingleton (null);
if (head == null)
throw new InvalidRegExException (m_lineNumber, m_lex.getInput ());
NFA tail;
while ((tail = parseSingleton (null)) != null)
head = head.cat (tail);
return head;
}
private NFA parseSingleton (NFA head)
{
while (true)
{
if (head == null)
{
boolean[] ccl;
Character ch;
if (m_lex.ifMatch ('.'))
{
++m_ruleLen;
head = m_nfaFactory.createNFA (NFA.ISCCL, m_ccl.ANY);
}
else if (m_lex.ifMatch ("<<EOF>>"))
{
if (!m_lex.isEmpty ())
throw new LookaheadException (m_lineNumber, m_ccl, m_ccl.EOF, m_lex.getInput (), m_lex.getPos ());
head = m_nfaFactory.createNFA (m_ccl.EOF, null);
}
else if (m_lex.ifMatchReplaceName ())
{
continue;
}
else if ((ccl = parseFullCCL ()) != null)
{
++m_ruleLen;
head = m_nfaFactory.createNFA (NFA.ISCCL, ccl);
}
else if (m_lex.ifMatch ('"'))
{
head = parseString ();
if (head == null)
throw new InvalidRegExException (m_lineNumber, m_lex.getInput ());
m_lex.match ('"');
}
else if (m_lex.ifMatch ('('))
{
head = parseRegex ();
if (head == null)
throw new InvalidRegExException (m_lineNumber, m_lex.getInput ());
m_lex.match (')');
}
else if ((ch = parseChar (m_singletonCharSet)) != null)
{
++m_ruleLen;
if (m_nocase)
{
char c = ch.charValue ();
ccl = m_ccl.EMPTY.clone ();
ccl[c] = true;
if (c >= 'a' && c <= 'z')
ccl[c - 'a' + 'A'] = true;
else if (c >= 'A' && c <= 'Z')
ccl[c - 'A' + 'a'] = true;
head = m_nfaFactory.createNFA (NFA.ISCCL, ccl);
}
else
head = m_nfaFactory.createNFA (ch.charValue (), null);
}
else
return null;
}
else
{
if (m_lex.ifMatch ('*'))
{
m_varLen = true;
head = head.star ();
}
else if (m_lex.ifMatch ('+'))
{
m_varLen = true;
head = head.plus ();
}
else if (m_lex.ifMatch ('?'))
{
m_varLen = true;
head = head.q ();
}
if (m_lex.ifMatchReplaceName ())
{
continue;
}
else if (m_lex.ifMatch ('{'))
{
Integer number = parseNumber ();
if (number == null || number.intValue () < 0)
throw new BadIterationException (m_lineNumber, number);
if (m_lex.ifMatch ('}'))
head = head.repeat (number);
else
{
int min, max;
min = number.intValue ();
m_lex.match (',');
number = parseNumber ();
if (number == null)
max = -1;
else
max = number.intValue ();
head = head.repeat (min, max);
m_lex.match ('}');
}
}
else
break;
}
}
return head;
}
private Character parseChar (boolean[] charSet)
{
Character ch = m_lex.ifMatchEsc ();
if (ch == null)
ch = m_lex.ifMatch (charSet);
return ch;
}
private Integer parseNumber ()
{
Character ch;
boolean neg = false;
if (m_lex.ifMatch ('-'))
neg = true;
int number;
if ((ch = parseChar (m_ccl.DIGIT)) == null)
throw new LookaheadException (m_lineNumber, m_ccl, m_ccl.DIGIT, m_lex.getInput (), m_lex.getPos ());
number = ch.charValue () - '0';
while ((ch = parseChar (m_ccl.DIGIT)) != null)
number = number * 10 + ch.charValue () - '0';
if (neg)
number = -number;
return new Integer (number);
}
private NFA parseString ()
{
NFA head = null;
Character ch;
while ((ch = parseChar (m_quoteCharSet)) != null)
{
++m_ruleLen;
NFA tail;
if (m_nocase)
{
char c = ch.charValue ();
boolean[] ccl = m_ccl.EMPTY.clone ();
ccl[c] = true;
if (c >= 'a' && c <= 'z')
ccl[c - 'a' + 'A'] = true;
else if (c >= 'A' && c <= 'Z')
ccl[c - 'A' + 'a'] = true;
tail = m_nfaFactory.createNFA (NFA.ISCCL, ccl);
}
else
tail = m_nfaFactory.createNFA (ch.charValue (), null);
if (head == null)
head = tail;
else
head = head.cat (tail);
}
return head;
}
private boolean[] parseFullCCL ()
{
if (!m_lex.ifMatch ('['))
return null;
boolean neg = false;
if (m_lex.ifMatch ('^'))
neg = true;
boolean[] ccl = m_ccl.EMPTY.clone ();
ccl = parseCCL (ccl);
if (m_nocase)
{
for (int i = 'a'; i <= 'z'; ++i)
{
if (ccl[i])
ccl[i - 'a' + 'A'] = true;
if (ccl[i - 'a' + 'A'])
ccl[i] = true;
}
}
if (neg)
CCL.negate (ccl);
m_lex.match (']');
return ccl;
}
private boolean[] parseCCL (boolean[] ccl)
{
while (parseCCE (ccl) != null ||
parseCCLChar (ccl) != null)
;
return ccl;
}
private boolean[] parseCCLChar (boolean[] ccl)
{
Character start = parseChar (m_cclCharSet);
if (start == null)
return null;
if (!m_lex.ifMatch ('-'))
{
ccl[start.charValue ()] = true;
return ccl;
}
Character end = parseChar (m_cclCharSet);
if (end == null)
throw new LookaheadException (m_lineNumber, m_ccl, m_cclCharSet, m_lex.getInput (), m_lex.getPos ());
for (int i = start.charValue (); i <= end.charValue (); ++i)
ccl[i] = true;
return ccl;
}
private boolean[] parseCCE (boolean[] ccl)
{
if (m_lex.ifMatch ("[:lower:]"))
return CCL.merge (ccl, m_ccl.LOWER);
if (m_lex.ifMatch ("[:upper:]"))
return CCL.merge (ccl, m_ccl.UPPER);
if (m_lex.ifMatch ("[:ascii:]"))
return CCL.merge (ccl, m_ccl.ASCII);
if (m_lex.ifMatch ("[:alpha:]"))
return CCL.merge (ccl, m_ccl.ALPHA);
if (m_lex.ifMatch ("[:digit:]"))
return CCL.merge (ccl, m_ccl.DIGIT);
if (m_lex.ifMatch ("[:alnum:]"))
return CCL.merge (ccl, m_ccl.ALNUM);
if (m_lex.ifMatch ("[:punct:]"))
return CCL.merge (ccl, m_ccl.PUNCT);
if (m_lex.ifMatch ("[:graph:]"))
return CCL.merge (ccl, m_ccl.GRAPH);
if (m_lex.ifMatch ("[:print:]"))
return CCL.merge (ccl, m_ccl.PRINT);
if (m_lex.ifMatch ("[:blank:]"))
return CCL.merge (ccl, m_ccl.BLANK);
if (m_lex.ifMatch ("[:cntrl:]"))
return CCL.merge (ccl, m_ccl.CNTRL);
if (m_lex.ifMatch ("[:xdigit:]"))
return CCL.merge (ccl, m_ccl.XDIGIT);
if (m_lex.ifMatch ("[:space:]"))
return CCL.merge (ccl, m_ccl.SPACE);
return null;
}
} |
import javax.servlet.RequestDispatcher;
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.util.*;
/**
* Admin: Allows the admin to view the given issue, change state, add comments, mark as KB article, etc
* User: Allows the user to view the given issue if they created it, add comments
*/
public class Issues_ViewController extends BaseController {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.doGet(request, response);
String path = request.getPathInfo();
String[] pathParts = path.split("/");
int id;
try {
id = Integer.parseInt(pathParts[1]);
} catch (NumberFormatException ex) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
if (this.isLoggedIn()) {
try {
Issue issue = this.getPortalBean().getIssues().getIssueById(id);
if(issue!=null){
request.setAttribute("issue", issue);
Status_DBWrapper statusWrapper = this.getPortalBean().getStatuses();
statusWrapper.reset();
statusWrapper.addSort("id", "ASC");
Status[] statuses = statusWrapper.runQuery();
request.setAttribute("statuses", statuses);
if(this.getUser().isAdmin()){
request.getRequestDispatcher("/WEB-INF/jsp/issues/view-admin.jsp").forward(request, response);
}
else{
request.getRequestDispatcher("/WEB-INF/jsp/issues/view-user.jsp").forward(request, response);
}
}
else {
response.sendRedirect(this.getBaseURL() + "issues");
}
}catch (Exception e){
e.printStackTrace();
response.sendRedirect(this.getBaseURL()+"issues");
}
} else {
request.getSession().setAttribute("r", "issues/" + id);
RequestDispatcher dispatcher = request.getRequestDispatcher("/login");
dispatcher.forward(request, response);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
super.doPost(request, response);
// System.out.println("Testub");
// //@TODO: Not sure how the issue is being sent through here, so will just generate a dummy issue for now
// Issue updatedIssue = new Issue();
// // Update user on status change if needed
// Issue currentState = this.portalBean.issues.getIssueById(updatedIssue.getIssueId());
// if (updatedIssue.getIssueId() != currentState.getIssueId()) {
// // Notify reporter
// User reporter = this.portalBean.users.getById(updatedIssue.getUserId());
// reporter.setNotification(true);
// reporter.setNotificationText("Issue: #" + updatedIssue.getIssueId() + " has been updated.");
// this.portalBean.users.updateUser(reporter);
String path = request.getPathInfo();
String[] pathParts = path.split("/");
int id;
try {
id = Integer.parseInt(pathParts[1]);
} catch (NumberFormatException ex) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
Issue currentState = null;
Issue_DBWrapper issue_dbWrapper = this.getPortalBean().getIssues();
if(this.getUser().isAdmin()){
currentState = issue_dbWrapper.getIssueById(id);
}
else {
Issue[] allUserIssues = issue_dbWrapper.getIssuesbyUserId(this.getUser().getUserId());
for (int m = 0; m <allUserIssues.length; m++) {
if(allUserIssues[m].getIssueId() == id){
currentState = allUserIssues[m];
break;
}
}
}
if(currentState!=null){
if(request.getParameter("status")!="8"){
Calendar calendar = Calendar.getInstance();
java.sql.Date startDate = new java.sql.Date(calendar.getTime().getTime());
Comment_DBWrapper comment_dbWrapper = this.getPortalBean().getComments();
String commentPara = request.getParameter("reply");
if(!"".equals(commentPara) && commentPara.trim().length() != 0){
Comment comment = new Comment();
comment.setIssueId(currentState.getIssueId());
comment.setUserId(this.getUser().getUserId());
comment.setComment(commentPara);
comment.setCreated(startDate);
if(this.getUser().isAdmin()){
comment.setPublic(Integer.parseInt(request.getParameter("public")) !=0);
}
else{
comment.setPublic(false);
}
//create new comment
comment_dbWrapper.createNewComment(comment); // it will throw null exceptions here
//update issue status
currentState.setStatus(Integer.parseInt(request.getParameter("status")));
issue_dbWrapper.updateIssue(currentState); //maybe here too
}
else {
response.sendRedirect(this.getBaseURL()+"issues/"+id);
}
}
//when the admin marks it as KB, there there will be no comment submitted
else {
currentState.setStatus(Integer.parseInt(request.getParameter("status")));
issue_dbWrapper.updateIssue(currentState);
}
response.sendRedirect(this.getBaseURL()+"issues");
}
else {
response.sendRedirect(this.getBaseURL()+"issues");
}
}
} |
package peergos.server.storage;
import static peergos.server.util.Logging.LOG;
import peergos.shared.crypto.hash.*;
import peergos.shared.io.ipfs.cid.*;
import peergos.shared.io.ipfs.multihash.*;
import peergos.shared.util.*;
import java.io.*;
import java.net.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;
/**
* A Utility for installing IPFS.
*/
public class IpfsInstaller {
public enum DownloadTarget {
DARWIN_386("https://github.com/peergos/ipfs-releases/blob/master/v0.4.20/darwin-386/ipfs?raw=true",
Cid.decode("Qma27kfXKiUvNquDyoEKHFM69gtGBDC9NDciFRnN9zo3zP")),
DARWIN_AMD64("https://github.com/peergos/ipfs-releases/blob/master/v0.4.20/darwin-amd64/ipfs?raw=true",
Cid.decode("QmTbC8c5454EyXCQwBR85xwfzSGGKKrrYqiXoKrygnm5K3")),
FREEBSD_386("https://github.com/peergos/ipfs-releases/blob/master/v0.4.20/freebsd-386/ipfs?raw=true",
Cid.decode("QmbXJAa1AGvZegsAXNk7b1TkaWjsuzo1u69ctK1DFqDLyx")),
FREEBSD_AMD64("https://github.com/peergos/ipfs-releases/blob/master/v0.4.20/freebsd-amd64/ipfs?raw=true",
Cid.decode("QmbZUER5uoGzUp9U3LNBq8urPaXy7muEiZ8r1kURWu1tQj")),
FREEBSD_ARM("https://github.com/peergos/ipfs-releases/blob/master/v0.4.20/freebsd-arm/ipfs?raw=true",
Cid.decode("QmbHemtrhayfLb9mqqEZx87rWuLP5qegi9dh5FXExkYsZa")),
LINUX_386("https://github.com/peergos/ipfs-releases/blob/master/v0.4.20/linux-386/ipfs?raw=true",
Cid.decode("QmVdsP7fD1gg8KaY4TD23PKKDAhFfgbX9Y3WaKpjgjAV1f")),
LINUX_AMD64("https://github.com/peergos/ipfs-releases/blob/master/v0.4.20/linux-amd64/ipfs?raw=true",
Cid.decode("QmUQiCjgjhCQayb7N1VxtuEYvaduEfbc6xjg7R56E6hdcp")),
LINUX_ARM("https://github.com/peergos/ipfs-releases/blob/master/v0.4.20/linux-arm/ipfs?raw=true",
Cid.decode("QmewfkEfLGqHtRJNU9MuTKwdYykCtMiEeAEVuSWSkNgJem")),
LINUX_ARM64("https://github.com/peergos/ipfs-releases/blob/master/v0.4.20/linux-arm64/ipfs?raw=true",
Cid.decode("QmRWqo1pZ6LgK7ne9KoyNB8wM9sqdvo38CojwLRMs1U244")),
WINDOWS_386("https://github.com/peergos/ipfs-releases/blob/master/v0.4.20/windows-386/ipfs.exe?raw=true",
Cid.decode("QmRqUTcaZiKengp3eTgUGhx69c7jroyxwKronp2uZvfYDT")),
WINDOWS_AMD64("https://github.com/peergos/ipfs-releases/blob/master/v0.4.20/windows-amd64/ipfs.exe?raw=true",
Cid.decode("Qmd7rUCrcADcGQ5GK6ewHUmAeeCpmsh4fiQUhHzcnQNnPG")),;
public final String url;
public final Multihash multihash;
DownloadTarget(String url, Multihash multihash) {
this.url = url;
this.multihash = multihash;
}
}
/**
* Ensure the ipfs executable is installed and that it's contents are correct.
*/
public static void ensureInstalled(Path targetFile) {
ensureInstalled(targetFile, getForPlatform());
}
public static void install(Path targetFile) {
install(targetFile, getForPlatform());
}
public static Path getExecutableForOS(Path targetFile) {
if (System.getProperty("os.name").toLowerCase().contains("windows"))
return targetFile.getParent().resolve(targetFile.getFileName() + ".exe");
return targetFile;
}
private static DownloadTarget getForPlatform() {
String os = canonicaliseOS(System.getProperty("os.name").toLowerCase());
String arch = canonicaliseArchitecture(System.getProperty("os.arch"));
String type = os + "_" + arch;
return DownloadTarget.valueOf(type.toUpperCase());
}
private static String canonicaliseArchitecture(String arch) {
System.out.println("Looking up architecture: " + arch);
if (arch.startsWith("arm64"))
return "arm64";
if (arch.startsWith("arm"))
return "arm";
if (arch.startsWith("x86_64"))
return "amd64";
if (arch.startsWith("x86"))
return "386";
return arch;
}
private static String canonicaliseOS(String os) {
System.out.println("Looking up OS: " + os);
if (os.startsWith("mac"))
return "darwin";
if (os.startsWith("windows"))
return "windows";
return os;
}
private static void ensureInstalled(Path targetFile, DownloadTarget downloadTarget) {
if (Files.exists(targetFile)) {
//check contents are correct
try {
byte[] raw = Files.readAllBytes(targetFile);
Multihash computed = new Multihash(Multihash.Type.sha2_256, Hash.sha256(raw));
if (computed.equals(downloadTarget.multihash)) {
//all present and correct
return;
}
LOG().info("Existing ipfs-exe " + targetFile + " has a different hash than expected, overwriting");
} catch (IOException ioe) {
throw new IllegalStateException(ioe.getMessage(), ioe);
}
}
else {
LOG().info("ipfs-exe "+ targetFile + " not available");
}
install(targetFile, downloadTarget);
}
private static void install(Path targetFile, DownloadTarget downloadTarget) {
try {
Path cacheFile = getLocalCacheDir().resolve(downloadTarget.multihash.toString());
if (cacheFile.toFile().exists()) {
LOG().info("Using cached IPFS "+ cacheFile);
byte[] raw = Files.readAllBytes(cacheFile);
Multihash computed = new Multihash(Multihash.Type.sha2_256, Hash.sha256(raw));
if (computed.equals(downloadTarget.multihash)) {
try {
Files.createSymbolicLink(targetFile, cacheFile);
} catch (Throwable t) {
// Windows requires extra privilege to symlink, so just copy it
Files.copy(cacheFile, targetFile);
}
targetFile.toFile().setExecutable(true);
return;
}
}
URI uri = new URI(downloadTarget.url);
LOG().info("Downloading IPFS binary "+ downloadTarget.url +"...");
byte[] raw = Serialize.readFully(uri.toURL().openStream());
Multihash computed = new Multihash(Multihash.Type.sha2_256, Hash.sha256(raw));
if (! computed.equals(downloadTarget.multihash))
throw new IllegalStateException("Incorrect hash for ipfs binary, aborting install!");
// save to local cache
cacheFile.getParent().toFile().mkdirs();
atomicallySaveToFile(cacheFile, raw);
LOG().info("Writing ipfs-binary to "+ targetFile);
try {
atomicallySaveToFile(targetFile, raw);
} catch (FileAlreadyExistsException e) {
boolean delete = targetFile.toFile().delete();
if (! delete)
throw new IllegalStateException("Couldn't delete old version of ipfs!");
atomicallySaveToFile(targetFile, raw);
}
targetFile.toFile().setExecutable(true);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static void atomicallySaveToFile(Path targetFile, byte[] data) throws IOException {
Path tempFile = Files.createTempFile("ipfs-temp-exe", "");
Files.write(tempFile, data);
try {
Files.move(tempFile, targetFile, StandardCopyOption.ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException ex) {
Files.move(tempFile, targetFile);
}
}
private static Path getLocalCacheDir() {
return Paths.get(System.getProperty("user.home"), ".cache");
}
public static void main(String[] args) throws Exception {
Path ipfsPath = Files.createTempFile("something", ".tmp");
System.out.println("ipfsPath "+ ipfsPath);
install(ipfsPath);
// codegen(Paths.get("/home/ian/ipfs-releases/v0.4.20"));
}
private static void codegen(Path root) throws Exception {
String urlBase = "https://github.com/peergos/ipfs-releases/blob/master/" + root.getFileName() + "/";
for (File arch: Arrays.asList(root.toFile().listFiles()).stream().sorted().collect(Collectors.toList())) {
for (File binary: arch.listFiles()) {
byte[] bytes = Files.readAllBytes(binary.toPath());
Multihash hash = new Multihash(Multihash.Type.sha2_256, Hash.sha256(bytes));
System.out.println(arch.getName().toUpperCase().replaceAll("-", "_")
+ "(\"" + urlBase + arch.getName() + "/" + binary.getName()
+ "?raw=true\", Cid.decode(\"" + hash + "\")),");
}
}
}
private static class ReleasePreparation {
public static void main(String[] a) throws Exception {
String version = "v0.4.20";
Path baseDir = Files.createTempDirectory("ipfs");
for (String os: Arrays.asList("linux", "windows", "darwin", "freebsd")) {
for (String arch: Arrays.asList("386", "amd64", "arm", "arm64")) {
String archive = os.equals("windows") ? "zip" : "tar.gz";
String filename = "go-ipfs_"+version+"_" + os + "-" + arch + "." + archive;
URI target = new URI("https://dist.ipfs.io/go-ipfs/"+version+"/" + filename);
Path archDir = baseDir.resolve(os + "-" + arch);
try {
archDir.toFile().mkdirs();
URLConnection conn = target.toURL().openConnection();
Path tarPath = archDir.resolve(filename);
System.out.printf("Downloading " + filename + " ...");
Files.write(tarPath, Serialize.readFully(conn.getInputStream()));
System.out.println("done");
ProcessBuilder pb = os.equals("windows") ?
new ProcessBuilder("unzip", filename) :
new ProcessBuilder("tar", "-xvzf", filename);
pb.directory(archDir.toFile());
Process proc = pb.start();
while (proc.isAlive())
Thread.sleep(100);
String executable = os.equals("windows") ? "ipfs.exe" : "ipfs";
byte[] bytes = Files.readAllBytes(archDir.resolve("go-ipfs").resolve(executable));
Multihash computed = new Multihash(Multihash.Type.sha2_256, Hash.sha256(bytes));
System.out.println(os + "-" + arch + "-" + computed);
} catch (FileNotFoundException e) {
archDir.toFile().delete();
// OS + arch combination doesn't exist
}
}
}
}
}
} |
package co.cdev.agave;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class ISO8601DateFormat extends SimpleDateFormat {
private static final long serialVersionUID = 1L;
private final Locale locale;
public ISO8601DateFormat(Locale locale) {
super("yyyy-MM-dd'T'HH:mm:ssZ", locale);
this.locale = locale;
super.setTimeZone(TimeZone.getTimeZone("UTC"));
}
@Override
public Date parse(String input) throws ParseException {
return (Date) parseObject(input);
}
@Override
public Object parseObject(String input) throws ParseException {
return parseObject(input, null);
}
@Override
public Object parseObject(String input, ParsePosition parsePosition) {
Date parsedDate = null;
if (input != null && !"".equals(input)) {
String formatString = null;
String actualInput = null;
String[] components = input.split("T");
if (components.length > 0) {
components[0] = components[0].replace("-", "");
if (components[0].contains("W")) {
// Date as year, week in year, day of week (starting with Monday as 1
// and ending with Sunday as 7
formatString = "yyyy'W'wwEEE";
actualInput = components[0].substring(0, 7);
DateFormatSymbols symbols = new DateFormatSymbols(locale);
int dayOfWeek = Integer.valueOf(components[0].substring(7, 8));
if (dayOfWeek == 1) {
actualInput += symbols.getWeekdays()[Calendar.MONDAY];
} else if (dayOfWeek == 2) {
actualInput += symbols.getWeekdays()[Calendar.TUESDAY];
} else if (dayOfWeek == 3) {
actualInput += symbols.getWeekdays()[Calendar.WEDNESDAY];
} else if (dayOfWeek == 4) {
actualInput += symbols.getWeekdays()[Calendar.THURSDAY];
} else if (dayOfWeek == 5) {
actualInput += symbols.getWeekdays()[Calendar.FRIDAY];
} else if (dayOfWeek == 6) {
actualInput += symbols.getWeekdays()[Calendar.SATURDAY];
} else if (dayOfWeek == 7) {
actualInput += symbols.getWeekdays()[Calendar.SUNDAY];
}
} else if (components[0].length() == 8) {
// Date as year, month, day
formatString = "yyyyMMdd";
actualInput = components[0];
} else if (components[0].length() == 7) {
// Date as year and day of year
formatString = "yyyyDDD";
actualInput = components[0];
}
if (formatString != null && actualInput != null) {
// Optional Time and Time Zone
if (components.length > 1) {
components[1] = components[1].replace(":", "");
components[1] = components[1].replace("Z", "");
String timePart = null;
String timeZonePart = null;
if (components[1].contains("+")) {
String[] timeComponents = components[1].split("\\+");
timePart = timeComponents[0];
timeZonePart = "+" + timeComponents[1];
} else if (components[1].contains("-")) {
String[] timeComponents = components[1].split("\\-");
timePart = timeComponents[0];
timeZonePart = "-" + timeComponents[1];
} else {
timePart = components[1];
}
// Time
if (timePart != null) {
while (timePart.length() < 4) {
timePart += "0";
}
if (timePart.length() > 6) {
timePart = timePart.substring(0, 6);
}
actualInput += timePart;
if (timePart.length() == 4) {
formatString += "HHmm";
} else if (timePart.length() == 6) {
formatString += "HHmmss";
}
// Time Zone
if (timeZonePart != null) {
if (timeZonePart.length() == 1) {
timeZonePart = null;
} else {
while (timeZonePart.length() < 5) {
timeZonePart += "0";
}
actualInput += timeZonePart;
formatString += "Z";
}
}
}
}
}
}
SimpleDateFormat format = new SimpleDateFormat(formatString);
try {
parsedDate = format.parse(actualInput);
parsedDate.setTime(parsedDate.getTime() / 1000 * 1000); // shave off milliseconds
} catch (ParseException e) {
// do nothing on invalid input
}
}
return parsedDate;
}
} |
package com.oney.WebRTCModule;
import android.Manifest;
import android.app.Application;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Handler;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableType;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.net.URISyntaxException;
import java.util.LinkedList;
import android.support.v4.content.ContextCompat;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.util.SparseArray;
import android.hardware.Camera;
import android.media.AudioManager;
import android.content.Context;
import android.view.Window;
import android.view.WindowManager;
import android.app.Activity;
import android.os.PowerManager;
import android.opengl.EGLContext;
import android.util.Log;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import org.webrtc.*;
import static android.content.Context.TELEPHONY_SERVICE;
public class WebRTCModule extends ReactContextBaseJavaModule {
private final static String TAG = WebRTCModule.class.getCanonicalName();
private static final String LANGUAGE = "language";
private PeerConnectionFactory mFactory;
private int mMediaStreamId = 0;
private int mMediaStreamTrackId = 0;
private static SparseArray<PeerConnection> mPeerConnections;
public final SparseArray<MediaStream> mMediaStreams;
public final SparseArray<MediaStreamTrack> mMediaStreamTracks;
private final SparseArray<DataChannel> mDataChannels;
private MediaConstraints pcConstraints = new MediaConstraints();
private VideoSource videoSource;
private VideoCapturerAndroid currentVideoCapturerAndroid;
private TelephonyManager tManager;
private CustomPhoneStateListener customPhoneStateListener;
public WebRTCModule(ReactApplicationContext reactContext) {
super(reactContext);
mPeerConnections = new SparseArray<PeerConnection>();
mMediaStreams = new SparseArray<MediaStream>();
mMediaStreamTracks = new SparseArray<MediaStreamTrack>();
mDataChannels = new SparseArray<DataChannel>();
pcConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"));
pcConstraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "true"));
pcConstraints.optional.add(new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"));
PeerConnectionFactory.initializeAndroidGlobals(reactContext, true, true, true);
mFactory = new PeerConnectionFactory();
}
@Override
public String getName() {
return "WebRTCModule";
}
private String getCurrentLanguage(){
Locale current = getReactApplicationContext().getResources().getConfiguration().locale;
return current.getLanguage();
}
@Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
constants.put(LANGUAGE, getCurrentLanguage());
return constants;
}
@ReactMethod
public void getLanguage(Callback callback){
String language = getCurrentLanguage();
System.out.println("The current language is "+language);
callback.invoke(null, language);
}
private void sendEvent(String eventName, @Nullable WritableMap params) {
getReactApplicationContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
}
private List<PeerConnection.IceServer> createIceServers(ReadableArray iceServersArray) {
LinkedList<PeerConnection.IceServer> iceServers = new LinkedList<>();
for (int i = 0; i < iceServersArray.size(); i++) {
ReadableMap iceServerMap = iceServersArray.getMap(i);
boolean hasUsernameAndCredential = iceServerMap.hasKey("username") && iceServerMap.hasKey("credential");
if (iceServerMap.hasKey("url")) {
if (hasUsernameAndCredential) {
iceServers.add(new PeerConnection.IceServer(iceServerMap.getString("url"),iceServerMap.getString("username"), iceServerMap.getString("credential")));
} else {
iceServers.add(new PeerConnection.IceServer(iceServerMap.getString("url")));
}
} else if (iceServerMap.hasKey("urls")) {
switch (iceServerMap.getType("urls")) {
case String:
if (hasUsernameAndCredential) {
iceServers.add(new PeerConnection.IceServer(iceServerMap.getString("urls"),iceServerMap.getString("username"), iceServerMap.getString("credential")));
} else {
iceServers.add(new PeerConnection.IceServer(iceServerMap.getString("urls")));
}
break;
case Array:
ReadableArray urls = iceServerMap.getArray("urls");
for (int j = 0; j < urls.size(); j++) {
String url = urls.getString(j);
if (hasUsernameAndCredential) {
iceServers.add(new PeerConnection.IceServer(url,iceServerMap.getString("username"), iceServerMap.getString("credential")));
} else {
iceServers.add(new PeerConnection.IceServer(url));
}
}
break;
}
}
}
return iceServers;
}
@ReactMethod
public void peerConnectionInit(ReadableMap configuration, final int id){
List<PeerConnection.IceServer> iceServers = createIceServers(configuration.getArray("iceServers"));
PeerConnection peerConnection = mFactory.createPeerConnection(iceServers, pcConstraints, new PeerConnection.Observer() {
@Override
public void onSignalingChange(PeerConnection.SignalingState signalingState) {
WritableMap params = Arguments.createMap();
params.putInt("id", id);
params.putString("signalingState", signalingStateString(signalingState));
sendEvent("peerConnectionSignalingStateChanged", params);
}
@Override
public void onIceConnectionChange(PeerConnection.IceConnectionState iceConnectionState) {
WritableMap params = Arguments.createMap();
params.putInt("id", id);
params.putString("iceConnectionState", iceConnectionStateString(iceConnectionState));
sendEvent("peerConnectionIceConnectionChanged", params);
}
@Override
public void onIceGatheringChange(PeerConnection.IceGatheringState iceGatheringState) {
Log.d(TAG, "onIceGatheringChangedwe" + iceGatheringState.name());
WritableMap params = Arguments.createMap();
params.putInt("id", id);
params.putString("iceGatheringState", iceGatheringStateString(iceGatheringState));
sendEvent("peerConnectionIceGatheringChanged", params);
}
@Override
public void onIceCandidate(final IceCandidate candidate) {
Log.d(TAG, "onIceCandidatewqerqwrsdfsd");
WritableMap params = Arguments.createMap();
params.putInt("id", id);
WritableMap candidateParams = Arguments.createMap();
candidateParams.putInt("sdpMLineIndex", candidate.sdpMLineIndex);
candidateParams.putString("sdpMid", candidate.sdpMid);
candidateParams.putString("candidate", candidate.sdp);
params.putMap("candidate", candidateParams);
sendEvent("peerConnectionGotICECandidate", params);
}
@Override
public void onAddStream(MediaStream mediaStream) {
mMediaStreamId++;
mMediaStreams.put(mMediaStreamId, mediaStream);
WritableMap params = Arguments.createMap();
params.putInt("id", id);
params.putInt("streamId", mMediaStreamId);
WritableArray tracks = Arguments.createArray();
for (int i = 0; i < mediaStream.videoTracks.size(); i++) {
VideoTrack track = mediaStream.videoTracks.get(i);
int mediaStreamTrackId = mMediaStreamTrackId++;
WritableMap trackInfo = Arguments.createMap();
trackInfo.putString("id", mediaStreamTrackId + "");
trackInfo.putString("label", "Video");
trackInfo.putString("kind", track.kind());
trackInfo.putBoolean("enabled", track.enabled());
trackInfo.putString("readyState", track.state().toString());
trackInfo.putBoolean("remote", true);
tracks.pushMap(trackInfo);
}
for (int i = 0; i < mediaStream.audioTracks.size(); i++) {
AudioTrack track = mediaStream.audioTracks.get(i);
int mediaStreamTrackId = mMediaStreamTrackId++;
WritableMap trackInfo = Arguments.createMap();
trackInfo.putString("id", mediaStreamTrackId + "");
trackInfo.putString("label", "Audio");
trackInfo.putString("kind", track.kind());
trackInfo.putBoolean("enabled", track.enabled());
trackInfo.putString("readyState", track.state().toString());
trackInfo.putBoolean("remote", true);
tracks.pushMap(trackInfo);
}
params.putArray("tracks", tracks);
sendEvent("peerConnectionAddedStream", params);
}
@Override
public void onRemoveStream(MediaStream mediaStream) {
if (mediaStream != null) {
int trackIndex;
int streamIndex;
for (int i = 0; i < mediaStream.videoTracks.size(); i++) {
VideoTrack track = mediaStream.videoTracks.get(i);
trackIndex = mMediaStreamTracks.indexOfValue(track);
while (trackIndex >= 0) {
mMediaStreamTracks.removeAt(trackIndex);
trackIndex = mMediaStreamTracks.indexOfValue(track);
}
}
for (int i = 0; i < mediaStream.audioTracks.size(); i++) {
AudioTrack track = mediaStream.audioTracks.get(i);
trackIndex = mMediaStreamTracks.indexOfValue(track);
while (trackIndex >= 0) {
mMediaStreamTracks.removeAt(trackIndex);
trackIndex = mMediaStreamTracks.indexOfValue(track);
}
}
streamIndex = mMediaStreams.indexOfValue(mediaStream);
if (streamIndex >= 0) {
mMediaStreams.removeAt(streamIndex);
}
}
}
@Override
public void onDataChannel(DataChannel dataChannel) {
}
@Override
public void onRenegotiationNeeded() {
WritableMap params = Arguments.createMap();
params.putInt("id", id);
sendEvent("peerConnectionOnRenegotiationNeeded", params);
}
@Override
public void onIceConnectionReceivingChange(boolean var1) {
}
});
mPeerConnections.put(id, peerConnection);
}
@ReactMethod
public void getUserMedia(ReadableMap constraints, Callback callback){
MediaStream mediaStream = mFactory.createLocalMediaStream("ARDAMS");
WritableArray tracks = Arguments.createArray();
if (constraints.hasKey("video")) {
ReadableType type = constraints.getType("video");
VideoSource videoSource = null;
MediaConstraints videoConstraints = new MediaConstraints();
switch (type) {
case Boolean:
boolean useVideo = constraints.getBoolean("video");
if (useVideo) {
String name = CameraEnumerationAndroid.getNameOfFrontFacingDevice();
VideoCapturerAndroid v = VideoCapturerAndroid.create(name, new VideoCapturerAndroid.CameraErrorHandler() {
@Override
public void onCameraError(String s) {
}
});
this.currentVideoCapturerAndroid = v;
videoSource = mFactory.createVideoSource(v, videoConstraints);
}
break;
case Map:
ReadableMap useVideoMap = constraints.getMap("video");
if (useVideoMap.hasKey("optional")) {
if (useVideoMap.getType("optional") == ReadableType.Array) {
ReadableArray options = useVideoMap.getArray("optional");
for (int i = 0; i < options.size(); i++) {
if (options.getType(i) == ReadableType.Map) {
ReadableMap option = options.getMap(i);
if (option.hasKey("sourceId") && option.getType("sourceId") == ReadableType.String) {
VideoCapturerAndroid v = getVideoCapturerById(Integer.parseInt(option.getString("sourceId")));
this.currentVideoCapturerAndroid = v;
videoSource = mFactory.createVideoSource(v, videoConstraints);
}
}
}
}
}
break;
}
// videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("maxHeight", Integer.toString(100)));
// videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("maxWidth", Integer.toString(100)));
// videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("maxFrameRate", Integer.toString(10)));
// videoConstraints.mandatory.add(new MediaConstraints.KeyValuePair("minFrameRate", Integer.toString(10)));
if (videoSource != null) {
VideoTrack videoTrack = mFactory.createVideoTrack("ARDAMSv0", videoSource);
int mediaStreamTrackId = mMediaStreamTrackId++;
mMediaStreamTracks.put(mediaStreamTrackId, videoTrack);
WritableMap trackInfo = Arguments.createMap();
trackInfo.putString("id", mediaStreamTrackId + "");
trackInfo.putString("label", "Video");
trackInfo.putString("kind", videoTrack.kind());
trackInfo.putBoolean("enabled", videoTrack.enabled());
trackInfo.putString("readyState", videoTrack.state().toString());
trackInfo.putBoolean("remote", false);
tracks.pushMap(trackInfo);
mediaStream.addTrack(videoTrack);
}
}
boolean useAudio = constraints.getBoolean("audio");
if (useAudio) {
MediaConstraints audioConstarints = new MediaConstraints();
audioConstarints.mandatory.add(new MediaConstraints.KeyValuePair("googNoiseSuppression", "true"));
audioConstarints.mandatory.add(new MediaConstraints.KeyValuePair("googEchoCancellation", "true"));
audioConstarints.mandatory.add(new MediaConstraints.KeyValuePair("echoCancellation", "true"));
audioConstarints.mandatory.add(new MediaConstraints.KeyValuePair("googEchoCancellation2", "true"));
audioConstarints.mandatory.add(new MediaConstraints.KeyValuePair("googDAEchoCancellation", "true"));
AudioSource audioSource = mFactory.createAudioSource(audioConstarints);
AudioTrack audioTrack = mFactory.createAudioTrack("ARDAMSa0", audioSource);
int mediaStreamTrackId = mMediaStreamTrackId++;
mMediaStreamTracks.put(mediaStreamTrackId, audioTrack);
WritableMap trackInfo = Arguments.createMap();
trackInfo.putString("id", mediaStreamTrackId + "");
trackInfo.putString("label", "Audio");
trackInfo.putString("kind", audioTrack.kind());
trackInfo.putBoolean("enabled", audioTrack.enabled());
trackInfo.putString("readyState", audioTrack.state().toString());
trackInfo.putBoolean("remote", false);
tracks.pushMap(trackInfo);
mediaStream.addTrack(audioTrack);
}
Log.d(TAG, "mMediaStreamId: " + mMediaStreamId);
mMediaStreamId++;
mMediaStreams.put(mMediaStreamId, mediaStream);
callback.invoke(mMediaStreamId, tracks);
}
@ReactMethod
public void mediaStreamTrackGetSources(Callback callback){
WritableArray array = Arguments.createArray();
String[] names = new String[Camera.getNumberOfCameras()];
for(int i = 0; i < Camera.getNumberOfCameras(); ++i) {
WritableMap info = getCameraInfo(i);
if (info != null) {
array.pushMap(info);
}
}
WritableMap audio = Arguments.createMap();
audio.putString("label", "Audio");
audio.putString("id", "audio-1");
audio.putString("facing", "");
audio.putString("kind", "audio");
array.pushMap(audio);
callback.invoke(array);
}
@ReactMethod
public void mediaStreamTrackStop(final String id) {
final int trackId = Integer.parseInt(id);
MediaStreamTrack track = mMediaStreamTracks.get(trackId, null);
if (track == null) {
Log.d(TAG, "mediaStreamTrackStop() track is null");
return;
}
track.setEnabled(false);
track.setState(MediaStreamTrack.State.ENDED);
mMediaStreamTracks.remove(trackId);
// what exaclty `detached` means in doc?
// see: https://www.w3.org/TR/mediacapture-streams/#track-detached
}
@ReactMethod
public void mediaStreamTrackSetEnabled(final String id, final boolean enabled) {
final int trackId = Integer.parseInt(id);
MediaStreamTrack track = mMediaStreamTracks.get(trackId, null);
if (track == null) {
Log.d(TAG, "mediaStreamTrackSetEnabled() track is null");
return;
} else if (track.enabled() == enabled) {
return;
}
track.setEnabled(enabled);
}
@ReactMethod
public void mediaStreamTrackRelease(final int streamId, final String _trackId) {
// TODO: need to normalize streamId as a string ( spec wanted )
//final int streamId = Integer.parseInt(_streamId);
final int trackId = Integer.parseInt(_trackId);
MediaStream stream = mMediaStreams.get(streamId, null);
if (stream == null) {
Log.d(TAG, "mediaStreamTrackRelease() stream is null");
return;
}
MediaStreamTrack track = mMediaStreamTracks.get(trackId, null);
if (track == null) {
Log.d(TAG, "mediaStreamTrackRelease() track is null");
return;
}
track.setEnabled(false); // should we do this?
track.setState(MediaStreamTrack.State.ENDED); // should we do this?
mMediaStreamTracks.remove(trackId);
if (track.kind().equals("audio")) {
stream.removeTrack((AudioTrack)track);
} else if (track.kind().equals("video")) {
stream.removeTrack((VideoTrack)track);
}
}
public WritableMap getCameraInfo(int index) {
CameraInfo info = new CameraInfo();
try {
Camera.getCameraInfo(index, info);
} catch (Exception var3) {
Logging.e("CameraEnumerationAndroid", "getCameraInfo failed on index " + index, var3);
return null;
}
WritableMap params = Arguments.createMap();
String facing = info.facing == 1 ? "front" : "back";
params.putString("label", "Camera " + index + ", Facing " + facing + ", Orientation " + info.orientation);
params.putString("id", "" + index);
params.putString("facing", facing);
params.putString("kind", "video");
return params;
}
private VideoCapturerAndroid getVideoCapturerById(int id) {
String name = CameraEnumerationAndroid.getDeviceName(id);
if (name == null) {
name = CameraEnumerationAndroid.getNameOfFrontFacingDevice();
}
return VideoCapturerAndroid.create(name, new VideoCapturerAndroid.CameraErrorHandler() {
@Override
public void onCameraError(String s) {
}
});
}
private MediaConstraints defaultConstraints() {
MediaConstraints constraints = new MediaConstraints();
// TODO video media
constraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"));
constraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "true"));
constraints.optional.add(new MediaConstraints.KeyValuePair("DtlsSrtpKeyAgreement", "true"));
return constraints;
}
@ReactMethod
public void peerConnectionAddStream(final int streamId, final int id){
MediaStream mediaStream = mMediaStreams.get(streamId, null);
if (mediaStream == null) {
Log.d(TAG, "peerConnectionAddStream() mediaStream is null");
return;
}
PeerConnection peerConnection = mPeerConnections.get(id, null);
if (peerConnection != null) {
boolean result = peerConnection.addStream(mediaStream);
Log.d(TAG, "addStream" + result);
} else {
Log.d(TAG, "peerConnectionAddStream() peerConnection is null");
}
}
@ReactMethod
public void peerConnectionRemoveStream(final int streamId, final int id){
MediaStream mediaStream = mMediaStreams.get(streamId, null);
if (mediaStream == null) {
Log.d(TAG, "peerConnectionRemoveStream() mediaStream is null");
return;
}
PeerConnection peerConnection = mPeerConnections.get(id, null);
if (peerConnection != null) {
peerConnection.removeStream(mediaStream);
} else {
Log.d(TAG, "peerConnectionRemoveStream() peerConnection is null");
}
}
@ReactMethod
public void switchCameras() {
this.currentVideoCapturerAndroid.switchCamera(new VideoCapturerAndroid.CameraSwitchHandler() {
@Override
public void onCameraSwitchDone(boolean b) {
Log.d("SWITCHCAMERA", "Successfully Switched Cameras");
}
@Override
public void onCameraSwitchError(String s) {
Log.d("SWITCHCAMERA", "There was an error switching cameras");
}
});
}
@ReactMethod
public void toggleMute() {
Log.d("INTOGGLEMUTE", mMediaStreams.get(1).toString());
MediaStream mediaStream = mMediaStreams.get(1);
LinkedList<AudioTrack> audioTracks = mediaStream.audioTracks;
for (AudioTrack aAudioTrack : audioTracks) {
if (aAudioTrack.enabled()) {
aAudioTrack.setEnabled(false);
} else {
aAudioTrack.setEnabled(true);
}
}
}
@ReactMethod
public void toggleCamera() {
Log.d("INTOGGLECAMERA", mMediaStreams.get(1).toString());
MediaStream mediaStream = mMediaStreams.get(1);
LinkedList<VideoTrack> videoTracks = mediaStream.videoTracks;
boolean isCameraEnabled = false;
for (VideoTrack aVideoTrack : videoTracks) {
if (aVideoTrack.enabled()) {
aVideoTrack.setEnabled(false);
} else {
aVideoTrack.setEnabled(true);
}
}
}
@ReactMethod
public String getDeviceCameraAccessibilityOld() {
String cameraStatus = new String("cameraStatus_Authorized");
Camera camera = null;
try {
camera = Camera.open();
} catch (RuntimeException e) {
cameraStatus = "denied";
} finally {
if (camera != null) camera.release();
}
return cameraStatus;
}
@ReactMethod
public String getDeviceMicrophoneAccessibilityOld() {
String microphoneStatus = new String("microphoneStatus_Authorized");
AudioRecord recorder =new AudioRecord(
MediaRecorder.AudioSource.MIC, 44100,
AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_DEFAULT, 44100);
try {
if (recorder.getRecordingState() != AudioRecord.RECORDSTATE_STOPPED) {
microphoneStatus = "denied";
}
recorder.startRecording();
if (recorder.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) {
recorder.stop();
microphoneStatus = "denied";
}
recorder.stop();
} finally {
recorder.release();
recorder = null;
}
return microphoneStatus;
}
@ReactMethod
public void getDeviceCameraAccessibility(final Callback callback) {
// Assume thisActivity is the current activity
int permissionCheck = ContextCompat.checkSelfPermission(this.getCurrentActivity(),
Manifest.permission.CAMERA);
if(PackageManager.PERMISSION_DENIED == permissionCheck){
callback.invoke(false);
}else if(PackageManager.PERMISSION_GRANTED == permissionCheck) {
callback.invoke(true);
}
}
@ReactMethod
public void getDeviceMicrophoneAccessibility(final Callback callback) {
// Assume thisActivity is the current activity
int permissionCheck = ContextCompat.checkSelfPermission(this.getCurrentActivity(),
Manifest.permission.RECORD_AUDIO);
if(PackageManager.PERMISSION_DENIED == permissionCheck){
callback.invoke(false);
}else if(PackageManager.PERMISSION_GRANTED == permissionCheck) {
callback.invoke(true);
}
}
@ReactMethod
public void getDeviceFileReadAccessibility(final Callback callback) {
// Assume thisActivity is the current activity
int permissionCheck = ContextCompat.checkSelfPermission(this.getCurrentActivity(),
Manifest.permission.READ_EXTERNAL_STORAGE);
if(PackageManager.PERMISSION_DENIED == permissionCheck){
callback.invoke(false);
}else if(PackageManager.PERMISSION_GRANTED == permissionCheck) {
callback.invoke(true);
}
}
@ReactMethod
public void getDeviceFileWriteAccessibility(final Callback callback) {
// Assume thisActivity is the current activity
int permissionCheck = ContextCompat.checkSelfPermission(this.getCurrentActivity(),
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if(PackageManager.PERMISSION_DENIED == permissionCheck){
callback.invoke(false);
}else if(PackageManager.PERMISSION_GRANTED == permissionCheck) {
callback.invoke(true);
}
}
@ReactMethod
public void releaseCameraAndMicroPhone() {
if (mMediaStreams != null) {
while (mMediaStreamId >= 0) {
MediaStream mediaStream = mMediaStreams.get(mMediaStreamId);
LinkedList<VideoTrack> videoTracks = mediaStream.videoTracks;
LinkedList<AudioTrack> audioTracks = mediaStream.audioTracks;
if (videoTracks != null) {
for (VideoTrack v : videoTracks) {
int trackIndex = mMediaStreamTracks.indexOfValue(v);
v.dispose();
mMediaStreamTracks.remove(trackIndex);
mediaStream.removeTrack(v);
}
}
if (audioTracks != null) {
for (AudioTrack a : audioTracks) {
int trackIndex = mMediaStreamTracks.indexOfValue(a);
a.dispose();
mMediaStreamTracks.remove(trackIndex);
mediaStream.removeTrack(a);
}
}
}
}
for (int i = 0; i < mPeerConnections.size(); i++) {
int index = mPeerConnections.keyAt(i);
PeerConnection p = mPeerConnections.valueAt(index);
p.dispose();
}
}
public static void changeBandwidthResolution(int bandWidth) {
if (WebRTCModule.mPeerConnections != null) {
final PeerConnection peerConnection = WebRTCModule.mPeerConnections.get(0);
if (peerConnection != null) {
SessionDescription oldLocalDescription = peerConnection.getLocalDescription();
SessionDescription oldRemoteDescription = peerConnection.getRemoteDescription();
StringBuilder sbLocal = null;
StringBuilder sbRemote = null;
if (oldLocalDescription != null) {
String stringOldLocalDescription = oldLocalDescription.description;
sbLocal = new StringBuilder(stringOldLocalDescription);
int indexOfLocalVideo = sbLocal.indexOf("m=video");
int indexOfLocalFirstA = sbLocal.indexOf("a=rtcp", indexOfLocalVideo);
if (!stringOldLocalDescription.contains("b=AS")) {
sbLocal.insert(indexOfLocalFirstA, "b=AS:" + bandWidth + "\n"
+ "b=RS:"+bandWidth+"\n"
+ "b=RR:"+bandWidth+"\n");
}
}
if (oldRemoteDescription != null) {
Log.d("OLD_REMOTE_SDP", oldRemoteDescription.description);
String stringOldRemoteDescription = oldRemoteDescription.description;
sbRemote = new StringBuilder(stringOldRemoteDescription);
int indexOfRemoteVideo = sbRemote.indexOf("m=video");
int indexOfRemoteFirstA = sbRemote.indexOf("a=rtcp", indexOfRemoteVideo);
if (!stringOldRemoteDescription.contains("b=AS")) {
sbRemote.insert(indexOfRemoteFirstA, "b=AS:" + bandWidth + "\n"
+ "b=RS:"+bandWidth+"\n"
+ "b=RR:"+bandWidth+"\n");
}
}
if (sbLocal != null && sbRemote != null) {
final SessionDescription newLocalDescription = new SessionDescription(SessionDescription.Type.OFFER, sbLocal.toString());
final SessionDescription newRemoteDescription = new SessionDescription(SessionDescription.Type.ANSWER, sbRemote.toString());
peerConnection.setLocalDescription(new SdpObserver() {
@Override
public void onCreateSuccess(SessionDescription sessionDescription) {
}
@Override
public void onSetSuccess() {
Log.d("NEW_AFTER_LOCAL_SDP", newLocalDescription.description);
peerConnection.setRemoteDescription(new SdpObserver() {
@Override
public void onCreateSuccess(SessionDescription sessionDescription) {
}
@Override
public void onSetSuccess() {
Log.d("NEW_AFTER_REMOTE_SDP", newRemoteDescription.description);
}
@Override
public void onCreateFailure(String s) {
}
@Override
public void onSetFailure(String s) {
}
}, newRemoteDescription);
}
@Override
public void onCreateFailure(String s) {
}
@Override
public void onSetFailure(String s) {
}
}, newLocalDescription);
}
}
}
}
@ReactMethod
public void setSignalStrengthListener(){
this.tManager = (TelephonyManager) this.getCurrentActivity().getSystemService(TELEPHONY_SERVICE);
this.customPhoneStateListener = new CustomPhoneStateListener(this.getReactApplicationContext());
tManager.listen(this.customPhoneStateListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
this.customPhoneStateListener.myTimer.scheduleAtFixedRate(this.customPhoneStateListener.myTimerTask, 0, 5000);
}
@ReactMethod
public void removeSignalStrengthListener(){
this.tManager = (TelephonyManager) this.getCurrentActivity().getSystemService(TELEPHONY_SERVICE);
tManager.listen(this.customPhoneStateListener, PhoneStateListener.LISTEN_NONE);
this.customPhoneStateListener.myTimerTask.cancel();
this.customPhoneStateListener.myTimer.cancel();
this.customPhoneStateListener.myTimer.purge();
}
@ReactMethod
public void peerConnectionCreateOffer(final int id, final Callback callback) {
PeerConnection peerConnection = mPeerConnections.get(id, null);
// MediaConstraints constraints = new MediaConstraints();
// constraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"));
// constraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "false"));
Log.d(TAG, "RTCPeerConnectionCreateOfferWithObjectID start");
if (peerConnection != null) {
peerConnection.createOffer(new SdpObserver() {
@Override
public void onCreateSuccess(final SessionDescription sdp) {
WritableMap params = Arguments.createMap();
params.putString("type", sdp.type.canonicalForm());
params.putString("sdp", sdp.description);
callback.invoke(true, params);
}
@Override
public void onSetSuccess() {}
@Override
public void onCreateFailure(String s) {
callback.invoke(false, s);
}
@Override
public void onSetFailure(String s) {}
}, pcConstraints);
} else {
Log.d(TAG, "peerConnectionCreateOffer() peerConnection is null");
callback.invoke(false, "peerConnection is null");
}
Log.d(TAG, "RTCPeerConnectionCreateOfferWithObjectID end");
}
@ReactMethod
public void peerConnectionCreateAnswer(final int id, final Callback callback) {
PeerConnection peerConnection = mPeerConnections.get(id, null);
// MediaConstraints constraints = new MediaConstraints();
// constraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveAudio", "true"));
// constraints.mandatory.add(new MediaConstraints.KeyValuePair("OfferToReceiveVideo", "false"));
Log.d(TAG, "RTCPeerConnectionCreateAnswerWithObjectID start");
if (peerConnection != null) {
peerConnection.createAnswer(new SdpObserver() {
@Override
public void onCreateSuccess(final SessionDescription sdp) {
WritableMap params = Arguments.createMap();
params.putString("type", sdp.type.canonicalForm());
params.putString("sdp", sdp.description);
callback.invoke(true, params);
}
@Override
public void onSetSuccess() {
}
@Override
public void onCreateFailure(String s) {
callback.invoke(false, s);
}
@Override
public void onSetFailure(String s) {
}
}, pcConstraints);
} else {
Log.d(TAG, "peerConnectionCreateAnswer() peerConnection is null");
callback.invoke(false, "peerConnection is null");
}
Log.d(TAG, "RTCPeerConnectionCreateAnswerWithObjectID end");
}
@ReactMethod
public void peerConnectionSetLocalDescription(ReadableMap sdpMap, final int id, final Callback callback) {
PeerConnection peerConnection = mPeerConnections.get(id, null);
Log.d(TAG, "peerConnectionSetLocalDescription() start");
if (peerConnection != null) {
SessionDescription sdp = new SessionDescription(
SessionDescription.Type.fromCanonicalForm(sdpMap.getString("type")),
sdpMap.getString("sdp")
);
peerConnection.setLocalDescription(new SdpObserver() {
@Override
public void onCreateSuccess(final SessionDescription sdp) {
}
@Override
public void onSetSuccess() {
callback.invoke(true);
}
@Override
public void onCreateFailure(String s) {
}
@Override
public void onSetFailure(String s) {
callback.invoke(false, s);
}
}, sdp);
} else {
Log.d(TAG, "peerConnectionSetLocalDescription() peerConnection is null");
callback.invoke(false, "peerConnection is null");
}
Log.d(TAG, "peerConnectionSetLocalDescription() end");
}
@ReactMethod
public void peerConnectionSetRemoteDescription(final ReadableMap sdpMap, final int id, final Callback callback) {
PeerConnection peerConnection = mPeerConnections.get(id, null);
// final String d = sdpMap.getString("type");
Log.d(TAG, "peerConnectionSetRemoteDescription() start");
if (peerConnection != null) {
SessionDescription sdp = new SessionDescription(
SessionDescription.Type.fromCanonicalForm(sdpMap.getString("type")),
sdpMap.getString("sdp")
);
peerConnection.setRemoteDescription(new SdpObserver() {
@Override
public void onCreateSuccess(final SessionDescription sdp) {
}
@Override
public void onSetSuccess() {
callback.invoke(true);
}
@Override
public void onCreateFailure(String s) {
}
@Override
public void onSetFailure(String s) {
callback.invoke(false, s);
}
}, sdp);
} else {
Log.d(TAG, "peerConnectionSetRemoteDescription() peerConnection is null");
callback.invoke(false, "peerConnection is null");
}
Log.d(TAG, "peerConnectionSetRemoteDescription() end");
}
@ReactMethod
public void peerConnectionAddICECandidate(ReadableMap candidateMap, final int id, final Callback callback) {
boolean result = false;
PeerConnection peerConnection = mPeerConnections.get(id, null);
Log.d(TAG, "peerConnectionAddICECandidate() start");
if (peerConnection != null) {
IceCandidate candidate = new IceCandidate(
candidateMap.getString("sdpMid"),
candidateMap.getInt("sdpMLineIndex"),
candidateMap.getString("candidate")
);
result = peerConnection.addIceCandidate(candidate);
} else {
Log.d(TAG, "peerConnectionAddICECandidate() peerConnection is null");
}
callback.invoke(result);
Log.d(TAG, "peerConnectionAddICECandidate() end");
}
@ReactMethod
public void peerConnectionClose(final int id) {
PeerConnection peerConnection = mPeerConnections.get(id, null);
if (peerConnection != null) {
peerConnection.close();
mPeerConnections.remove(id);
} else {
Log.d(TAG, "peerConnectionClose() peerConnection is null");
}
resetAudio();
}
@ReactMethod
public void mediaStreamRelease(final int id) {
MediaStream mediaStream = mMediaStreams.get(id, null);
if (mediaStream != null) {
int trackIndex;
for (int i = 0; i < mediaStream.videoTracks.size(); i++) {
VideoTrack track = mediaStream.videoTracks.get(i);
trackIndex = mMediaStreamTracks.indexOfValue(track);
while (trackIndex >= 0) {
mMediaStreamTracks.removeAt(trackIndex);
trackIndex = mMediaStreamTracks.indexOfValue(track);
}
}
for (int i = 0; i < mediaStream.audioTracks.size(); i++) {
AudioTrack track = mediaStream.audioTracks.get(i);
trackIndex = mMediaStreamTracks.indexOfValue(track);
while (trackIndex >= 0) {
mMediaStreamTracks.removeAt(trackIndex);
trackIndex = mMediaStreamTracks.indexOfValue(track);
}
}
mMediaStreams.remove(id);
} else {
Log.d(TAG, "mediaStreamRelease() mediaStream is null");
}
}
private void resetAudio() {
AudioManager audioManager = (AudioManager)getReactApplicationContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setSpeakerphoneOn(true);
audioManager.setMode(AudioManager.MODE_NORMAL);
}
@ReactMethod
public void setAudioOutput(String output) {
AudioManager audioManager = (AudioManager)getReactApplicationContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setMode(AudioManager.MODE_IN_CALL);
audioManager.setSpeakerphoneOn(output.equals("speaker"));
}
@ReactMethod
public void setKeepScreenOn(final boolean isOn) {
UiThreadUtil.runOnUiThread(new Runnable() {
public void run() {
Window window = getCurrentActivity().getWindow();
if (isOn) {
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
});
}
@ReactMethod
public void setProximityScreenOff(boolean enabled) {
// TODO
/*
PowerManager powerManager = (PowerManager)getReactApplicationContext().getSystemService(Context.POWER_SERVICE);
if (powerManager.isWakeLockLevelSupported(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)) {
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, TAG);
wakeLock.setReferenceCounted(false);
} else {
}*/
}
@ReactMethod
public void dataChannelInit(final int peerConnectionId, final int dataChannelId, String label, ReadableMap config) {
PeerConnection peerConnection = mPeerConnections.get(peerConnectionId, null);
if (peerConnection != null) {
DataChannel.Init init = new DataChannel.Init();
init.id = dataChannelId;
if (config != null) {
if (config.hasKey("ordered")) {
init.ordered = config.getBoolean("ordered");
}
if (config.hasKey("maxRetransmitTime")) {
init.maxRetransmitTimeMs = config.getInt("maxRetransmitTime");
}
if (config.hasKey("maxRetransmits")) {
init.maxRetransmits = config.getInt("maxRetransmits");
}
if (config.hasKey("protocol")) {
init.protocol = config.getString("protocol");
}
if (config.hasKey("negotiated")) {
init.ordered = config.getBoolean("negotiated");
}
}
DataChannel dataChannel = peerConnection.createDataChannel(label, init);
mDataChannels.put(dataChannelId, dataChannel);
} else {
Log.d(TAG, "dataChannelInit() peerConnection is null");
}
}
@ReactMethod
public void dataChannelSend(final int dataChannelId, String data, String type) {
DataChannel dataChannel = mDataChannels.get(dataChannelId, null);
if (dataChannel != null) {
byte[] byteArray;
if (type.equals("text")) {
try {
byteArray = data.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
Log.d(TAG, "Could not encode text string as UTF-8.");
return;
}
} else if (type.equals("binary")) {
byteArray = Base64.decode(data, Base64.NO_WRAP);
} else {
Log.e(TAG, "Unsupported data type: " + type);
return;
}
ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray);
DataChannel.Buffer buffer = new DataChannel.Buffer(byteBuffer, type.equals("binary"));
dataChannel.send(buffer);
} else {
Log.d(TAG, "dataChannelSend() dataChannel is null");
}
}
@ReactMethod
public void dataChannelClose(final int dataChannelId) {
DataChannel dataChannel = mDataChannels.get(dataChannelId, null);
if (dataChannel != null) {
dataChannel.close();
mDataChannels.remove(dataChannelId);
} else {
Log.d(TAG, "dataChannelClose() dataChannel is null");
}
}
@Nullable
public String iceConnectionStateString(PeerConnection.IceConnectionState iceConnectionState) {
switch (iceConnectionState) {
case NEW:
return "new";
case CHECKING:
return "checking";
case CONNECTED:
return "connected";
case COMPLETED:
return "completed";
case FAILED:
return "failed";
case DISCONNECTED:
return "disconnected";
case CLOSED:
return "closed";
}
return null;
}
@Nullable
public String signalingStateString(PeerConnection.SignalingState signalingState) {
switch (signalingState) {
case STABLE:
return "stable";
case HAVE_LOCAL_OFFER:
return "have-local-offer";
case HAVE_LOCAL_PRANSWER:
return "have-local-pranswer";
case HAVE_REMOTE_OFFER:
return "have-remote-offer";
case HAVE_REMOTE_PRANSWER:
return "have-remote-pranswer";
case CLOSED:
return "closed";
}
return null;
}
@Nullable
public String iceGatheringStateString(PeerConnection.IceGatheringState iceGatheringState) {
switch (iceGatheringState) {
case NEW:
return "new";
case GATHERING:
return "gathering";
case COMPLETE:
return "complete";
}
return null;
}
@Nullable
public String dataChannelStateString(DataChannel.State dataChannelState) {
switch (dataChannelState) {
case CONNECTING:
return "connecting";
case OPEN:
return "open";
case CLOSING:
return "closing";
case CLOSED:
return "closed";
}
return null;
}
} |
package ar.ext.spark;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import ar.Aggregates;
import ar.Aggregator;
import ar.Glyph;
import ar.aggregates.FlatAggregates;
import ar.glyphsets.implicitgeometry.Indexed;
import ar.glyphsets.implicitgeometry.Shaper;
import ar.glyphsets.implicitgeometry.Valuer;
import spark.api.java.JavaRDD;
import spark.api.java.function.Function;
//TODO: Implement the Renderer interface...probably will require some construction params to do it right
public class RDDRender {
/* Glyphset: (DONE)
* Node-local object.
* Can be a "parallelizedCollection" for now,
* Keep an idea on "Hadoop dataset" for actual usage with shark/hive tables
* sc.parallelize(<collection>)
* Transform raw dataset into glyphset via map (of a glypher and a valuer)
*/
public static <V> JavaRDD<Glyph<V>> glyphs(JavaRDD<Indexed> baseData,
Shaper<Indexed> shaper,
Valuer<Indexed,V> valuer) {
JavaRDD<Glyph<V>> glyphs = baseData.map(new Glypher(shaper,valuer));
return glyphs;
}
/**Render a single glyph.
*
* Takes a single glyph and creates a set of aggregates, basically
* splats the value into the bounding box.
*
* TODO: Put value into just cells the bounding box touches
*
* **/
public static class RenderOne<V> extends Function<Glyph<V>, Aggregates<V>> {
private static final long serialVersionUID = 7666400467739718445L;
private final AffineTransform vt;
public RenderOne(AffineTransform vt) {this.vt = vt;}
public Aggregates<V> call(Glyph<V> glyph) throws Exception {
Shape s = vt.createTransformedShape(glyph.shape());
Rectangle bounds =s.getBounds();
V v = glyph.value();
Aggregates<V> aggs = new FlatAggregates<V>(bounds.x, bounds.y, bounds.x+bounds.width, bounds.y+bounds.height, v);
return aggs;
}
}
public static <V> JavaRDD<Aggregates<V>> renderAll(AffineTransform vt, JavaRDD<Glyph<V>> glyphs) {
return glyphs.map(new RenderOne<V>(vt));
}
public static <V> Aggregates<V> collect(JavaRDD<Aggregates<V>> aggs, Aggregator<?,V> aggregator) {
return aggs.reduce(new Rollup<V>(aggregator));
}
} |
package io.sidecar.client;
import static com.google.common.base.Throwables.propagate;
import static io.sidecar.security.signature.SignatureVersion.Version.ONE;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.sidecar.access.AccessKey;
import io.sidecar.credential.Credential;
import io.sidecar.event.Event;
import io.sidecar.jackson.ModelMapper;
import io.sidecar.notification.NotificationRule;
import io.sidecar.org.Device;
import io.sidecar.org.PlatformDeviceToken;
import io.sidecar.org.Role;
import io.sidecar.org.UserGroup;
import io.sidecar.org.UserGroupMember;
import io.sidecar.query.Query;
import io.sidecar.query.UserAnswerBucket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings("unused")
public class SidecarClient {
private static final Logger LOGGER = LoggerFactory.getLogger(SidecarClient.class);
private final ClientConfig clientConfig;
private final AccessKey accessKey;
private final ModelMapper mapper = new ModelMapper();
@SuppressWarnings("unused")
public SidecarClient(AccessKey accessKey) {
this(accessKey, new ClientConfig());
}
public SidecarClient(AccessKey accessKey, ClientConfig clientConfig) {
this.accessKey = accessKey;
this.clientConfig = clientConfig;
}
/**
* Given a username and password, obtain that user's AccessKey's for this application if that user exists.
*
* @param credential The user's credentials.
* @return AccessKeys for the user identified by the provided Credentials
*/
@SuppressWarnings("unused")
public AccessKey authenticateUser(Credential credential) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/application/auth");
SidecarPostRequest sidecarPostRequest = new SidecarPostRequest.Builder(
accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(credential)
.build();
SidecarResponse response = sidecarPostRequest.send();
if (response.getStatusCode() == 200) {
LOGGER.debug(response.getBody());
return mapper.readValue(response.getBody(), AccessKey.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
public boolean checkApplicationKeyset() {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/application/status");
SidecarGetRequest sidecarGetRequest =
new SidecarGetRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarGetRequest.send();
return response.getStatusCode() == 200;
} catch (Exception e) {
throw propagate(e);
}
}
public boolean checkUserKeyset() {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/status");
SidecarGetRequest sidecarGetRequest =
new SidecarGetRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarGetRequest.send();
return response.getStatusCode() == 200;
} catch (Exception e) {
throw propagate(e);
}
}
public UUID postEvent(Event event) {
try {
URL endpoint = fullUrlForPath("/rest/v1/event");
SidecarPostRequest sidecarPostRequest = new SidecarPostRequest.Builder(
accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(event)
.build();
SidecarResponse response = sidecarPostRequest.send();
if (response.getStatusCode() == 202) {
String s = response.getBody();
JsonNode json = mapper.readTree(s);
System.out.println(json);
return UUID.fromString(json.path("id").asText());
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
// User...
@SuppressWarnings("unused")
public AccessKey createNewUser(String emailAddress, String password) {
try {
Credential credential = new Credential(emailAddress, password);
URL endpoint = fullUrlForPath("/rest/v1/provision/application/user");
SidecarPostRequest sidecarRequest =
new SidecarPostRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withUrl(endpoint)
.withSignatureVersion(ONE)
.withPayload(credential)
.build();
SidecarResponse response = sidecarRequest.send();
if (response.getStatusCode() == 200) {
return mapper.readValue(response.getBody(), AccessKey.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public void deleteUser(String emailAddress, String password) {
try {
Credential credential = new Credential(emailAddress, password);
URL endpoint = fullUrlForPath("/rest/v1/provision/application/user");
SidecarDeleteRequest sidecarRequest =
new SidecarDeleteRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withUrl(endpoint)
.withSignatureVersion(ONE)
.withPayload(credential)
.build();
SidecarResponse response = sidecarRequest.send();
// check for an no content response code
if (response.getStatusCode() != 204) {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public AccessKey createAccessKeyForUser(String emailAddress, String password) {
try {
Credential credential = new Credential(emailAddress, password);
URL endpoint = fullUrlForPath("/rest/v1/provision/application/accesskey");
SidecarPostRequest sidecarRequest =
new SidecarPostRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withUrl(endpoint)
.withSignatureVersion(ONE)
.withPayload(credential)
.build();
SidecarResponse response = sidecarRequest.send();
if (response.getStatusCode() == 200) {
return mapper.readValue(response.getBody(), AccessKey.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public AccessKey updateAccessKeyForUser(String emailAddress, String password) {
try {
Credential credential = new Credential(emailAddress, password);
URL endpoint = fullUrlForPath("/rest/v1/provision/application/accesskey");
SidecarPutRequest sidecarPutRequest =
new SidecarPutRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(credential)
.build();
SidecarResponse response = sidecarPutRequest.send();
if (response.getStatusCode() == 200) {
return mapper.readValue(response.getBody(), AccessKey.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public void updateUserMetadata(Map<String, String> metaData) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user");
SidecarPutRequest sidecarPutRequest =
new SidecarPutRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(metaData)
.build();
SidecarResponse response = sidecarPutRequest.send();
if (response.getStatusCode() != 204) {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public Map<String, String> getUserMetadata() {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user");
SidecarGetRequest sidecarGetRequest =
new SidecarGetRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarGetRequest.send();
if (response.getStatusCode() == 200) {
return mapper.readValue(response.getBody(), Map.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public UUID userIdForUserAddress(String emailAddress) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/" + emailAddress);
SidecarGetRequest sidecarGetRequest =
new SidecarGetRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarGetRequest.send();
if (response.getStatusCode() == 200) {
return UUID
.fromString(mapper.readTree(response.getBody()).get("userId").textValue());
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
// Group....
@SuppressWarnings("unused")
public UserGroup createNewUserGroup(String newGroupName) {
try {
HashMap<String, String> payload = new HashMap<>();
payload.put("name", newGroupName);
URL endpoint = fullUrlForPath("/rest/v1/provision/group");
SidecarPostRequest
sidecarPostRequest =
new SidecarPostRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(payload)
.build();
SidecarResponse response = sidecarPostRequest.send();
if (response.getStatusCode() == 200) {
return mapper.readValue(response.getBody(), UserGroup.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public UserGroup getGroupById(UUID groupId) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/group/" + groupId.toString());
SidecarGetRequest
sidecarGetRequest =
new SidecarGetRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarGetRequest.send();
if (response.getStatusCode() == 200) {
return mapper.readValue(response.getBody(), UserGroup.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public void deleteGroup(UUID groupId) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/group/" + groupId.toString());
SidecarDeleteRequest sidecarRequest =
new SidecarDeleteRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withUrl(endpoint)
.withSignatureVersion(ONE)
.build();
SidecarResponse response = sidecarRequest.send();
if (response.getStatusCode() != 204) {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public UserGroup addUserToUserGroup(UserGroup userGroup, UserGroupMember member) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/group/" + userGroup.getId() + "/members");
SidecarPostRequest sidecarPostRequest =
new SidecarPostRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(member)
.build();
SidecarResponse response = sidecarPostRequest.send();
if (response.getStatusCode() == 200) {
return mapper.readValue(response.getBody(), UserGroup.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings({"unchecked", "unused"})
public List<UUID> getGroupMembers(UUID groupId) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/group/" + groupId.toString() + "/members");
SidecarGetRequest sidecarGetRequest =
new SidecarGetRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarGetRequest.send();
if (response.getStatusCode() == 200) {
return Collections.checkedList(mapper.readValue(response.getBody(), List.class), UUID.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
public UserGroup removeMemberFromGroup(UserGroup group, UUID userId) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/group/" + group.getId().toString() + "/members/" +
userId.toString());
SidecarDeleteRequest sidecarDeleteRequest =
new SidecarDeleteRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarDeleteRequest.send();
if (response.getStatusCode() == 200) {
return mapper.readValue(response.getBody(), UserGroup.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
public UserGroup changeRoleForGroupMember(UserGroup group, UUID userId, Role newRole) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/group/" + group.getId().toString() + "/members/" +
userId.toString() + "/role");
ObjectNode roleJson = JsonNodeFactory.instance.objectNode();
roleJson.put("role", newRole.roleName);
SidecarPutRequest sidecarPutRequest =
new SidecarPutRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(roleJson)
.build();
SidecarResponse response = sidecarPutRequest.send();
if (response.getStatusCode() == 200) {
return mapper.readValue(response.getBody(), UserGroup.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings({"unchecked", "unused"})
public List<UUID> getGroupsForUser(String emailAddress) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/" + emailAddress + "/groups");
SidecarGetRequest sidecarGetRequest =
new SidecarGetRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarGetRequest.send();
if (response.getStatusCode() == 200) {
return Collections.checkedList(mapper.readValue(response.getBody(), List.class), UUID.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public void provisionDevice(UUID deviceId) {
Map<String, String> metaData = new HashMap<>();
metaData.put("deviceId", deviceId.toString());
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/device");
SidecarPostRequest sidecarPostRequest =
new SidecarPostRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(metaData)
.build();
SidecarResponse response = sidecarPostRequest.send();
if (response.getStatusCode() != 204) {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public void deprovisionDevice(UUID deviceId) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/device/" + deviceId.toString());
SidecarDeleteRequest sidecarDeleteRequest =
new SidecarDeleteRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarDeleteRequest.send();
//The response body is empty if 204, so only check if we do not have a 204 response
if (response.getStatusCode() != 204) {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public Map<String, String> getUserDeviceMetadata(UUID deviceId) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/device/" + deviceId.toString());
SidecarGetRequest sidecarGetRequest =
new SidecarGetRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarGetRequest.send();
if (response.getStatusCode() == 200) {
return mapper.readValue(response.getBody(), Map.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public void updateUserDeviceMetadata(UUID deviceId, Map<String, String> metaData) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/device/" + deviceId.toString());
SidecarPutRequest sidecarPutRequest =
new SidecarPutRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(metaData)
.build();
SidecarResponse response = sidecarPutRequest.send();
if (response.getStatusCode() != 204) {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings({"unused", "unchecked"})
public List<Device> getDevicesForUser() {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/devices");
SidecarGetRequest sidecarPostRequest =
new SidecarGetRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarPostRequest.send();
// check for an OK response code
if (response.getStatusCode() == 200) {
return Collections.checkedList(mapper.readValue(response.getBody(), java.util.List.class), Device.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public void addNotificationToken(PlatformDeviceToken token) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/notifications/token");
SidecarPostRequest sidecarPostRequest =
new SidecarPostRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(token)
.build();
SidecarResponse response = sidecarPostRequest.send();
// check for an no content response code
if (response.getStatusCode() != 204) {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public UUID addNotificationRule(String name, String description, String stream, String key, Double min, Double max) {
HashMap<String, Object> payload = new HashMap<>();
payload.put("name", name);
payload.put("description", description);
payload.put("stream", stream);
payload.put("key", key);
payload.put("min", min);
payload.put("max", max);
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/notifications/rule");
SidecarPostRequest sidecarPostRequest =
new SidecarPostRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(payload)
.build();
SidecarResponse response = sidecarPostRequest.send();
// check for an OK response code
if (response.getStatusCode() == 200) {
return UUID.fromString(mapper.readTree(response.getBody()).get("id").textValue());
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public UUID updateNotificationRule(UUID ruleId, String name, String description, String stream, String key, Double min, Double max) {
HashMap<String, Object> payload = new HashMap<>();
payload.put("name", name);
payload.put("description", description);
payload.put("stream", stream);
payload.put("key", key);
payload.put("min", min);
payload.put("max", max);
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/notifications/rule/" + ruleId.toString());
SidecarPutRequest sidecarPutRequest =
new SidecarPutRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(payload)
.build();
SidecarResponse response = sidecarPutRequest.send();
// check for an OK response code
if (response.getStatusCode() == 200) {
return UUID.fromString(mapper.readTree(response.getBody()).get("id").textValue());
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public NotificationRule getNotificationRule(UUID ruleId) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/notifications/rule/" + ruleId.toString());
SidecarGetRequest sidecarPostRequest =
new SidecarGetRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarPostRequest.send();
// check for an OK response code
if (response.getStatusCode() == 200) {
return mapper.readValue(response.getBody(), NotificationRule.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings({"unused", "unchecked"})
public List<NotificationRule> getNotificationRules() {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/notifications/rules");
SidecarGetRequest sidecarPostRequest =
new SidecarGetRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarPostRequest.send();
// check for an OK response code
if (response.getStatusCode() == 200) {
return Collections.checkedList(mapper.readValue(response.getBody(), java.util.List.class), NotificationRule.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public void deleteNotificationRule(UUID ruleId) {
try {
URL endpoint = fullUrlForPath("/rest/v1/provision/user/notifications/rule/" + ruleId.toString());
SidecarDeleteRequest sidecarDeleteRequest =
new SidecarDeleteRequest.Builder(accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.build();
SidecarResponse response = sidecarDeleteRequest.send();
// check for an no content response code
if (response.getStatusCode() != 204) {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
@SuppressWarnings("unused")
public List<UserAnswerBucket> postUserQuery(String type, Query query) {
String path = "/rest/v1/query/user/devices/" + type;
return postUserBasedQuery(path, query);
}
public List<UserAnswerBucket> postUserDeviceQuery(String type, UUID deviceId, Query query) {
String path = "/rest/v1/query/user/device/" + deviceId.toString() + "/" + type;
return postUserBasedQuery(path, query);
}
@SuppressWarnings("unchecked")
private List<UserAnswerBucket> postUserBasedQuery(String path, Query query) {
try {
URL endpoint = fullUrlForPath(path);
SidecarPostRequest sidecarPostRequest = new SidecarPostRequest.Builder(
accessKey.getKeyId(), "", accessKey.getSecret())
.withSignatureVersion(ONE)
.withUrl(endpoint)
.withPayload(query)
.build();
SidecarResponse response = sidecarPostRequest.send();
if (response.getStatusCode() == 200) {
LOGGER.debug(response.getBody());
return Collections.checkedList(mapper.readValue(response.getBody(), List.class), UserAnswerBucket.class);
} else {
throw new SidecarClientException(response.getStatusCode(), response.getBody());
}
} catch (Exception e) {
throw propagate(e);
}
}
public ClientConfig getConfig() {
return clientConfig;
}
private URL fullUrlForPath(String path) {
try {
URL baseUrl = clientConfig.getRestApiBasePath();
return new URL(baseUrl.toString() + path);
} catch (MalformedURLException e) {
throw propagate(e);
}
}
} |
package com.github.podd.utils;
import org.openrdf.model.URI;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.impl.ValueFactoryImpl;
import org.openrdf.model.vocabulary.OWL;
/**
* Interface containing URI constants for the Ontologies needed in PODD.
*
* @author kutila
*
*/
public interface PoddRdfConstants
{
public static final ValueFactory VF = ValueFactoryImpl.getInstance();
/** Path to default alias file */
public static final String PATH_DEFAULT_ALIASES_FILE = "/com/github/podd/api/file/default-file-repositories.ttl";
/** Path to dcTerms.owl */
public static final String PATH_PODD_DCTERMS = "/ontologies/dcTerms.owl";
/** Path to foaf.owl */
public static final String PATH_PODD_FOAF = "/ontologies/foaf.owl";
/** Path to poddUser.owl */
public static final String PATH_PODD_USER = "/ontologies/poddUser.owl";
/** Path to poddBase.owl */
public static final String PATH_PODD_BASE = "/ontologies/poddBase.owl";
/** Path to poddScience.owl */
public static final String PATH_PODD_SCIENCE = "/ontologies/poddScience.owl";
/** Path to poddPlant.owl */
public static final String PATH_PODD_PLANT = "/ontologies/poddPlant.owl";
/** Path to poddAnimal.owl */
public static final String PATH_PODD_ANIMAL = "/ontologies/poddAnimal.owl";
/**
* Path to poddFileRepository.owl.
*
* This ontology is NOT part of the standard schema ontologies. It is a separate ontology used
* to validate File Repository configurations.
*/
public static final String PATH_PODD_FILE_REPOSITORY = "/ontologies/poddFileRepository.owl";
public static final String PODD_DCTERMS = "http://purl.org/podd/ns/dcTerms
public static final String PODD_FOAF = "http://purl.org/podd/ns/foaf
public static final String PODD_USER = "http://purl.org/podd/ns/poddUser
public static final String PODD_BASE = "http://purl.org/podd/ns/poddBase
public static final String PODD_SCIENCE = "http://purl.org/podd/ns/poddScience
public static final String PODD_PLANT = "http://purl.org/podd/ns/poddPlant
public static final String FILE_REPOSITORY = "http://purl.org/podd/ns/fileRepository
/**
* An arbitrary prefix to use for automatically assigning ontology IRIs to inferred ontologies.
* There are no versions delegated to inferred ontologies, and the ontology IRI is generated
* using the version IRI of the original ontology, which must be unique.
*/
public static final String INFERRED_PREFIX = "urn:podd:inferred:ontologyiriprefix:";
/** Default value is urn:podd:default:artifactmanagementgraph: */
public static final URI DEFAULT_ARTIFACT_MANAGEMENT_GRAPH = PoddRdfConstants.VF
.createURI("urn:podd:default:artifactmanagementgraph:");
/** Default value is urn:podd:default:schemamanagementgraph */
public static final URI DEFAULT_SCHEMA_MANAGEMENT_GRAPH = PoddRdfConstants.VF
.createURI("urn:podd:default:schemamanagementgraph");
/** Default value is urn:podd:default:usermanagementgraph: */
public static final URI DEF_USER_MANAGEMENT_GRAPH = PoddRdfConstants.VF
.createURI("urn:podd:default:usermanagementgraph:");
public static final URI DEFAULT_FILE_REPOSITORY_MANAGEMENT_GRAPH = PoddRdfConstants.VF
.createURI("urn:podd:default:filerepositorymanagementgraph:");
public static final URI OWL_MAX_QUALIFIED_CARDINALITY = PoddRdfConstants.VF
.createURI("http://www.w3.org/2002/07/owl#maxQualifiedCardinality");
public static final URI OWL_MIN_QUALIFIED_CARDINALITY = PoddRdfConstants.VF
.createURI("http://www.w3.org/2002/07/owl#minQualifiedCardinality");
public static final URI OWL_QUALIFIED_CARDINALITY = PoddRdfConstants.VF
.createURI("http://www.w3.org/2002/07/owl#qualifiedCardinality");
public static final URI OWL_VERSION_IRI = PoddRdfConstants.VF.createURI(OWL.NAMESPACE, "versionIRI");
/**
* The OMV vocabulary defines a property for the current version of an ontology, so we are
* reusing it here.
*/
public static final URI OMV_CURRENT_VERSION = PoddRdfConstants.VF.createURI("http://omv.ontoware.org/ontology
"currentVersion");
/**
* Creating a property for PODD to track the currentInferredVersion for the inferred axioms
* ontology when linking from the ontology IRI.
*/
public static final URI PODD_BASE_CURRENT_INFERRED_VERSION = PoddRdfConstants.VF.createURI(
PoddRdfConstants.PODD_BASE, "currentInferredVersion");
public static final String HTTP = "http://www.w3.org/2011/http
public static final URI HTTP_STATUS_CODE_VALUE = ValueFactoryImpl.getInstance().createURI(PoddRdfConstants.HTTP,
"statusCodeValue");
public static final URI HTTP_REASON_PHRASE = ValueFactoryImpl.getInstance().createURI(PoddRdfConstants.HTTP,
"reasonPhrase");
/**
* Creating a property for PODD to track the inferredVersion for the inferred axioms ontology of
* a particular versioned ontology.
*/
public static final URI PODD_BASE_INFERRED_VERSION = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE,
"inferredVersion");
public static final URI PODD_BASE_HAS_PUBLICATION_STATUS = PoddRdfConstants.VF.createURI(
PoddRdfConstants.PODD_BASE, "hasPublicationStatus");
public static final URI PODD_BASE_HAS_TOP_OBJECT = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE,
"artifactHasTopObject");
public static final URI PODD_BASE_PUBLISHED = PoddRdfConstants.VF
.createURI(PoddRdfConstants.PODD_BASE, "Published");
public static final URI PODD_BASE_NOT_PUBLISHED = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE,
"NotPublished");
public static final URI PODD_BASE_WEIGHT = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "weight");
public static final URI PODD_BASE_DO_NOT_DISPLAY = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE,
"doNotDisplay");
public static final URI PODD_BASE_CONTAINS = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "contains");
public static final URI PODD_BASE_DISPLAY_TYPE = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE,
"hasDisplayType");
public static final URI PODD_BASE_DISPLAY_TYPE_SHORTTEXT = PoddRdfConstants.VF.createURI(
PoddRdfConstants.PODD_BASE, "DisplayType_ShortText");
public static final URI PODD_BASE_DISPLAY_TYPE_LONGTEXT = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE,
"DisplayType_LongText");
public static final URI PODD_BASE_DISPLAY_TYPE_DROPDOWN = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE,
"DisplayType_DropDownList");
public static final URI PODD_BASE_DISPLAY_TYPE_CHECKBOX = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE,
"DisplayType_CheckBox");
public static final URI PODD_BASE_DISPLAY_TYPE_TABLE = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE,
"DisplayType_Table");
public static final URI PODD_BASE_ALLOWED_VALUE = ValueFactoryImpl.getInstance().createURI(
PoddRdfConstants.PODD_BASE, "hasAllowedValue");
public static final URI PODD_BASE_HAS_CARDINALITY = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE,
"hasCardinality");
public static final URI PODD_BASE_CARDINALITY_EXACTLY_ONE = PoddRdfConstants.VF.createURI(
PoddRdfConstants.PODD_BASE, "Cardinality_Exactly_One");
public static final URI PODD_BASE_CARDINALITY_ONE_OR_MANY = PoddRdfConstants.VF.createURI(
PoddRdfConstants.PODD_BASE, "Cardinality_One_Or_Many");
public static final URI PODD_BASE_CARDINALITY_ZERO_OR_ONE = PoddRdfConstants.VF.createURI(
PoddRdfConstants.PODD_BASE, "Cardinality_Zero_Or_One");
public static final URI PODD_BASE_CARDINALITY_ZERO_OR_MANY = PoddRdfConstants.VF.createURI(
PoddRdfConstants.PODD_BASE, "Cardinality_Zero_Or_Many");
public static final URI PODD_BASE_HAS_FILE_REFERENCE = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE,
"hasFileReference");
public static final URI PODD_BASE_HAS_FILENAME = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE,
"hasFileName");
public static final URI PODD_BASE_HAS_FILE_PATH = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE,
"hasPath");
public static final URI PODD_BASE_HAS_ALIAS = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE, "hasAlias");
public static final URI PODD_BASE_FILE_REFERENCE_TYPE = PoddRdfConstants.VF.createURI(PoddRdfConstants.PODD_BASE,
"FileReference");
public static final URI PODD_BASE_FILE_REFERENCE_TYPE_SSH = PoddRdfConstants.VF.createURI(
PoddRdfConstants.PODD_BASE, "SSHFileReference");
public static final URI PODD_FILE_REPOSITORY = PoddRdfConstants.VF.createURI(PoddRdfConstants.FILE_REPOSITORY,
"FileRepository");
public static final URI PODD_SSH_FILE_REPOSITORY = PoddRdfConstants.VF.createURI(PoddRdfConstants.FILE_REPOSITORY,
"SSHFileRepository");
public static final URI PODD_HTTP_FILE_REPOSITORY = PoddRdfConstants.VF.createURI(PoddRdfConstants.FILE_REPOSITORY,
"HTTPFileRepository");
public static final URI PODD_FILE_REPOSITORY_ALIAS = PoddRdfConstants.VF.createURI(
PoddRdfConstants.FILE_REPOSITORY, "hasFileRepositoryAlias");
public static final URI PODD_FILE_REPOSITORY_PROTOCOL = PoddRdfConstants.VF.createURI(
PoddRdfConstants.FILE_REPOSITORY, "hasFileRepositoryProtocol");
public static final URI PODD_FILE_REPOSITORY_HOST = PoddRdfConstants.VF.createURI(PoddRdfConstants.FILE_REPOSITORY,
"hasFileRepositoryHost");
public static final URI PODD_FILE_REPOSITORY_PORT = PoddRdfConstants.VF.createURI(PoddRdfConstants.FILE_REPOSITORY,
"hasFileRepositoryPort");
public static final URI PODD_FILE_REPOSITORY_FINGERPRINT = PoddRdfConstants.VF.createURI(
PoddRdfConstants.FILE_REPOSITORY, "hasFileRepositoryFingerprint");
public static final URI PODD_FILE_REPOSITORY_USERNAME = PoddRdfConstants.VF.createURI(
PoddRdfConstants.FILE_REPOSITORY, "hasFileRepositoryUsername");
public static final URI PODD_FILE_REPOSITORY_SECRET = PoddRdfConstants.VF.createURI(
PoddRdfConstants.FILE_REPOSITORY, "hasFileRepositorySecret");
} |
package com.distelli.graphql.apigen;
import graphql.language.Definition;
import graphql.language.EnumTypeDefinition;
import graphql.language.EnumValueDefinition;
import graphql.language.FieldDefinition;
import graphql.language.InputObjectTypeDefinition;
import graphql.language.InputValueDefinition;
import graphql.language.InterfaceTypeDefinition;
import graphql.language.ListType;
import graphql.language.NonNullType;
import graphql.language.ObjectTypeDefinition;
import graphql.language.OperationTypeDefinition;
import graphql.language.ScalarTypeDefinition;
import graphql.language.SchemaDefinition;
import graphql.language.Type;
import graphql.language.TypeName;
import graphql.language.UnionTypeDefinition;
import graphql.language.Value;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
public class STModel {
private static Map<String, String> BUILTINS = new HashMap<String, String>(){{
put("Int", null);
put("Long", null);
put("Float", null);
put("String", null);
put("Boolean", null);
put("ID", null);
put("BigInteger", "java.math.BigInteger");
put("BigDecimal", "java.math.BigDecimal");
put("Byte", null);
put("Short", null);
put("Char", null);
}};
private static Map<String, String> RENAME = new HashMap<String, String>(){{
put("Int", "Integer");
put("ID", "String");
put("Char", "Character");
}};
public static class Builder {
private TypeEntry typeEntry;
private Map<String, TypeEntry> referenceTypes;
public Builder withTypeEntry(TypeEntry typeEntry) {
this.typeEntry = typeEntry;
return this;
}
public Builder withReferenceTypes(Map<String, TypeEntry> referenceTypes) {
this.referenceTypes = referenceTypes;
return this;
}
public STModel build() {
return new STModel(this);
}
}
public static class DataResolver {
public String fieldName;
public String fieldType;
public int listDepth;
}
public static class Interface {
public String type;
}
public static class Arg {
public String name;
public String type;
public String graphQLType;
public String defaultValue;
public Arg(String name, String type) {
this.name = name;
this.type = type;
}
public String getUcname() {
return ucFirst(name);
}
}
// Field of Interface, Object, InputObject, UnionType (no names), Enum (no types)
public static class Field {
public String name;
public String type;
public DataResolver dataResolver;
public String graphQLType;
public List<Arg> args;
public String defaultValue;
public Field(String name, String type) {
this.name = name;
this.type = type;
}
public String getUcname() {
return ucFirst(name);
}
}
private TypeEntry typeEntry;
private Map<String, TypeEntry> referenceTypes;
private List<Field> fields;
public List<Interface> interfaces;
private List<String> imports;
private Field idField;
private boolean gotIdField = false;
private STModel(Builder builder) {
this.typeEntry = builder.typeEntry;
this.referenceTypes = builder.referenceTypes;
}
public void validate() {
// TODO: Validate that any Object "implements" actually implements
// the interface so we can error before compile time...
// these throw if there are any inconsistencies...
getFields();
getImports();
getInterfaces();
}
public boolean isObjectType() {
return typeEntry.getDefinition() instanceof ObjectTypeDefinition;
}
public boolean isInterfaceType() {
return typeEntry.getDefinition() instanceof InterfaceTypeDefinition;
}
public boolean isEnumType() {
return typeEntry.getDefinition() instanceof EnumTypeDefinition;
}
public boolean isScalarType() {
return typeEntry.getDefinition() instanceof ScalarTypeDefinition;
}
public boolean isUnionType() {
return typeEntry.getDefinition() instanceof UnionTypeDefinition;
}
public boolean isInputObjectType() {
return typeEntry.getDefinition() instanceof InputObjectTypeDefinition;
}
public boolean isSchemaType() {
return typeEntry.getDefinition() instanceof SchemaDefinition;
}
public String getPackageName() {
return typeEntry.getPackageName();
}
public String getName() {
return typeEntry.getName();
}
public String getUcname() {
return ucFirst(getName());
}
private static String ucFirst(String name) {
if ( null == name || name.length() < 1 ) return name;
return name.substring(0, 1).toUpperCase() + name.substring(1);
}
private static String lcFirst(String name) {
if ( null == name || name.length() < 1 ) return name;
return name.substring(0, 1).toLowerCase() + name.substring(1);
}
public synchronized Field getIdField() {
if ( ! gotIdField ) {
for ( Field field : getFields() ) {
if ( "id".equals(field.name) ) {
idField = field;
break;
}
}
gotIdField = true;
}
return idField;
}
public List<Interface> getInterfaces() {
interfaces = new ArrayList<>();
if (!isObjectType()) {
return interfaces;
}
ObjectTypeDefinition objectTypeDefinition = (ObjectTypeDefinition) typeEntry.getDefinition();
List<Type> interfaceTypes = objectTypeDefinition.getImplements();
for (Type anInterfaceType : interfaceTypes) {
Interface anInterface = new Interface();
anInterface.type = toJavaTypeName(anInterfaceType);
interfaces.add(anInterface);
}
return interfaces;
}
public List<DataResolver> getDataResolvers() {
Map<String, DataResolver> resolvers = new LinkedHashMap<>();
for ( Field field : getFields() ) {
DataResolver resolver = field.dataResolver;
if ( null == resolver ) continue;
resolvers.put(resolver.fieldType, resolver);
}
return new ArrayList<>(resolvers.values());
}
public synchronized List<String> getImports() {
if ( null == imports ) {
Definition def = typeEntry.getDefinition();
Set<String> names = new TreeSet<String>();
if ( isObjectType() ) {
addImports(names, (ObjectTypeDefinition)def);
} else if ( isInterfaceType() ) {
addImports(names, (InterfaceTypeDefinition)def);
} else if ( isInputObjectType() ) {
addImports(names, (InputObjectTypeDefinition)def);
} else if ( isUnionType() ) {
addImports(names, (UnionTypeDefinition)def);
} else if ( isEnumType() ) {
addImports(names, (EnumTypeDefinition)def);
} else if ( isSchemaType() ) {
addImports(names, (SchemaDefinition)def);
}
imports = new ArrayList<>(names);
}
return imports;
}
public synchronized List<Field> getFields() {
if ( null == fields ) {
Definition def = typeEntry.getDefinition();
if ( isObjectType() ) {
fields = getFields((ObjectTypeDefinition)def);
} else if ( isInterfaceType() ) {
fields = getFields((InterfaceTypeDefinition)def);
} else if ( isInputObjectType() ) {
fields = getFields((InputObjectTypeDefinition)def);
} else if ( isUnionType() ) {
fields = getFields((UnionTypeDefinition)def);
} else if ( isEnumType() ) {
fields = getFields((EnumTypeDefinition)def);
} else if ( isSchemaType() ) {
fields = getFields((SchemaDefinition)def);
} else {
fields = Collections.emptyList();
}
}
return fields;
}
private List<Field> getFields(ObjectTypeDefinition def) {
List<Field> fields = new ArrayList<Field>();
for ( FieldDefinition fieldDef : def.getFieldDefinitions() ) {
Field field = new Field(fieldDef.getName(), toJavaTypeName(fieldDef.getType()));
field.graphQLType = toGraphQLType(fieldDef.getType());
field.dataResolver = toDataResolver(fieldDef.getType());
field.args = toArgs(fieldDef.getInputValueDefinitions());
fields.add(field);
}
return fields;
}
private List<Field> getFields(InterfaceTypeDefinition def) {
List<Field> fields = new ArrayList<Field>();
for ( FieldDefinition fieldDef : def.getFieldDefinitions() ) {
Field field = new Field(fieldDef.getName(), toJavaTypeName(fieldDef.getType()));
field.args = toArgs(fieldDef.getInputValueDefinitions());
fields.add(field);
}
return fields;
}
private List<Field> getFields(InputObjectTypeDefinition def) {
List<Field> fields = new ArrayList<Field>();
for ( InputValueDefinition fieldDef : def.getInputValueDefinitions() ) {
Field field = new Field(fieldDef.getName(), toJavaTypeName(fieldDef.getType()));
field.graphQLType = toGraphQLType(fieldDef.getType());
field.defaultValue = toJavaValue(fieldDef.getDefaultValue());
fields.add(field);
}
return fields;
}
private List<Field> getFields(UnionTypeDefinition def) {
List<Field> fields = new ArrayList<Field>();
for ( Type type : def.getMemberTypes() ) {
fields.add(new Field(null, toJavaTypeName(type)));
}
return fields;
}
private List<Field> getFields(EnumTypeDefinition def) {
List<Field> fields = new ArrayList<Field>();
for ( EnumValueDefinition fieldDef : def.getEnumValueDefinitions() ) {
fields.add(new Field(fieldDef.getName(), null));
}
return fields;
}
private List<Field> getFields(SchemaDefinition def) {
List<Field> fields = new ArrayList<Field>();
for ( OperationTypeDefinition fieldDef : def.getOperationTypeDefinitions() ) {
fields.add(new Field(fieldDef.getName(), toJavaTypeName(fieldDef.getType())));
}
return fields;
}
private List<Arg> toArgs(List<InputValueDefinition> defs) {
List<Arg> result = new ArrayList<>();
for ( InputValueDefinition def : defs ) {
Arg arg = new Arg(def.getName(), toJavaTypeName(def.getType()));
arg.graphQLType = toGraphQLType(def.getType());
arg.defaultValue = toJavaValue(def.getDefaultValue());
result.add(arg);
}
return result;
}
private String toJavaValue(Value value) {
// TODO: Implement me!
return null;
}
private DataResolver toDataResolver(Type type) {
if ( type instanceof ListType ) {
DataResolver resolver = toDataResolver(((ListType)type).getType());
if ( null == resolver ) return null;
resolver.listDepth++;
return resolver;
} else if ( type instanceof NonNullType ) {
return toDataResolver(((NonNullType)type).getType());
} else if ( type instanceof TypeName ) {
String typeName = ((TypeName)type).getName();
if ( BUILTINS.containsKey(typeName) ) return null;
TypeEntry typeEntry = referenceTypes.get(typeName);
if ( !typeEntry.hasIdField() ) return null;
DataResolver resolver = new DataResolver();
resolver.fieldType = typeName + ".Resolver";
resolver.fieldName = "_" + lcFirst(typeName) + "Resolver";
return resolver;
} else {
throw new UnsupportedOperationException("Unknown Type="+type.getClass().getName());
}
}
private String toGraphQLType(Type type) {
if ( type instanceof ListType ) {
return "new GraphQLList(" + toGraphQLType(((ListType)type).getType()) + ")";
} else if ( type instanceof NonNullType ) {
return toGraphQLType(((NonNullType)type).getType());
} else if ( type instanceof TypeName ) {
String name = ((TypeName)type).getName();
if ( BUILTINS.containsKey(name) ) {
return "Scalars.GraphQL" + name;
}
return "new GraphQLTypeReference(\""+name+"\")";
} else {
throw new UnsupportedOperationException("Unknown Type="+type.getClass().getName());
}
}
private String toJavaTypeName(Type type) {
if ( type instanceof ListType ) {
return "List<" + toJavaTypeName(((ListType)type).getType()) + ">";
} else if ( type instanceof NonNullType ) {
return toJavaTypeName(((NonNullType)type).getType());
} else if ( type instanceof TypeName ) {
String name = ((TypeName)type).getName();
String rename = RENAME.get(name);
// TODO: scalar type directive to get implementation class...
if ( null != rename ) return rename;
return name;
} else {
throw new UnsupportedOperationException("Unknown Type="+type.getClass().getName());
}
}
private void addImports(Collection<String> imports, ObjectTypeDefinition def) {
for ( FieldDefinition fieldDef : def.getFieldDefinitions() ) {
addImports(imports, fieldDef.getType());
}
}
private void addImports(Collection<String> imports, InterfaceTypeDefinition def) {
for ( FieldDefinition fieldDef : def.getFieldDefinitions() ) {
addImports(imports, fieldDef.getType());
}
}
private void addImports(Collection<String> imports, InputObjectTypeDefinition def) {
for ( InputValueDefinition fieldDef : def.getInputValueDefinitions() ) {
addImports(imports, fieldDef.getType());
}
}
private void addImports(Collection<String> imports, UnionTypeDefinition def) {
for ( Type type : def.getMemberTypes() ) {
addImports(imports, type);
}
}
private void addImports(Collection<String> imports, EnumTypeDefinition def) {
// No imports should be necessary...
}
private void addImports(Collection<String> imports, SchemaDefinition def) {
for ( OperationTypeDefinition fieldDef : def.getOperationTypeDefinitions() ) {
addImports(imports, fieldDef.getType());
}
}
private void addImports(Collection<String> imports, Type type) {
if ( type instanceof ListType ) {
imports.add("java.util.List");
addImports(imports, ((ListType)type).getType());
} else if ( type instanceof NonNullType ) {
addImports(imports, ((NonNullType)type).getType());
} else if ( type instanceof TypeName ) {
String name = ((TypeName)type).getName();
if ( BUILTINS.containsKey(name) ) {
String importName = BUILTINS.get(name);
if ( null == importName ) return;
imports.add(importName);
} else {
TypeEntry refEntry = referenceTypes.get(name);
// TODO: scalar name may be different... should read annotations for scalars.
if ( null == refEntry ) {
throw new RuntimeException("Unknown type '"+name+"' was not defined in the schema");
} else {
imports.add(refEntry.getPackageName() + "." + name);
}
}
} else {
throw new RuntimeException("Unknown Type="+type.getClass().getName());
}
}
} |
package org.jgroups.tests;
import org.jgroups.Global;
import org.jgroups.JChannel;
import org.jgroups.Message;
import org.jgroups.ReceiverAdapter;
import org.jgroups.logging.Log;
import org.jgroups.logging.LogFactory;
import org.jgroups.protocols.*;
import org.jgroups.protocols.pbcast.GMS;
import org.jgroups.protocols.pbcast.NAKACK2;
import org.jgroups.stack.DiagnosticsHandler;
import org.jgroups.stack.ProtocolStack;
import org.jgroups.util.*;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.io.IOException;
import java.net.InetAddress;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Tests tthe {@link RSVP} protocol
* @author Bela Ban
*/
@Test(groups=Global.FUNCTIONAL,sequential=true)
public class RSVPTest {
protected static final int NUM=5; // number of members
protected final JChannel[] channels=new JChannel[NUM];
protected final MyReceiver[] receivers=new MyReceiver[NUM];
protected MyDiagnosticsHandler handler;
protected ThreadPoolExecutor oob_thread_pool;
protected ThreadPoolExecutor thread_pool;
@BeforeMethod
void setUp() throws Exception {
handler=new MyDiagnosticsHandler(InetAddress.getByName("224.0.75.75"), 7500,
LogFactory.getLog(DiagnosticsHandler.class),
new DefaultSocketFactory(),
new DefaultThreadFactory(new ThreadGroup("RSVPTest"), "", false));
handler.start();
ThreadGroup test_group=new ThreadGroup("LargeMergeTest");
TimeScheduler timer=new TimeScheduler2(new DefaultThreadFactory(test_group, "Timer", true, true),
5,20,
3000, 5000, "abort");
oob_thread_pool=new ThreadPoolExecutor(5, Math.max(5, NUM/4), 3000, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(NUM * NUM));
oob_thread_pool.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
thread_pool=new ThreadPoolExecutor(5, Math.max(5, NUM/4), 3000, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(NUM * NUM));
thread_pool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
System.out.print("Connecting channels: ");
for(int i=0; i < NUM; i++) {
SHARED_LOOPBACK shared_loopback=(SHARED_LOOPBACK)new SHARED_LOOPBACK().setValue("enable_bundling", false);
// UDP shared_loopback=(UDP)new UDP().setValue("enable_bundling", false);
shared_loopback.setLoopback(false);
shared_loopback.setTimer(timer);
shared_loopback.setOOBThreadPool(oob_thread_pool);
shared_loopback.setDefaultThreadPool(thread_pool);
shared_loopback.setDiagnosticsHandler(handler);
channels[i]=Util.createChannel(shared_loopback,
new DISCARD(),
new PING().setValue("timeout",1000).setValue("num_initial_members",NUM)
.setValue("force_sending_discovery_rsps", true),
new MERGE2().setValue("min_interval", 1000).setValue("max_interval", 3000),
new NAKACK2().setValue("use_mcast_xmit",false)
.setValue("discard_delivered_msgs",true)
.setValue("log_discard_msgs",false).setValue("log_not_found_msgs",false)
.setValue("xmit_table_num_rows",5)
.setValue("xmit_table_msgs_per_row",10),
// new UNICAST(),
new UNICAST2().setValue("xmit_table_num_rows",5).setValue("xmit_interval", 300)
.setValue("xmit_table_msgs_per_row",10)
.setValue("conn_expiry_timeout", 10000)
.setValue("stable_interval", 30000)
.setValue("max_bytes", 50000),
new RSVP().setValue("timeout", 10000).setValue("throw_exception_on_timeout", false),
// new STABLE().setValue("max_bytes",500000).setValue("desired_avg_gossip", 60000),
new GMS().setValue("print_local_addr",false)
.setValue("leave_timeout",100)
.setValue("log_view_warnings",false)
.setValue("view_ack_collection_timeout",2000)
.setValue("log_collect_msgs",false));
channels[i].setName(String.valueOf((i + 1)));
receivers[i]=new MyReceiver();
channels[i].setReceiver(receivers[i]);
channels[i].connect("RSVPTest");
System.out.print(i + 1 + " ");
if(i == 0)
Util.sleep(2000);
}
Util.waitUntilAllChannelsHaveSameSize(30000, 1000, channels);
System.out.println("");
}
@AfterMethod
void tearDown() throws Exception {
for(int i=NUM-1; i >= 0; i
ProtocolStack stack=channels[i].getProtocolStack();
String cluster_name=channels[i].getClusterName();
stack.stopStack(cluster_name);
stack.destroy();
}
handler.destroy();
}
public void testSynchronousMulticastSend() throws Exception {
for(JChannel ch: channels)
assert ch.getView().size() == NUM : "channel " + ch.getAddress() + ": view is " + ch.getView();
// test with a multicast message:
short value=(short)Math.abs((short)Util.random(10000));
Message msg=new Message(null, null, value);
msg.setFlag(Message.Flag.RSVP);
DISCARD discard=(DISCARD)channels[0].getProtocolStack().findProtocol(DISCARD.class);
discard.setDropDownMulticasts(1);
long start=System.currentTimeMillis();
channels[0].send(msg);
long diff=System.currentTimeMillis() - start;
System.out.println("sending took " + diff + " ms");
int cnt=1;
for(MyReceiver receiver: receivers) {
System.out.println("receiver " + cnt++ + ": value=" + receiver.getValue());
}
for(MyReceiver receiver: receivers) {
long tmp_value=receiver.getValue();
assert tmp_value == value : "value is " + tmp_value + ", but should be " + value;
}
}
public void testSynchronousUnicastSend() throws Exception {
for(JChannel ch: channels)
assert ch.getView().size() == NUM : "channel " + ch.getAddress() + ": view is " + ch.getView();
// test with a multicast message:
short value=(short)Math.abs((short)Util.random(10000));
Message msg=new Message(channels[1].getAddress(), null, value);
msg.setFlag(Message.Flag.RSVP);
DISCARD discard=(DISCARD)channels[0].getProtocolStack().findProtocol(DISCARD.class);
discard.setDropDownUnicasts(1);
long start=System.currentTimeMillis();
channels[0].send(msg);
long diff=System.currentTimeMillis() - start;
System.out.println("sending took " + diff + " ms");
System.out.println("receiver: value=" + receivers[1].getValue());
long tmp_value=receivers[1].getValue();
assert tmp_value == value : "value is " + tmp_value + ", but should be " + value;
}
public void testCancellationByClosingChannel() throws Exception {
// test with a multicast message:
short value=(short)Math.abs((short)Util.random(10000));
Message msg=new Message(null, null, value);
msg.setFlag(Message.Flag.RSVP);
DISCARD discard=(DISCARD)channels[0].getProtocolStack().findProtocol(DISCARD.class);
discard.setDiscardAll(true);
RSVP rsvp=(RSVP)channels[0].getProtocolStack().findProtocol(RSVP.class);
rsvp.setValue("throw_exception_on_timeout", true);
try {
Thread closer=new Thread() {
public void run() {
Util.sleep(2000);
System.out.println("closer closing channel");
channels[0].close();
}
};
closer.start();
channels[0].send(msg); // this will be unsuccessful as the other 4 members won't receive it
// test fails if we get a TimeoutException
}
finally {
discard.setDiscardAll(false);
rsvp.setValue("throw_exception_on_timeout", false);
}
}
protected static class MyReceiver extends ReceiverAdapter {
short value=0;
public short getValue() {return value;}
public void receive(Message msg) {
value=(Short)msg.getObject();
}
}
protected static class MyDiagnosticsHandler extends DiagnosticsHandler {
protected MyDiagnosticsHandler(InetAddress diagnostics_addr, int diagnostics_port, Log log, SocketFactory socket_factory, ThreadFactory thread_factory) {
super(diagnostics_addr,diagnostics_port,log,socket_factory,thread_factory);
}
public void start() throws IOException {super.start();}
public void stop() {}
public void destroy() {super.stop();}
}
} |
package org.jgroups.tests;
import org.jgroups.*;
import org.jgroups.conf.ConfiguratorFactory;
import org.jgroups.conf.ProtocolData;
import org.jgroups.conf.ProtocolParameter;
import org.jgroups.conf.ProtocolStackConfigurator;
import org.jgroups.util.Util;
import java.util.LinkedList;
import java.util.List;
/**
* Tests which test the shared transport
* @author Bela Ban
* @version $Id: SharedTransportTest.java,v 1.6 2008/01/24 07:51:56 belaban Exp $
*/
public class SharedTransportTest extends ChannelTestBase {
private JChannel a, b, c;
private MyReceiver r1, r2, r3;
static final String SINGLETON_1="singleton-1", SINGLETON_2="singleton-2";
protected void tearDown() throws Exception {
if(c != null)
c.close();
if(b != null)
b.close();
if(a != null)
a.close();
r1=r2=r3=null;
super.tearDown();
}
public void testCreationNonSharedTransport() throws Exception {
a=createChannel();
a.connect("x");
View view=a.getView();
System.out.println("view = " + view);
assertEquals(1, view.size());
}
public void testCreationOfDuplicateCluster() throws Exception {
a=createSharedChannel(SINGLETON_1);
b=createSharedChannel(SINGLETON_1);
a.connect("x");
try {
b.connect("x");
fail("b should not be able to join cluster 'x' as a has already joined it");
}
catch(Exception ex) {
System.out.println("b was not able to join the same cluster (\"x\") as expected");
}
}
public void testView() throws Exception {
a=createSharedChannel(SINGLETON_1);
b=createSharedChannel(SINGLETON_2);
a.setReceiver(new MyReceiver(SINGLETON_1));
b.setReceiver(new MyReceiver(SINGLETON_2));
a.connect("x");
b.connect("x");
View view=a.getView();
assertEquals(2, view.size());
view=b.getView();
assertEquals(2, view.size());
}
public void testView2() throws Exception {
a=createSharedChannel(SINGLETON_1);
b=createSharedChannel(SINGLETON_1);
a.setReceiver(new MyReceiver("first-channel"));
b.setReceiver(new MyReceiver("second-channel"));
a.connect("x");
b.connect("y");
View view=a.getView();
assertEquals(1, view.size());
view=b.getView();
assertEquals(1, view.size());
}
public void testCreationOfDifferentCluster() throws Exception {
a=createSharedChannel(SINGLETON_1);
b=createSharedChannel(SINGLETON_2);
a.connect("x");
b.connect("x");
View view=b.getView();
System.out.println("b's view is " + view);
assertEquals(2, view.size());
}
public void testReferenceCounting() throws ChannelException {
a=createSharedChannel(SINGLETON_1);
r1=new MyReceiver("a");
a.setReceiver(r1);
b=createSharedChannel(SINGLETON_1);
r2=new MyReceiver("b");
b.setReceiver(r2);
c=createSharedChannel(SINGLETON_1);
r3=new MyReceiver("c");
c.setReceiver(r3);
a.connect("A");
b.connect("B");
c.connect("C");
a.send(null, null, "message from a");
b.send(null, null, "message from b");
c.send(null, null, "message from c");
Util.sleep(500);
assertEquals(1, r1.size());
assertEquals(1, r2.size());
assertEquals(1, r3.size());
r1.clear(); r2.clear(); r3.clear();
b.disconnect();
System.out.println("\n");
a.send(null, null, "message from a");
c.send(null, null, "message from c");
Util.sleep(500);
assertEquals(1, r1.size());
assertEquals(1, r3.size());
r1.clear(); r3.clear();
c.disconnect();
System.out.println("\n");
a.send(null, null, "message from a");
Util.sleep(500);
assertEquals(1, r1.size());
}
private static JChannel createSharedChannel(String singleton_name) throws ChannelException {
ProtocolStackConfigurator config=ConfiguratorFactory.getStackConfigurator(CHANNEL_CONFIG);
ProtocolData[] protocols=config.getProtocolStack();
ProtocolData transport=protocols[0];
transport.getParameters().put(Global.SINGLETON_NAME, new ProtocolParameter(Global.SINGLETON_NAME, singleton_name));
return new JChannel(config);
}
private static class MyReceiver extends ReceiverAdapter {
final List<Message> list=new LinkedList<Message>();
final String name;
private MyReceiver(String name) {
this.name=name;
}
public List<Message> getList() {
return list;
}
public int size() {
return list.size();
}
public void clear() {
list.clear();
}
public void receive(Message msg) {
System.out.println("[" + name + "]: received message from " + msg.getSrc() + ": " + msg.getObject());
list.add(msg);
}
public void viewAccepted(View new_view) {
System.out.println("view = " + new_view);
}
}
} |
package net.somethingdreadful.MAL;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import net.somethingdreadful.MAL.SearchActivity.networkThread;
import net.somethingdreadful.MAL.api.BaseMALApi;
import net.somethingdreadful.MAL.api.MALApi;
import net.somethingdreadful.MAL.record.AnimeRecord;
import net.somethingdreadful.MAL.record.MangaRecord;
import net.somethingdreadful.MAL.sql.MALSqlHelper;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.NotificationCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.app.SherlockDialogFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.sherlock.navigationdrawer.compat.SherlockActionBarDrawerToggle;
import de.keyboardsurfer.android.widget.crouton.Crouton;
import de.keyboardsurfer.android.widget.crouton.Style;
public class Home extends BaseActionBarSearchView
implements ActionBar.TabListener, ItemGridFragment.IItemGridFragment,
LogoutConfirmationDialogFragment.LogoutConfirmationDialogListener {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide fragments for each of the
* sections. We use a {@link android.support.v4.app.FragmentPagerAdapter} derivative, which will
* keep every loaded fragment in memory. If this becomes too memory intensive, it may be best
* to switch to a {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
HomeSectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
Context context;
PrefManager mPrefManager;
public MALManager mManager;
private boolean init = false;
ItemGridFragment af;
ItemGridFragment mf;
public boolean instanceExists;
boolean networkAvailable;
BroadcastReceiver networkReceiver;
MenuItem searchItem;
int AutoSync = 0; //run or not to run.
static final String state_sync = "AutoSync"; //to solve bugs.
static final String state_mylist = "myList";
int listType = 0; //remembers the list_type.
private DrawerLayout mDrawerLayout;
private ListView listView;
private SherlockActionBarDrawerToggle mDrawerToggle;
private ActionBarHelper mActionBar;
View mActiveView;
View mPreviousView;
boolean myList = true; //tracks if the user is on 'My List' or not
public static final String[] DRAWER_OPTIONS =
{
"Profile",
"My List",
"Top Rated",
"Most Popular",
"Just Added",
"Upcoming"
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getApplicationContext();
mPrefManager = new PrefManager(context);
init = mPrefManager.getInit();
//The following is state handling code
instanceExists = savedInstanceState != null && savedInstanceState.getBoolean("instanceExists", false);
networkAvailable = savedInstanceState == null || savedInstanceState.getBoolean("networkAvailable", true);
if (savedInstanceState != null) {
AutoSync = savedInstanceState.getInt(state_sync);
listType = savedInstanceState.getInt(state_mylist);
}
if (init) {
setContentView(R.layout.activity_home);
// Creates the adapter to return the Animu and Mango fragments
mSectionsPagerAdapter = new HomeSectionsPagerAdapter(getSupportFragmentManager());
mDrawerLayout= (DrawerLayout)findViewById(R.id.drawer_layout);
listView = (ListView)findViewById(R.id.left_drawer);
mDrawerLayout.setDrawerListener(new DemoDrawerListener());
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
HomeListViewArrayAdapter adapter = new HomeListViewArrayAdapter(this,R.layout.list_item,DRAWER_OPTIONS);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new DrawerItemClickListener());
listView.setCacheColorHint(0);
listView.setScrollingCacheEnabled(false);
listView.setScrollContainer(false);
listView.setFastScrollEnabled(true);
listView.setSmoothScrollbarEnabled(true);
mActionBar = createActionBarHelper();
mActionBar.init();
mDrawerToggle = new SherlockActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer_light, R.string.drawer_open, R.string.drawer_close);
mDrawerToggle.syncState();
mManager = new MALManager(context);
if (!instanceExists) {
}
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setPageMargin(32);
// When swiping between different sections, select the corresponding
// tab.
// We can also use ActionBar.Tab#select() to do this if we have a
// reference to the
// Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// Add tabs for the animu and mango lists
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title
// defined by the adapter.
// Also specify this Activity object, which implements the
// TabListener interface, as the
// listener for when this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
networkReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
checkNetworkAndDisplayCrouton();
}
};
listType = mPrefManager.getDefaultList(); //get chosen list :D
autosynctask();
} else { //If the app hasn't been configured, take us to the first run screen to sign in.
Intent firstRunInit = new Intent(this, FirstTimeInit.class);
firstRunInit.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(firstRunInit);
finish();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.activity_home, menu);
searchItem = menu.findItem(R.id.action_search);
super.onCreateOptionsMenu(menu);
return true;
}
@Override
public BaseMALApi.ListType getCurrentListType() {
String listName = getSupportActionBar().getSelectedTab().getText().toString();
return BaseMALApi.getListTypeByString(listName);
}
public boolean isConnectedWifi() {
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo Wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (Wifi.isConnected()&& mPrefManager.getonly_wifiEnabled() ) {
return true;
} else {
return false;
}
}
public void autosynctask(){
try {
af = (net.somethingdreadful.MAL.ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 0);
mf = (net.somethingdreadful.MAL.ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 1);
if (AutoSync == 0 && isNetworkAvailable() && networkAvailable == true && mPrefManager.getsynchronisationEnabled()){
if (mPrefManager.getsynchronisationEnabled() && mPrefManager.getonly_wifiEnabled() == false){ //connected to Wi-Fi and sync only on Wi-Fi checked.
af.getRecords(af.currentList, "anime", true, this.context);
mf.getRecords(af.currentList, "manga", true, this.context);
syncNotify();
AutoSync = 1;
}else if (mPrefManager.getonly_wifiEnabled() && isConnectedWifi() && mPrefManager.getsynchronisationEnabled()){ //connected and sync always.
af.getRecords(af.currentList, "anime", true, this.context);
mf.getRecords(af.currentList, "manga", true, this.context);
syncNotify();
AutoSync = 1;
}
}else{
//will do nothing, sync is turned off or (sync only on Wi-Fi checked) and there is no Wi-Fi.
}
}catch (Exception e){
Crouton.makeText(this, "Error: autosynctask faild!", Style.ALERT).show();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.menu_settings:
startActivity(new Intent(this, Settings.class));
break;
case R.id.menu_logout:
showLogoutDialog();
break;
case R.id.menu_about:
startActivity(new Intent(this, AboutActivity.class));
break;
case R.id.listType_all:
if (af != null && mf != null) {
af.getRecords(0, "anime", false, this.context);
mf.getRecords(0, "manga", false, this.context);
listType = 0;
supportInvalidateOptionsMenu();
}
break;
case R.id.listType_inprogress:
if (af != null && mf != null) {
af.getRecords(1, "anime", false, this.context);
mf.getRecords(1, "manga", false, this.context);
listType = 1;
supportInvalidateOptionsMenu();
}
break;
case R.id.listType_completed:
if (af != null && mf != null) {
af.getRecords(2, "anime", false, this.context);
mf.getRecords(2, "manga", false, this.context);
listType = 2;
supportInvalidateOptionsMenu();
}
break;
case R.id.listType_onhold:
if (af != null && mf != null) {
af.getRecords(3, "anime", false, this.context);
mf.getRecords(3, "manga", false, this.context);
listType = 3;
supportInvalidateOptionsMenu();
}
break;
case R.id.listType_dropped:
if (af != null && mf != null) {
af.getRecords(4, "anime", false, this.context);
mf.getRecords(4, "manga", false, this.context);
listType = 4;
supportInvalidateOptionsMenu();
}
break;
case R.id.listType_planned:
if (af != null && mf != null) {
af.getRecords(5, "anime", false, this.context);
mf.getRecords(5, "manga", false, this.context);
listType = 5;
supportInvalidateOptionsMenu();
}
break;
case R.id.forceSync:
if (af != null && mf != null) {
af.getRecords(af.currentList, "anime", true, this.context);
mf.getRecords(af.currentList, "manga", true, this.context);
syncNotify();
}
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onResume() {
super.onResume();
if (instanceExists && af.getMode()== 0) {
af.getRecords(af.currentList, "anime", false, this.context);
mf.getRecords(af.currentList, "manga", false, this.context);
}
checkNetworkAndDisplayCrouton();
registerReceiver(networkReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
if (mSearchView != null) {
mSearchView.clearFocus();
mSearchView.setFocusable(false);
mSearchView.setQuery("", false);
searchItem.collapseActionView();
}
}
@Override
public void onPause() {
super.onPause();
instanceExists = true;
unregisterReceiver(networkReceiver);
}
@Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
@Override
public void fragmentReady() {
//Interface implementation for knowing when the dynamically created fragment is finished loading
//We use instantiateItem to return the fragment. Since the fragment IS instantiated, the method returns it.
af = (net.somethingdreadful.MAL.ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 0);
mf = (net.somethingdreadful.MAL.ItemGridFragment) mSectionsPagerAdapter.instantiateItem(mViewPager, 1);
try { // if a error comes up it will not force close
getIntent().removeExtra("net.somethingdreadful.MAL.firstSync");
}catch (Exception e){
}
}
@Override
public void onSaveInstanceState(Bundle state) {
//This is telling out future selves that we already have some things and not to do them
state.putBoolean("instanceExists", true);
state.putBoolean("networkAvailable", networkAvailable);
state.putInt(state_sync, AutoSync);
state.putInt(state_mylist, listType);
super.onSaveInstanceState(state);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem item = menu.findItem(R.id.menu_listType);
if(!myList){//if not on my list then disable menu items like listType, etc
item.setEnabled(false);
item.setVisible(false);
}
else{
item.setEnabled(true);
item.setVisible(true);
}
if (af != null) {
//All this is handling the ticks in the switch list menu
switch (af.currentList) {
case 0:
menu.findItem(R.id.listType_all).setChecked(true);
break;
case 1:
menu.findItem(R.id.listType_inprogress).setChecked(true);
break;
case 2:
menu.findItem(R.id.listType_completed).setChecked(true);
break;
case 3:
menu.findItem(R.id.listType_onhold).setChecked(true);
break;
case 4:
menu.findItem(R.id.listType_dropped).setChecked(true);
break;
case 5:
menu.findItem(R.id.listType_planned).setChecked(true);
}
}
if (networkAvailable) {
if (myList){
menu.findItem(R.id.forceSync).setVisible(true);
}else{
menu.findItem(R.id.forceSync).setVisible(false);
}
menu.findItem(R.id.action_search).setVisible(true);
}
else {
menu.findItem(R.id.forceSync).setVisible(false);
menu.findItem(R.id.action_search).setVisible(false);
AutoSync = 1;
}
return true;
}
@SuppressLint("NewApi")
@Override
public void onLogoutConfirmed() {
mPrefManager.setInit(false);
mPrefManager.setUser("");
mPrefManager.setPass("");
mPrefManager.commitChanges();
context.deleteDatabase(MALSqlHelper.getHelper(context).getDatabaseName());
new ImageDownloader(context).wipeCache();
startActivity(new Intent(this, Home.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
finish();
}
private void syncNotify() {
Crouton.makeText(this, R.string.toast_SyncMessage, Style.INFO).show();
Intent notificationIntent = new Intent(context, Home.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 1, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification syncNotification = new NotificationCompat.Builder(context).setOngoing(true)
.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.icon)
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.toast_SyncMessage))
.getNotification();
nm.notify(R.id.notification_sync, syncNotification);
myList = true;
supportInvalidateOptionsMenu();
}
private void showLogoutDialog() {
FragmentManager fm = getSupportFragmentManager();
LogoutConfirmationDialogFragment lcdf = new LogoutConfirmationDialogFragment();
if (Build.VERSION.SDK_INT >= 11) {
lcdf.setStyle(SherlockDialogFragment.STYLE_NORMAL, android.R.style.Theme_Holo_Dialog);
} else {
lcdf.setStyle(SherlockDialogFragment.STYLE_NORMAL, 0);
}
lcdf.show(fm, "fragment_LogoutConfirmationDialog");
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
}
else {
return false;
}
}
public void maketext(String string) { //for the private class
Crouton.makeText(this, string, Style.INFO).show();
}
public void checkNetworkAndDisplayCrouton() {
if (!isNetworkAvailable() && networkAvailable == true) {
Crouton.makeText(this, R.string.crouton_noConnectivityOnRun, Style.ALERT).show();
if (af.getMode() > 0) {
af.setMode(0);
mf.setMode(0);
af.getRecords(listType, "anime", false, Home.this.context);
mf.getRecords(listType, "manga", false, Home.this.context);
myList = true;
}
} else if (isNetworkAvailable() && networkAvailable == false) {
Crouton.makeText(this, R.string.crouton_connectionRestored, Style.INFO).show();
af.getRecords(af.currentList, "anime", true, this.context);
mf.getRecords(af.currentList, "manga", true, this.context);
syncNotify();
}
if (!isNetworkAvailable()) {
networkAvailable = false;
} else {
networkAvailable = true;
}
supportInvalidateOptionsMenu();
}
/* thread & methods to fetch most popular anime/manga*/
//in order to reuse the code , 1 signifies a getPopular job and 2 signifies a getTopRated job. Probably a better way to do this
public void getMostPopular(BaseMALApi.ListType listType){
networkThread animethread = new networkThread(1);
animethread.setListType(BaseMALApi.ListType.ANIME);
animethread.execute(query);
/*networkThread mangathread = new networkThread(1);
mangathread.setListType(BaseMALApi.ListType.MANGA);
mangathread.execute(query);*/
//API doesn't support getting popular manga :/
}
public void getTopRated(BaseMALApi.ListType listType){
networkThread animethread = new networkThread(2);
animethread.setListType(BaseMALApi.ListType.ANIME);
animethread.execute(query);
/*networkThread mangathread = new networkThread(2);
mangathread.setListType(BaseMALApi.ListType.MANGA);
mangathread.execute(query);*/
//API doesn't support getting top rated manga :/
}
public void getJustAdded(BaseMALApi.ListType listType){
networkThread animethread = new networkThread(3);
animethread.setListType(BaseMALApi.ListType.ANIME);
animethread.execute(query);
/*networkThread mangathread = new networkThread(3);
mangathread.setListType(BaseMALApi.ListType.MANGA);
mangathread.execute(query);*/
//API doesn't support getting popular manga :/
}
public void getUpcoming(BaseMALApi.ListType listType){
networkThread animethread = new networkThread(4);
animethread.setListType(BaseMALApi.ListType.ANIME);
animethread.execute(query);
/*networkThread mangathread = new networkThread(4);
mangathread.setListType(BaseMALApi.ListType.MANGA);
mangathread.execute(query);*/
//API doesn't support getting popular manga :/
}
public class networkThread extends AsyncTask<String, Void, Void> {
JSONArray _result;
int job;
public networkThread(int job){
this.job = job;
}
public MALApi.ListType getListType() {
return listType;
}
public void setListType(MALApi.ListType listType) {
this.listType = listType;
}
MALApi.ListType listType;
@Override
protected Void doInBackground(String... params) {
try{
String query = params[0];
MALApi api = new MALApi(context);
switch (job){
case 1:
_result = api.getMostPopular(getListType(),1); //if job == 1 then get the most popular
break;
case 2:
_result = api.getTopRated(getListType(),1); //if job == 2 then get the top rated
break;
case 3:
_result = api.getJustAdded(getListType(),1); //if job == 3 then get the Just Added
break;
case 4:
_result = api.getUpcoming(getListType(),1); //if job == 4 then get the upcoming
break;
}
}catch (Exception e){
System.out.println("ERROR: doInBackground() at home.java");
}
return null;
}
@Override
protected void onPostExecute(Void result) {
String type = MALApi.getListTypeString(getListType());
try {
switch (listType) {
case ANIME: {
ArrayList<AnimeRecord> list = new ArrayList<AnimeRecord>();
if (_result.length() == 0) {
System.out.println("No records, retry! (Home.java)");//TODO shouldnt return nothing, but...
af.scrollToTop();
mf.scrollToTop();
if (af.getMode()== 1){
getTopRated(BaseMALApi.ListType.ANIME);
} else if (af.getMode()== 2){
getMostPopular(BaseMALApi.ListType.ANIME);
} else if (af.getMode()== 3){
getJustAdded(BaseMALApi.ListType.ANIME);
} else if (af.getMode()== 4){
getUpcoming(BaseMALApi.ListType.ANIME);
}
af.scrollListener.resetPageNumber();
} else {
for (int i = 0; i < _result.length(); i++) {
JSONObject genre = (JSONObject) _result.get(i);
AnimeRecord record = new AnimeRecord(mManager.getRecordDataFromJSONObject(genre, type));
list.add(record);
}
}
af.setAnimeRecords(list);
break;
}
case MANGA: {
ArrayList<MangaRecord> list = new ArrayList<MangaRecord>();
if (_result.length() == 0) {
System.out.println("No records");//TODO shouldnt return nothing, but...
}
else {
for (int i = 0; i < _result.length(); i++) {
JSONObject genre = (JSONObject) _result.get(i);
MangaRecord record = new MangaRecord(mManager.getRecordDataFromJSONObject(genre, type));
list.add(record);
}
}
mf.setMangaRecords(list);
break;
}
}
} catch (Exception e) {
Log.e(SearchActivity.class.getName(), Log.getStackTraceString(e));
}
Home.this.af.scrollListener.notifyMorePages();
}
}
/*private classes for nav drawer*/
private ActionBarHelper createActionBarHelper() {
return new ActionBarHelper();
}
public class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/* do stuff when drawer item is clicked here */
af.scrollToTop();
mf.scrollToTop();
if (!isNetworkAvailable()) {
if (position==0 || position==1){
}else{
position = 1;
maketext("No network connection available!");
}
}
switch (position){
case 0:
Intent intent = new Intent(context, net.somethingdreadful.MAL.ProfileActivity.class);
startActivity(intent);
break;
case 1:
af.getRecords(listType, "anime", false, Home.this.context);
mf.getRecords(listType, "manga", false, Home.this.context);
myList = true;
af.setMode(0);
mf.setMode(0);
break;
case 2:
getTopRated(BaseMALApi.ListType.ANIME);
mf.setMangaRecords(new ArrayList<MangaRecord>()); ////basically, since you can't get popular manga this is just a temporary measure to make the manga set empty, otherwise it would continue to display YOUR manga list
myList = false;
af.setMode(1);
mf.setMode(1);
af.scrollListener.resetPageNumber();
mf.scrollListener.resetPageNumber();
break;
case 3:
getMostPopular(BaseMALApi.ListType.ANIME);
mf.setMangaRecords(new ArrayList<MangaRecord>()); //basically, since you can't get popular manga this is just a temporary measure to make the manga set empty, otherwise it would continue to display YOUR manga list
myList = false;
af.setMode(2);
mf.setMode(2);
af.scrollListener.resetPageNumber();
mf.scrollListener.resetPageNumber();
break;
case 4:
getJustAdded(BaseMALApi.ListType.ANIME);
mf.setMangaRecords(new ArrayList<MangaRecord>()); //basically, since you can't get Just Added manga this is just a temporary measure to make the manga set empty, otherwise it would continue to display YOUR manga list
myList = false;
af.setMode(3);
mf.setMode(3);
af.scrollListener.resetPageNumber();
mf.scrollListener.resetPageNumber();
break;
case 5:
getUpcoming(BaseMALApi.ListType.ANIME);
mf.setMangaRecords(new ArrayList<MangaRecord>()); //basically, since you can't get Upcoming manga this is just a temporary measure to make the manga set empty, otherwise it would continue to display YOUR manga list
myList = false;
af.setMode(4);
mf.setMode(4);
af.scrollListener.resetPageNumber();
mf.scrollListener.resetPageNumber();
break;
}
Home.this.supportInvalidateOptionsMenu();
//This part is for figuring out which item in the nav drawer is selected and highlighting it with colors
mPreviousView = mActiveView;
if (mPreviousView != null)
mPreviousView.setBackgroundColor(Color.parseColor("#333333")); //dark color
mActiveView = view;
mActiveView.setBackgroundColor(Color.parseColor("#38B2E1")); //blue color
mDrawerLayout.closeDrawer(listView);
}
}
private class DemoDrawerListener implements DrawerLayout.DrawerListener {
final ActionBar actionBar = getSupportActionBar();
@Override
public void onDrawerOpened(View drawerView) {
mDrawerToggle.onDrawerOpened(drawerView);
mActionBar.onDrawerOpened();
}
@Override
public void onDrawerClosed(View drawerView) {
mDrawerToggle.onDrawerClosed(drawerView);
mActionBar.onDrawerClosed();
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
mDrawerToggle.onDrawerSlide(drawerView, slideOffset);
}
@Override
public void onDrawerStateChanged(int newState) {
mDrawerToggle.onDrawerStateChanged(newState);
}
}
private class ActionBarHelper {
private final ActionBar mActionBar;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private ActionBarHelper() {
mActionBar = getSupportActionBar();
}
public void init() {
mActionBar.setDisplayHomeAsUpEnabled(true);
mActionBar.setHomeButtonEnabled(true);
mTitle = mDrawerTitle = getTitle();
}
/**
* When the drawer is closed we restore the action bar state reflecting
* the specific contents in view.
*/
public void onDrawerClosed() {
mActionBar.setTitle(mTitle);
}
/**
* When the drawer is open we set the action bar to a generic title. The
* action bar should only contain data relevant at the top level of the
* nav hierarchy represented by the drawer, as the rest of your content
* will be dimmed down and non-interactive.
*/
public void onDrawerOpened() {
mActionBar.setTitle(mDrawerTitle);
}
public void setTitle(CharSequence title) {
mTitle = title;
}
}
} |
import java.util.ArrayList;
public interface BitWeavingVInterface {
long[] query(Query queryName, long cst);
long[] query(Query queryName, long cst1, long cst2);
int size();
void add(long nb);
void add(long[] nb);
ArrayList<BWVSegment> getColumn();
long[] complexQuery(String query);
} |
package org.sagebionetworks.bridge.validators;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.sagebionetworks.bridge.BridgeUtils.COMMA_SPACE_JOINER;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.regex.Pattern;
import org.apache.commons.validator.routines.EmailValidator;
import org.sagebionetworks.bridge.BridgeConstants;
import org.sagebionetworks.bridge.BridgeUtils;
import org.sagebionetworks.bridge.models.accounts.StudyParticipant;
import org.sagebionetworks.bridge.models.studies.AndroidAppLink;
import org.sagebionetworks.bridge.models.studies.AppleAppLink;
import org.sagebionetworks.bridge.models.studies.EmailTemplate;
import org.sagebionetworks.bridge.models.studies.OAuthProvider;
import org.sagebionetworks.bridge.models.studies.PasswordPolicy;
import org.sagebionetworks.bridge.models.studies.SmsTemplate;
import org.sagebionetworks.bridge.models.studies.Study;
import org.sagebionetworks.bridge.models.upload.UploadFieldDefinition;
import com.google.common.collect.Sets;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
@Component
public class StudyValidator implements Validator {
public static final StudyValidator INSTANCE = new StudyValidator();
private static final int MAX_SYNAPSE_LENGTH = 250;
private static final Pattern FINGERPRINT_PATTERN = Pattern.compile("^[0-9a-fA-F:]{95,95}$");
protected static final String EMAIL_ERROR = "is not a comma-separated list of email addresses";
/**
* Inspect StudyParticipant for its field names; these cannot be used as user profile attributes because UserProfile
* collapses these values into the top-level JSON it returns (unlike StudyParticipant where these values are a map
* under the attribute property).
*/
private static final Set<String> RESERVED_ATTR_NAMES = Sets.newHashSet();
static {
Field[] fields = StudyParticipant.class.getDeclaredFields();
for (Field field : fields) {
if (!Modifier.isStatic(field.getModifiers())) {
RESERVED_ATTR_NAMES.add(field.getName());
}
}
}
@Override
public boolean supports(Class<?> clazz) {
return Study.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object obj, Errors errors) {
Study study = (Study)obj;
if (isBlank(study.getIdentifier())) {
errors.rejectValue("identifier", "is required");
} else {
if (!study.getIdentifier().matches(BridgeConstants.BRIDGE_IDENTIFIER_PATTERN)) {
errors.rejectValue("identifier", "must contain only lower-case letters and/or numbers with optional dashes");
}
if (study.getIdentifier().length() < 2) {
errors.rejectValue("identifier", "must be at least 2 characters");
}
}
if (study.getActivityEventKeys().stream()
.anyMatch(k -> !k.matches(BridgeConstants.BRIDGE_IDENTIFIER_PATTERN))) {
errors.rejectValue("activityEventKeys", "must contain only lower-case letters and/or numbers with " +
"optional dashes");
}
if (isBlank(study.getName())) {
errors.rejectValue("name", "is required");
}
if (study.getShortName() != null && study.getShortName().length() > 10) {
errors.rejectValue("shortName", "must be 10 characters or less");
}
if (isBlank(study.getSponsorName())) {
errors.rejectValue("sponsorName", "is required");
}
if (isBlank(study.getSupportEmail())) {
errors.rejectValue("supportEmail", "is required");
} else {
validateEmail(errors, study.getSupportEmail(), "supportEmail");
}
validateEmail(errors, study.getTechnicalEmail(), "technicalEmail");
validateEmail(errors, study.getConsentNotificationEmail(), "consentNotificationEmail");
// uploadMetadatafieldDefinitions
List<UploadFieldDefinition> uploadMetadataFieldDefList = study.getUploadMetadataFieldDefinitions();
if (!uploadMetadataFieldDefList.isEmpty()) {
UploadFieldDefinitionListValidator.INSTANCE.validate(study.getUploadMetadataFieldDefinitions(), errors,
"uploadMetadataFieldDefinitions");
}
// These *should* be set if they are null, with defaults
if (study.getPasswordPolicy() == null) {
errors.rejectValue("passwordPolicy", "is required");
} else {
errors.pushNestedPath("passwordPolicy");
PasswordPolicy policy = study.getPasswordPolicy();
if (!isInRange(policy.getMinLength(), 2)) {
errors.rejectValue("minLength", "must be 2-"+PasswordPolicy.FIXED_MAX_LENGTH+" characters");
}
errors.popNestedPath();
}
if (study.getMinAgeOfConsent() < 0) {
errors.rejectValue("minAgeOfConsent", "must be zero (no minimum age of consent) or higher");
}
if (study.getAccountLimit() < 0) {
errors.rejectValue("accountLimit", "must be zero (no limit set) or higher");
}
validateEmailTemplate(errors, study.getVerifyEmailTemplate(), "verifyEmailTemplate", "${url}", "${emailVerificationUrl}");
validateEmailTemplate(errors, study.getResetPasswordTemplate(), "resetPasswordTemplate", "${url}", "${resetPasswordUrl}");
// Existing studies don't have the template, we use a default template. Okay to be missing.
if (study.getSignedConsentTemplate() != null) {
validateEmailTemplate(errors, study.getSignedConsentTemplate(), "signedConsentTemplate");
}
if (study.getEmailSignInTemplate() != null) {
validateEmailTemplate(errors, study.getEmailSignInTemplate(), "emailSignInTemplate", "${url}", "${emailSignInUrl}",
"${token}");
}
if (study.getAccountExistsTemplate() != null) {
validateEmailTemplate(errors, study.getAccountExistsTemplate(), "accountExistsTemplate", "${url}",
"${emailSignInUrl}", "${resetPasswordUrl}");
}
validateSmsTemplate(errors, study.getResetPasswordSmsTemplate(), "resetPasswordSmsTemplate", "${url}", "${resetPasswordUrl}");
validateSmsTemplate(errors, study.getPhoneSignInSmsTemplate(), "phoneSignInSmsTemplate", "${token}");
validateSmsTemplate(errors, study.getAppInstallLinkSmsTemplate(), "appInstallLinkSmsTemplate", "${url}", "${appInstallUrl}");
validateSmsTemplate(errors, study.getVerifyPhoneSmsTemplate(), "verifyPhoneSmsTemplate", "${token}");
validateSmsTemplate(errors, study.getAccountExistsSmsTemplate(), "accountExistsSmsTemplate", "${token}",
"${resetPasswordUrl}");
// Existing studies don't have the template, we use a default template. Okay to be missing.
if (study.getSignedConsentSmsTemplate() != null) {
validateSmsTemplate(errors, study.getSignedConsentSmsTemplate(), "signedConsentSmsTemplate", "${consentUrl}");
}
for (String userProfileAttribute : study.getUserProfileAttributes()) {
if (RESERVED_ATTR_NAMES.contains(userProfileAttribute)) {
String msg = String.format("'%s' conflicts with existing user profile property", userProfileAttribute);
errors.rejectValue("userProfileAttributes", msg);
}
// For backwards compatibility, we require this to be a valid JavaScript identifier.
if (!userProfileAttribute.matches(BridgeConstants.JS_IDENTIFIER_PATTERN)) {
String msg = String.format("'%s' must contain only digits, letters, underscores and dashes, and cannot start with a dash", userProfileAttribute);
errors.rejectValue("userProfileAttributes", msg);
}
}
validateDataGroupNamesAndFitForSynapseExport(errors, study.getDataGroups());
// emailVerificationEnabled=true (public study):
// externalIdValidationEnabled and externalIdRequiredOnSignup can vary independently
// emailVerificationEnabled=false:
// externalIdValidationEnabled and externalIdRequiredOnSignup must both be true
if (!study.isEmailVerificationEnabled()) {
if (!study.isExternalIdRequiredOnSignup()) {
errors.rejectValue("externalIdRequiredOnSignup", "cannot be disabled if email verification has been disabled");
}
if (!study.isExternalIdValidationEnabled()) {
errors.rejectValue("externalIdValidationEnabled", "cannot be disabled if email verification has been disabled");
}
}
// Links in installedLinks are length-constrained by SMS.
if (!study.getInstallLinks().isEmpty()) {
for (Map.Entry<String,String> entry : study.getInstallLinks().entrySet()) {
if (isBlank(entry.getValue())) {
errors.rejectValue("installLinks", "cannot be blank");
} else if (entry.getValue().length() > BridgeConstants.SMS_CHARACTER_LIMIT) {
errors.rejectValue("installLinks", "cannot be longer than "+BridgeConstants.SMS_CHARACTER_LIMIT+" characters");
}
}
}
for (Map.Entry<String, OAuthProvider> entry : study.getOAuthProviders().entrySet()) {
String fieldName = "oauthProviders["+entry.getKey()+"]";
OAuthProvider provider = entry.getValue();
if (provider == null) {
errors.rejectValue(fieldName, "is required");
} else {
errors.pushNestedPath(fieldName);
if (isBlank(provider.getClientId())) {
errors.rejectValue("clientId", "is required");
}
if (isBlank(provider.getSecret())) {
errors.rejectValue("secret", "is required");
}
if (isBlank(provider.getEndpoint())) {
errors.rejectValue("endpoint", "is required");
}
if (isBlank(provider.getCallbackUrl())) {
errors.rejectValue("callbackUrl", "is required");
}
errors.popNestedPath();
}
}
// app link configuration is not required, but if it is provided, we validate it
if (study.getAppleAppLinks() != null && !study.getAppleAppLinks().isEmpty()) {
validateAppLinks(errors, "appleAppLinks", study.getAppleAppLinks(), (AppleAppLink link) -> {
if (isBlank(link.getAppId())) {
errors.rejectValue("appID", "cannot be blank or null");
}
if (link.getPaths() == null || link.getPaths().isEmpty()) {
errors.rejectValue("paths", "cannot be null or empty");
} else {
for (int j=0; j < link.getPaths().size(); j++) {
String path = link.getPaths().get(j);
if (isBlank(path)) {
errors.rejectValue("paths["+j+"]", "cannot be blank or empty");
}
}
}
return link.getAppId();
});
}
if (study.getAndroidAppLinks() != null && !study.getAndroidAppLinks().isEmpty()) {
validateAppLinks(errors, "androidAppLinks", study.getAndroidAppLinks(), (AndroidAppLink link) -> {
if (isBlank(link.getNamespace())) {
errors.rejectValue("namespace", "cannot be blank or null");
}
if (isBlank(link.getPackageName())) {
errors.rejectValue("package_name", "cannot be blank or null");
}
if (link.getFingerprints() == null || link.getFingerprints().isEmpty()) {
errors.rejectValue("sha256_cert_fingerprints", "cannot be null or empty");
} else {
for (int i=0; i < link.getFingerprints().size(); i++) {
String fingerprint = link.getFingerprints().get(i);
if (isBlank(fingerprint)) {
errors.rejectValue("sha256_cert_fingerprints["+i+"]", "cannot be null or empty");
} else if (!FINGERPRINT_PATTERN.matcher(fingerprint).matches()){
errors.rejectValue("sha256_cert_fingerprints["+i+"]", "is not a SHA 256 fingerprint");
}
}
}
return link.getNamespace() + "." + link.getPackageName();
});
}
}
private void validateEmail(Errors errors, String emailString, String fieldName) {
if (emailString != null) {
Set<String> emails = BridgeUtils.commaListToOrderedSet(emailString);
// The "if" clause catches cases like "" which are weeded out of the ordered set
if (emails.isEmpty()) {
errors.rejectValue(fieldName, EMAIL_ERROR);
} else {
for (String email : emails) {
if (!EmailValidator.getInstance().isValid(email)) {
errors.rejectValue(fieldName, EMAIL_ERROR);
}
}
}
}
}
private <T> void validateAppLinks(Errors errors, String propName, List<T> appLinks, Function<T,String> itemValidator) {
boolean hasNotRecordedDuplicates = true;
Set<String> uniqueAppIDs = Sets.newHashSet();
for (int i=0; i < appLinks.size(); i++) {
T link = appLinks.get(i);
String fieldName = propName+"["+i+"]";
if (link == null) {
errors.rejectValue(fieldName, "cannot be null");
} else {
errors.pushNestedPath(fieldName);
String id = itemValidator.apply(link);
errors.popNestedPath();
if (id != null && hasNotRecordedDuplicates && !uniqueAppIDs.add(id)) {
errors.rejectValue(propName, "cannot contain duplicate entries");
hasNotRecordedDuplicates = false;
}
}
}
}
private boolean isInRange(int value, int min) {
return (value >= min && value <= PasswordPolicy.FIXED_MAX_LENGTH);
}
private void validateEmailTemplate(Errors errors, EmailTemplate template, String fieldName, String... templateVariables) {
if (template == null) {
errors.rejectValue(fieldName, "is required");
} else {
errors.pushNestedPath(fieldName);
if (isBlank(template.getSubject())) {
errors.rejectValue("subject", "cannot be blank");
}
if (isBlank(template.getBody())) {
errors.rejectValue("body", "cannot be blank");
} else if (templateVariables.length > 0) {
boolean missingTemplateVariable = true;
for (int i=0; i < templateVariables.length; i++) {
if (template.getBody().contains(templateVariables[i])) {
missingTemplateVariable = false;
break;
}
}
if (missingTemplateVariable) {
errors.rejectValue("body", "must contain one of these template variables: "
+ BridgeUtils.COMMA_SPACE_JOINER.join(templateVariables));
}
}
errors.popNestedPath();
}
}
private void validateSmsTemplate(Errors errors, SmsTemplate template, String fieldName, String... templateVariables) {
if (template != null) {
errors.pushNestedPath(fieldName);
// This is not necessarily going to prevent the message from be split because the template variables haven't
// been substituted. We do calculate this more accurately in the study manager right now.
if (isBlank(template.getMessage())) {
errors.rejectValue("message", "cannot be blank");
} else if (template.getMessage().length() > 160) {
errors.rejectValue("message", "cannot be more than 160 characters");
} else {
boolean missingTemplateVariable = true;
for (int i=0; i < templateVariables.length; i++) {
if (template.getMessage().contains(templateVariables[i])) {
missingTemplateVariable = false;
break;
}
}
if (missingTemplateVariable) {
errors.rejectValue("message", "must contain one of these template variables: "
+ BridgeUtils.COMMA_SPACE_JOINER.join(templateVariables));
}
}
errors.popNestedPath();
}
}
private void validateDataGroupNamesAndFitForSynapseExport(Errors errors, Set<String> dataGroups) {
if (dataGroups != null) {
for (String group : dataGroups) {
if (!group.matches(BridgeConstants.SYNAPSE_IDENTIFIER_PATTERN)) {
errors.rejectValue("dataGroups", "contains invalid tag '"+group+"' (only letters, numbers, underscore and dash allowed)");
}
}
String ser = COMMA_SPACE_JOINER.join(dataGroups);
if (ser.length() > MAX_SYNAPSE_LENGTH) {
errors.rejectValue("dataGroups", "will not export to Synapse (string is over "+MAX_SYNAPSE_LENGTH+" characters: '" + ser + "')");
}
}
}
} |
package com.kuxhausen.huemore.persistence;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
import android.util.SparseArray;
import com.google.gson.Gson;
import com.kuxhausen.huemore.persistence.DatabaseDefinitions.AlarmColumns;
import com.kuxhausen.huemore.persistence.DatabaseDefinitions.GroupColumns;
import com.kuxhausen.huemore.persistence.DatabaseDefinitions.MoodColumns;
import com.kuxhausen.huemore.persistence.DatabaseDefinitions.PreferenceKeys;
import com.kuxhausen.huemore.state.Event;
import com.kuxhausen.huemore.state.Mood;
import com.kuxhausen.huemore.state.api.BulbState;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "huemore.db";
private static final int DATABASE_VERSION = 5;
Gson gson = new Gson();
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + MoodColumns.TABLE_NAME + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY," + MoodColumns.MOOD
+ " TEXT," + MoodColumns.STATE + " TEXT" + ");");
db.execSQL("CREATE TABLE " + GroupColumns.TABLE_NAME + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY,"
+ GroupColumns.GROUP + " TEXT," + GroupColumns.PRECEDENCE
+ " INTEGER," + GroupColumns.BULB + " INTEGER" + ");");
this.onUpgrade(db, 1, DATABASE_VERSION);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch(oldVersion){
case 1:
{
ContentValues cv = new ContentValues();
/** update 2.4/2.5/switch to serialized b64 **/
String[] moodColumns = {MoodColumns.MOOD, MoodColumns.STATE};
Cursor cursor = db.query(DatabaseDefinitions.MoodColumns.TABLE_NAME, moodColumns, null, null, null, null, null);
HashMap<String,ArrayList<String>> moodStateMap = new HashMap<String,ArrayList<String>>();
while (cursor.moveToNext()) {
String mood = cursor.getString(0);
String state = cursor.getString(1);
if(mood!=null && state!=null && !mood.equals("") && !state.equals("") && !state.equals("{}")){
ArrayList<String> states;
if(moodStateMap.containsKey(mood))
states = moodStateMap.get(mood);
else
states = new ArrayList<String>();
states.add(state);
moodStateMap.put(mood, states);
}
}
db.execSQL("DROP TABLE " + MoodColumns.TABLE_NAME);
db.execSQL("CREATE TABLE " + MoodColumns.TABLE_NAME + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY," + MoodColumns.MOOD
+ " TEXT," + MoodColumns.STATE + " TEXT" + ");");
String[] gSelectionArgs = { "ALL", ((char) 8) + "ALL" };
db.delete(GroupColumns.TABLE_NAME,
DatabaseDefinitions.GroupColumns.GROUP + "=? or "
+ DatabaseDefinitions.GroupColumns.GROUP + "=?",
gSelectionArgs);
//remove standard moods that are no longer correct
String[] moodsToRemove = {"OFF", "Reading", "Relax", "Concentrate",
"Energize", "Red", "Orange", "Blue", "Romantic",
"Rainbow", ((char) 8) + "OFF", ((char) 8) + "ON", ((char) 8) + "RANDOM"};
for(String removeKey : moodsToRemove){
moodStateMap.remove(removeKey);
}
String[] simpleNames = {"Reading","Relax","Concentrate","Energize", "Deep Sea", "Deep Sea", "Deep Sea", "Fruit", "Fruit", "Fruit"};
int[] simpleSat = {144, 211 ,49, 232, 253, 230, 253, 244, 254, 173};
int[] simpleHue = {15331, 13122, 33863, 34495, 45489, 1111, 45489, 15483, 25593, 64684};
for(int i = 0; i< simpleNames.length; i++){
BulbState hs = new BulbState();
hs.sat=(short)simpleSat[i];
hs.hue=simpleHue[i];
hs.on=true;
hs.effect="none";
ArrayList<String> states;
if(moodStateMap.containsKey(simpleNames[i]))
states = moodStateMap.get(simpleNames[i]);
else
states = new ArrayList<String>();
states.add(gson.toJson(hs));
moodStateMap.put(simpleNames[i], states);
}
for(String key : moodStateMap.keySet()){
ArrayList<String> stateJson = moodStateMap.get(key);
//bug fix in case there are any empty bulbstates in the old system
for(int i = 0; i<stateJson.size(); i++){
if(stateJson.get(i)==null || gson.fromJson(stateJson.get(i),BulbState.class)==null)
stateJson.remove(i);
}
Event[] events = new Event[stateJson.size()];
for(int i = 0; i< stateJson.size(); i++){
Event e = new Event();
e.state = gson.fromJson(stateJson.get(i), BulbState.class);
e.time=0;
e.channel=i;
events[i]=e;
}
Mood m = new Mood();
m.usesTiming=false;
m.timeAddressingRepeatPolicy=false;
m.setNumChannels(stateJson.size());
m.events = events;
cv.put(MoodColumns.MOOD, key);
cv.put(MoodColumns.STATE, HueUrlEncoder.encode(m));
db.insert(MoodColumns.TABLE_NAME, null, cv);
}
}
case 2:
{
ContentValues cv = new ContentValues();
String[] moodColumns = {MoodColumns.MOOD, MoodColumns.STATE};
Cursor cursor = db.query(DatabaseDefinitions.MoodColumns.TABLE_NAME, moodColumns, null, null, null, null, null);
HashMap<String,Mood> moodMap = new HashMap<String,Mood>();
while (cursor.moveToNext()) {
try {
String name = cursor.getString(0);
Mood mood = HueUrlEncoder.decode(cursor.getString(1)).second.first;
moodMap.put(name, mood);
} catch (InvalidEncodingException e){
} catch (FutureEncodingException e) {
}
}
moodMap.remove("Fruity");
moodMap.remove("Sunset");
db.execSQL("DROP TABLE IF EXISTS " + MoodColumns.TABLE_NAME);
db.execSQL("CREATE TABLE " + MoodColumns.TABLE_NAME + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY," + MoodColumns.MOOD
+ " TEXT," + MoodColumns.STATE + " TEXT" + ");");
for(String key : moodMap.keySet()){
cv.put(MoodColumns.MOOD, key);
cv.put(MoodColumns.STATE, HueUrlEncoder.encode(moodMap.get(key)));
db.insert(MoodColumns.TABLE_NAME, null, cv);
}
//Construct animated fruit mood
{
BulbState bs1 = new BulbState();
bs1.on = true;
bs1.transitiontime = 50;
bs1.sat = 244;
bs1.hue = 15483;
BulbState bs2 = new BulbState();
bs2.on = true;
bs2.transitiontime = 50;
bs2.sat = 254;
bs2.hue= 25593;
BulbState bs3 = new BulbState();
bs3.on = true;
bs3.transitiontime = 50;
bs3.sat = 173;
bs3.hue= 64684;
Event e1 = new Event(bs1, 0, 0);
Event e2 = new Event(bs2, 1, 0);
Event e3 = new Event(bs3, 2, 0);
Event e4 = new Event(bs2, 0, 100);
Event e5 = new Event(bs3, 1, 100);
Event e6 = new Event(bs1, 2, 100);
Event e7 = new Event(bs3, 0, 200);
Event e8 = new Event(bs1, 1, 200);
Event e9 = new Event(bs2, 2, 200);
Event[] events = {e1,e2,e3,e4,e5,e6,e7,e8,e9};
Mood m = new Mood();
m.usesTiming = true;
m.timeAddressingRepeatPolicy = false;
m.setNumChannels(3);
m.setInfiniteLooping(true);
m.events = events;
m.loopIterationTimeLength = 300;
cv.put(MoodColumns.MOOD, "Fruity");
cv.put(MoodColumns.STATE, HueUrlEncoder.encode(m));
db.insert(MoodColumns.TABLE_NAME, null, cv);
}
db.execSQL("DROP TABLE IF EXISTS " + AlarmColumns.TABLE_NAME);
db.execSQL("CREATE TABLE IF NOT EXISTS " + AlarmColumns.TABLE_NAME + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY,"
+ AlarmColumns.STATE + " TEXT,"
+ AlarmColumns.INTENT_REQUEST_CODE + " INTEGER" + ");");
}
case 3:
{
//remove any nameless moods
ContentValues cv = new ContentValues();
String[] moodColumns = {MoodColumns.MOOD, MoodColumns.STATE};
Cursor moodCursor = db.query(DatabaseDefinitions.MoodColumns.TABLE_NAME, moodColumns, null, null, null, null, null);
HashMap<String,Mood> moodMap = new HashMap<String,Mood>();
while (moodCursor.moveToNext()) {
try {
String name = moodCursor.getString(0);
Mood mood = HueUrlEncoder.decode(moodCursor.getString(1)).second.first;
moodMap.put(name, mood);
} catch (InvalidEncodingException e){
} catch (FutureEncodingException e) {
}
}
moodMap.remove("");
moodMap.remove(null);
db.execSQL("DROP TABLE IF EXISTS " + MoodColumns.TABLE_NAME);
db.execSQL("CREATE TABLE " + MoodColumns.TABLE_NAME + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY," + MoodColumns.MOOD
+ " TEXT," + MoodColumns.STATE + " TEXT" + ");");
for(String key : moodMap.keySet()){
try{
cv.put(MoodColumns.MOOD, key);
cv.put(MoodColumns.STATE, HueUrlEncoder.encode(moodMap.get(key)));
db.insert(MoodColumns.TABLE_NAME, null, cv);
} catch (Exception e) {
}
}
//remove any nameless groups
String[] gSelectionArgs = { ""};
db.delete(GroupColumns.TABLE_NAME,
DatabaseDefinitions.GroupColumns.GROUP + "=?",
gSelectionArgs);
}
case 4:
{
String[] simpleNames = {"Reading","Relax","Concentrate","Energize", "Deep Sea1", "Deep Sea2", "Fruit1", "Fruit2", "Fruit3"};
int[] simpleSat = {144, 211, 49, 232, 253, 230, 244, 254, 173};
int[] simpleHue = {15331, 13122, 33863, 34495, 45489, 1111, 15483, 25593, 64684};
float[] simpleX = {0.4571f, 0.5119f, 0.368f, 0.3151f, 0.1859f, 0.6367f, 0.5089f, 0.5651f, 0.4081f};
float[] simpleY = {0.4123f, 0.4147f, 0.3686f, 0.3252f, 0.0771f, 0.3349f, 0.438f, 0.3306f, 0.518f};
SparseArray<BulbState> conversionMap = new SparseArray<BulbState>();
for(int i = 0; i< simpleHue.length; i++){
BulbState conversion = new BulbState();
conversion.sat = (short) simpleSat[i];
conversion.hue = simpleHue[i];
Float[] conversionXY = {simpleX[i], simpleY[i]};
conversion.xy = conversionXY;
conversionMap.put(conversion.hue,conversion);
}
ContentValues cv = new ContentValues();
String[] moodColumns = {MoodColumns.MOOD, MoodColumns.STATE};
Cursor moodCursor = db.query(DatabaseDefinitions.MoodColumns.TABLE_NAME, moodColumns, null, null, null, null, null);
HashMap<String,Mood> moodMap = new HashMap<String,Mood>();
while (moodCursor.moveToNext()) {
try {
String name = moodCursor.getString(0);
Mood mood = HueUrlEncoder.decode(moodCursor.getString(1)).second.first;
for(Event e : mood.events){
if(e.state.hue!=null && e.state.sat!=null && conversionMap.get(e.state.hue)!=null && conversionMap.get(e.state.hue).sat.equals(e.state.sat)){
BulbState conversion = conversionMap.get(e.state.hue);
e.state.hue = null;
e.state.sat = null;
e.state.xy = conversion.xy;
}
}
moodMap.put(name, mood);
} catch (InvalidEncodingException e){
} catch (FutureEncodingException e) {
}
}
try {
if(!moodMap.containsKey("Gentle Sunrise"))
moodMap.put("Gentle Sunrise", HueUrlEncoder.decode("AQSAAQAAgDQApAGAJzfkJ8o85KtGLQMAk8j5riCB-ZYxfgDAZPIyfiB9bL5VtUAAMAFgwCSAQwA=").second.first);
if(!moodMap.containsKey("Gentle Sunset"))
moodMap.put("Gentle Sunset", HueUrlEncoder.decode("AQSAAQAAgDQApAGAI-cHhj7kW1GOBwCTyd34iaDH-GrSiQHAJDAAMAFgQBWAQwA=").second.first);
if(!moodMap.containsKey("Living Night"))
moodMap.put("Living Night", HueUrlEncoder.decode("AfKHAAAAAEwAaGJWfu4rZb4IfDsAk4m_-TkqEvniQEQATAAEFBAVACYA").second.first);
if(!moodMap.containsKey("f.lux"))
moodMap.put("f.lux", HueUrlEncoder.decode("AQxA5RmHN7_yNEQDWOqnAoAj5-ux8ufr6SQBAJDI-YGhD_lWlOMBACRyvitIYL5ljB8AAAFQFGIoEQAAAA==").second.first);
} catch (InvalidEncodingException e) {
} catch (FutureEncodingException e) {
}
db.execSQL("DROP TABLE IF EXISTS " + MoodColumns.TABLE_NAME);
db.execSQL("CREATE TABLE " + MoodColumns.TABLE_NAME + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY," + MoodColumns.MOOD
+ " TEXT," + MoodColumns.STATE + " TEXT" + ");");
for(String key : moodMap.keySet()){
cv.put(MoodColumns.MOOD, key);
cv.put(MoodColumns.STATE, HueUrlEncoder.encode(moodMap.get(key)));
db.insert(MoodColumns.TABLE_NAME, null, cv);
}
}
}
}
} |
package org.mozilla.focus.web;
import android.content.Context;
import android.support.v4.view.NestedScrollingChild;
import android.support.v4.view.NestedScrollingChildHelper;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import org.mozilla.gecko.GeckoView;
import org.mozilla.gecko.GeckoViewSettings;
public class NestedGeckoView extends GeckoView implements NestedScrollingChild {
private int mLastY;
private final int[] mScrollOffset = new int[2];
private final int[] mScrollConsumed = new int[2];
private int mNestedOffsetY;
private NestedScrollingChildHelper mChildHelper;
public NestedGeckoView(Context context, AttributeSet attrs, GeckoViewSettings settings) {
super(context, attrs, settings);
mChildHelper = new NestedScrollingChildHelper(this);
setNestedScrollingEnabled(true);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
boolean eventHandled = false;
final MotionEvent event = MotionEvent.obtain(ev);
final int action = event.getActionMasked();
if (action == MotionEvent.ACTION_DOWN) {
mNestedOffsetY = 0;
}
final int eventY = (int) event.getY();
event.offsetLocation(0, mNestedOffsetY);
switch (action) {
case MotionEvent.ACTION_MOVE:
int deltaY = mLastY - eventY;
if (dispatchNestedPreScroll(0, deltaY, mScrollConsumed, mScrollOffset)) {
deltaY -= mScrollConsumed[1];
mLastY = eventY - mScrollOffset[1];
event.offsetLocation(0, -mScrollOffset[1]);
mNestedOffsetY += mScrollOffset[1];
}
eventHandled = super.onTouchEvent(event);
if (dispatchNestedScroll(0, mScrollOffset[1], 0, deltaY, mScrollOffset)) {
event.offsetLocation(0, mScrollOffset[1]);
mNestedOffsetY += mScrollOffset[1];
mLastY -= mScrollOffset[1];
}
break;
case MotionEvent.ACTION_DOWN:
eventHandled = super.onTouchEvent(event);
mLastY = eventY;
startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
eventHandled = super.onTouchEvent(event);
stopNestedScroll();
break;
default:
// We don't care about other touch events
}
return eventHandled;
}
@Override
public void setNestedScrollingEnabled(boolean enabled) {
mChildHelper.setNestedScrollingEnabled(enabled);
}
@Override
public boolean isNestedScrollingEnabled() {
return mChildHelper.isNestedScrollingEnabled();
}
@Override
public boolean startNestedScroll(int axes) {
return mChildHelper.startNestedScroll(axes);
}
@Override
public void stopNestedScroll() {
mChildHelper.stopNestedScroll();
}
@Override
public boolean hasNestedScrollingParent() {
return mChildHelper.hasNestedScrollingParent();
}
@Override
public boolean dispatchNestedScroll(int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed, int[] offsetInWindow) {
return mChildHelper.dispatchNestedScroll(dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, offsetInWindow);
}
@Override
public boolean dispatchNestedPreScroll(int dx, int dy, int[] consumed, int[] offsetInWindow) {
return mChildHelper.dispatchNestedPreScroll(dx, dy, consumed, offsetInWindow);
}
@Override
public boolean dispatchNestedFling(float velocityX, float velocityY, boolean consumed) {
return mChildHelper.dispatchNestedFling(velocityX, velocityY, consumed);
}
@Override
public boolean dispatchNestedPreFling(float velocityX, float velocityY) {
return mChildHelper.dispatchNestedPreFling(velocityX, velocityY);
}
} |
package org.mozilla.focus.web;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import org.json.JSONException;
import org.json.JSONObject;
import org.mozilla.focus.browser.LocalizedContent;
import org.mozilla.focus.session.Session;
import org.mozilla.focus.telemetry.TelemetryWrapper;
import org.mozilla.focus.utils.AppConstants;
import org.mozilla.focus.utils.IntentUtils;
import org.mozilla.focus.utils.Settings;
import org.mozilla.focus.utils.UrlUtils;
import org.mozilla.gecko.util.GeckoBundle;
import org.mozilla.geckoview.GeckoResponse;
import org.mozilla.geckoview.GeckoRuntime;
import org.mozilla.geckoview.GeckoRuntimeSettings;
import org.mozilla.geckoview.GeckoSession;
import org.mozilla.geckoview.GeckoSessionSettings;
import kotlin.text.Charsets;
/**
* WebViewProvider implementation for creating a Gecko based implementation of IWebView.
*/
public class WebViewProvider {
private static volatile GeckoRuntime geckoRuntime;
public static void preload(final Context context) {
createGeckoRuntimeIfNeeded(context);
}
public static View create(Context context, AttributeSet attrs) {
return new GeckoWebView(context, attrs);
}
public static void performCleanup(final Context context) {
// Nothing: does Gecko need extra private mode cleanup?
}
public static void performNewBrowserSessionCleanup() {
// Nothing: a WebKit work-around.
}
private static void createGeckoRuntimeIfNeeded(Context context) {
if (geckoRuntime == null) {
final GeckoRuntimeSettings.Builder runtimeSettingsBuilder =
new GeckoRuntimeSettings.Builder();
runtimeSettingsBuilder.useContentProcessHint(true);
runtimeSettingsBuilder.javaCrashReportingEnabled(true);
runtimeSettingsBuilder.nativeCrashReportingEnabled(true);
geckoRuntime = GeckoRuntime.create(context.getApplicationContext(), runtimeSettingsBuilder.build());
}
}
public static class GeckoWebView extends NestedGeckoView implements IWebView, SharedPreferences.OnSharedPreferenceChangeListener {
private static final String TAG = "GeckoWebView";
private Callback callback;
private String currentUrl = "about:blank";
private boolean canGoBack;
private boolean canGoForward;
private boolean isSecure;
private GeckoSession geckoSession;
private String webViewTitle;
private boolean isLoadingInternalUrl = false;
private String internalAboutData = null;
private String internalRightsData = null;
public GeckoWebView(Context context, AttributeSet attrs) {
super(context, attrs);
PreferenceManager.getDefaultSharedPreferences(context)
.registerOnSharedPreferenceChangeListener(this);
geckoSession = createGeckoSession();
setGeckoSession();
}
private void setGeckoSession() {
applyAppSettings();
updateBlocking();
geckoSession.setContentDelegate(createContentDelegate());
geckoSession.setProgressDelegate(createProgressDelegate());
geckoSession.setNavigationDelegate(createNavigationDelegate());
geckoSession.setTrackingProtectionDelegate(createTrackingProtectionDelegate());
geckoSession.setPromptDelegate(createPromptDelegate());
setSession(geckoSession, geckoRuntime);
}
private GeckoSession createGeckoSession() {
final GeckoSessionSettings settings = new GeckoSessionSettings();
settings.setBoolean(GeckoSessionSettings.USE_MULTIPROCESS, true);
settings.setBoolean(GeckoSessionSettings.USE_PRIVATE_MODE, true);
return new GeckoSession(settings);
}
@Override
public void setCallback(Callback callback) {
this.callback = callback;
}
@Override
public void onPause() {
}
@Override
public void goBack() {
geckoSession.goBack();
}
@Override
public void goForward() {
geckoSession.goForward();
}
@Override
public void reload() {
geckoSession.reload();
}
@Override
public void destroy() {
geckoSession.close();
}
@Override
public void onResume() {
if (TelemetryWrapper.dayPassedSinceLastUpload(getContext())) {
sendTelemetrySnapshots();
}
}
@Override
public void stopLoading() {
geckoSession.stop();
if (callback != null) {
callback.onPageFinished(isSecure);
}
}
@Override
public String getUrl() {
return currentUrl;
}
@Override
public void loadUrl(final String url) {
currentUrl = url;
geckoSession.loadUri(currentUrl);
if (callback != null) {
callback.onProgress(10);
}
}
@Override
public void cleanup() {
// We're running in a private browsing window, so nothing to do
}
@Override
public void setBlockingEnabled(boolean enabled) {
geckoSession.getSettings().setBoolean(GeckoSessionSettings.USE_TRACKING_PROTECTION, enabled);
if (enabled) {
updateBlocking();
applyAppSettings();
} else {
if (geckoSession != null) {
geckoRuntime.getSettings().setJavaScriptEnabled(true);
geckoRuntime.getSettings().setWebFontsEnabled(true);
}
}
if (callback != null) {
callback.onBlockingStateChanged(enabled);
}
}
@Override
public void setRequestDesktop(boolean shouldRequestDesktop) {
geckoSession.getSettings().setBoolean(GeckoSessionSettings.USE_DESKTOP_MODE, shouldRequestDesktop);
if (callback != null) {
callback.onRequestDesktopStateChanged(shouldRequestDesktop);
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String prefName) {
updateBlocking();
applyAppSettings();
}
private void applyAppSettings() {
geckoRuntime.getSettings().setJavaScriptEnabled(!Settings.getInstance(getContext()).shouldBlockJavaScript());
geckoRuntime.getSettings().setWebFontsEnabled(!Settings.getInstance(getContext()).shouldBlockWebFonts());
final int cookiesValue;
if (Settings.getInstance(getContext()).shouldBlockCookies() && Settings.getInstance(getContext()).shouldBlockThirdPartyCookies()) {
cookiesValue = GeckoRuntimeSettings.COOKIE_ACCEPT_NONE;
} else if (Settings.getInstance(getContext()).shouldBlockThirdPartyCookies()) {
cookiesValue = GeckoRuntimeSettings.COOKIE_ACCEPT_FIRST_PARTY;
} else {
cookiesValue = GeckoRuntimeSettings.COOKIE_ACCEPT_ALL;
}
geckoRuntime.getSettings().setCookieBehavior(cookiesValue);
}
private void updateBlocking() {
final Settings settings = Settings.getInstance(getContext());
int categories = 0;
if (settings.shouldBlockSocialTrackers()) {
categories += GeckoSession.TrackingProtectionDelegate.CATEGORY_SOCIAL;
}
if (settings.shouldBlockAdTrackers()) {
categories += GeckoSession.TrackingProtectionDelegate.CATEGORY_AD;
}
if (settings.shouldBlockAnalyticTrackers()) {
categories += GeckoSession.TrackingProtectionDelegate.CATEGORY_ANALYTIC;
}
if (settings.shouldBlockOtherTrackers()) {
categories += GeckoSession.TrackingProtectionDelegate.CATEGORY_CONTENT;
}
geckoRuntime.getSettings().setTrackingProtectionCategories(categories);
}
private GeckoSession.ContentDelegate createContentDelegate() {
return new GeckoSession.ContentDelegate() {
@Override
public void onTitleChange(GeckoSession session, String title) {
webViewTitle = title;
}
@Override
public void onFullScreen(GeckoSession session, boolean fullScreen) {
if (callback != null) {
if (fullScreen) {
callback.onEnterFullScreen(new FullscreenCallback() {
@Override
public void fullScreenExited() {
geckoSession.exitFullScreen();
}
}, null);
} else {
callback.onExitFullScreen();
}
}
}
@Override
public void onContextMenu(GeckoSession session, int screenX, int screenY, String uri, @ElementType int elementType, String elementSrc) {
if (callback != null) {
if (elementSrc != null && uri != null && elementType ==
ELEMENT_TYPE_IMAGE) {
callback.onLongPress(new HitTarget(true, uri, true, elementSrc));
} else if (elementSrc != null && elementType == ELEMENT_TYPE_IMAGE) {
callback.onLongPress(new HitTarget(false, null, true, elementSrc));
} else if (uri != null) {
callback.onLongPress(new HitTarget(true, uri, false, null));
}
}
}
@Override
public void onExternalResponse(GeckoSession session, GeckoSession.WebResponseInfo response) {
if (!AppConstants.supportsDownloadingFiles()) {
return;
}
final String scheme = Uri.parse(response.uri).getScheme();
if (scheme == null || (!scheme.equals("http") && !scheme.equals("https"))) {
// We are ignoring everything that is not http or https. This is a limitation of
// Android's download manager. There's no reason to show a download dialog for
// something we can't download anyways.
Log.w(TAG, "Ignoring download from non http(s) URL: " + response.uri);
return;
}
if (callback != null) {
// TODO: get user agent from GeckoView #2470
final Download download = new Download(response.uri, "Mozilla/5.0 (Android 8.1.0; Mobile; rv:60.0) Gecko/60.0 Firefox/60.0",
response.filename, response.contentType, response.contentLength,
Environment.DIRECTORY_DOWNLOADS);
callback.onDownloadStart(download);
}
}
@Override
public void onCrash(GeckoSession session) {
Log.i(TAG, "Crashed, opening new session");
geckoSession.close();
geckoSession = createGeckoSession();
setGeckoSession();
geckoSession.open(geckoRuntime);
geckoSession.loadUri(currentUrl);
}
@Override
public void onFocusRequest(GeckoSession geckoSession) {
}
@Override
public void onCloseRequest(GeckoSession geckoSession) {
// TODO: #2150
}
};
}
private GeckoSession.ProgressDelegate createProgressDelegate() {
return new GeckoSession.ProgressDelegate() {
@Override
public void onPageStart(GeckoSession session, String url) {
if (callback != null) {
callback.onPageStarted(url);
callback.resetBlockedTrackers();
callback.onProgress(25);
isSecure = false;
}
}
@Override
public void onPageStop(GeckoSession session, boolean success) {
if (callback != null) {
if (success) {
if (UrlUtils.isLocalizedContent(getUrl())) {
// When the url is a localized content, then the page is secure
isSecure = true;
}
callback.onProgress(100);
callback.onPageFinished(isSecure);
}
}
}
@Override
public void onSecurityChange(GeckoSession session,
GeckoSession.ProgressDelegate.SecurityInformation securityInfo) {
isSecure = securityInfo.isSecure;
if (UrlUtils.isLocalizedContent(getUrl())) {
// When the url is a localized content, then the page is secure
isSecure = true;
}
if (callback != null) {
callback.onSecurityChanged(isSecure, securityInfo.host, securityInfo.issuerOrganization);
}
}
};
}
private GeckoSession.NavigationDelegate createNavigationDelegate() {
return new GeckoSession.NavigationDelegate() {
public void onLocationChange(GeckoSession session, String url) {
// Save internal data: urls we should override to present focus:about, focus:rights
if (isLoadingInternalUrl) {
if (currentUrl.equals(LocalizedContent.URL_ABOUT)) {
internalAboutData = url;
} else if (currentUrl.equals(LocalizedContent.URL_RIGHTS)) {
internalRightsData = url;
}
isLoadingInternalUrl = false;
url = currentUrl;
}
// Check for internal data: urls to instead present focus:rights, focus:about
if (!TextUtils.isEmpty(internalAboutData) && internalAboutData.equals(url)) {
url = LocalizedContent.URL_ABOUT;
} else if (!TextUtils.isEmpty(internalRightsData) && internalRightsData.equals(url)) {
url = LocalizedContent.URL_RIGHTS;
}
currentUrl = url;
if (callback != null) {
callback.onURLChanged(url);
}
}
public void onCanGoBack(GeckoSession session, boolean canGoBack) {
GeckoWebView.this.canGoBack = canGoBack;
}
public void onCanGoForward(GeckoSession session, boolean canGoForward) {
GeckoWebView.this.canGoForward = canGoForward;
}
@Override
public void onLoadRequest(GeckoSession session, String uri, int target, int flags, GeckoResponse<Boolean> response) {
// If this is trying to load in a new tab, just load it in the current one
if (target == GeckoSession.NavigationDelegate.TARGET_WINDOW_NEW) {
geckoSession.loadUri(uri);
response.respond(true);
}
// Check if we should handle an internal link
if (LocalizedContent.handleInternalContent(uri, GeckoWebView.this, getContext())) {
response.respond(true);
}
// Check if we should handle an external link
final Uri urlToURI = Uri.parse(uri);
if (!UrlUtils.isSupportedProtocol(urlToURI.getScheme()) && callback != null &&
IntentUtils.handleExternalUri(getContext(), GeckoWebView.this, uri)) {
response.respond(true);
}
if (uri.equals("about:neterror") || uri.equals("about:certerror")) {
// TODO: Error Page handling with Components ErrorPages #2471
response.respond(true);
}
if (callback != null) {
callback.onRequest(flags == GeckoSession.NavigationDelegate.LOAD_REQUEST_IS_USER_TRIGGERED);
}
// Otherwise allow the load to continue normally
response.respond(false);
}
@Override
public void onNewSession(GeckoSession session, String uri, GeckoResponse<GeckoSession> response) {
// TODO: #2151
}
};
}
private GeckoSession.TrackingProtectionDelegate createTrackingProtectionDelegate() {
return new GeckoSession.TrackingProtectionDelegate() {
@Override
public void onTrackerBlocked(GeckoSession geckoSession, String s, int i) {
if (callback != null) {
callback.countBlockedTracker();
}
}
};
}
private GeckoSession.PromptDelegate createPromptDelegate() {
return new GeckoViewPrompt((Activity) getContext());
}
@Override
public boolean canGoForward() {
return canGoForward;
}
@Override
public boolean canGoBack() {
return canGoBack;
}
@Override
public void restoreWebViewState(Session session) {
final Bundle stateData = session.getWebViewState();
final String desiredURL = session.getUrl().getValue();
final GeckoSession.SessionState sessionState = stateData.getParcelable("state");
if (sessionState != null) {
geckoSession.restoreState(sessionState);
}
loadUrl(desiredURL);
}
@Override
public void saveWebViewState(@NonNull final Session session) {
final GeckoResponse<GeckoSession.SessionState> response = new GeckoResponse<GeckoSession.SessionState>() {
@Override
public void respond(GeckoSession.SessionState value) {
if (value != null) {
final Bundle bundle = new Bundle();
bundle.putParcelable("state", value);
session.saveWebViewState(bundle);
}
}
};
geckoSession.saveState(response);
}
@Override
public String getTitle() {
return webViewTitle;
}
@Override
public void exitFullscreen() {
geckoSession.exitFullScreen();
}
@Override
public void findAllAsync(String find) {
// TODO: #2690
}
@Override
public void findNext(boolean forward) {
// TODO: #2690
}
@Override
public void clearMatches() {
// TODO: #2690
}
@Override
public void setFindListener(IFindListener findListener) {
// TODO: #2690
}
@Override
public void loadData(String baseURL, String data, String mimeType, String encoding, String historyURL) {
geckoSession.loadData(data.getBytes(Charsets.UTF_8), mimeType, baseURL);
currentUrl = baseURL;
isLoadingInternalUrl = currentUrl.equals(LocalizedContent.URL_RIGHTS) || currentUrl.equals(LocalizedContent.URL_ABOUT);
}
private void sendTelemetrySnapshots() {
final GeckoResponse<GeckoBundle> response = new GeckoResponse<GeckoBundle>() {
@Override
public void respond(GeckoBundle value) {
if (value != null) {
try {
final JSONObject jsonData = value.toJSONObject();
TelemetryWrapper.addMobileMetricsPing(jsonData);
} catch (JSONException e) {
Log.e("getSnapshots failed", e.getMessage());
}
}
}
};
geckoRuntime.getTelemetry().getSnapshots(true, response);
}
@Override
public void onDetachedFromWindow() {
PreferenceManager.getDefaultSharedPreferences(getContext()).unregisterOnSharedPreferenceChangeListener(this);
super.onDetachedFromWindow();
}
}
} |
package com.cronutils;
import com.cronutils.descriptor.CronDescriptor;
import com.cronutils.mapper.CronMapper;
import com.cronutils.model.Cron;
import com.cronutils.model.definition.CronDefinition;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.model.time.ExecutionTime;
import com.cronutils.parser.CronParser;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.time.ZonedDateTime;
import java.util.Locale;
import java.util.Optional;
class Issue528Test {
static final CronDefinition REBOOT_CRON_DEFINITION = CronDefinitionBuilder.defineCron()
.withSupportedNicknameReboot()
.instance();
@Test
void testRebootExecutionTime() {
Cron cron = new CronParser(REBOOT_CRON_DEFINITION).parse("@reboot");
ExecutionTime executionTime = ExecutionTime.forCron(cron);
Assertions.assertEquals(Optional.empty(), executionTime.nextExecution(ZonedDateTime.now()));
Assertions.assertEquals(Optional.empty(), executionTime.lastExecution(ZonedDateTime.now()));
}
@Test
void testCronDescriptor() {
Cron cron = new CronParser(REBOOT_CRON_DEFINITION).parse("@reboot");
String description = CronDescriptor.instance(Locale.UK).describe(cron);
Assertions.assertEquals("on reboot", description);
}
@Test
void testCronMapper() {
Cron cron = new CronParser(REBOOT_CRON_DEFINITION).parse("@reboot");
CronDefinition unix = CronDefinitionBuilder.defineCron()
.withMinutes().withValidRange(0, 59).withStrictRange().and()
.withHours().withValidRange(0, 23).withStrictRange().and()
.withDayOfMonth().withValidRange(1, 31).withStrictRange().and()
.withMonth().withValidRange(1, 12).withStrictRange().and()
.withDayOfWeek().withValidRange(0, 7).withMondayDoWValue(1).withIntMapping(7, 0).withStrictRange().and()
.withSupportedNicknameReboot()
.instance();
Cron mapped = CronMapper.sameCron(unix).map(cron);
Assertions.assertEquals(cron.asString(), mapped.asString());
}
} |
package com.sigopt.model;
import com.sigopt.model.APIResource;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
public class ModelTest {
@Test
public void testEquality() throws Exception {
Experiment e = new Experiment();
Experiment e2 = new Experiment();
Bounds b = new Bounds();
assertEquals(e, e);
assertEquals(e, e2);
assertNotEquals(e, new HashMap<String, Object>());
assertNotEquals(new HashMap<String, Object>(), e);
assertNotEquals(e, b);
assertEquals(new Experiment.Builder().name("a").build(), new Experiment.Builder().name("a").build());
assertNotEquals(e, new Experiment.Builder().name("a").build());
assertNotEquals(e, new Experiment.Builder().name(null).build());
assertNotEquals(new Experiment.Builder().name("a").build(), new Experiment.Builder().name("b").build());
assertNotEquals(
new Experiment.Builder().name("a").build(),
new Experiment.Builder().name("a").id("3").build()
);
}
@Test
public void testNulls() throws Exception {
Experiment e = new Experiment();
assertEquals(e.getId(), null);
assertEquals(e.getProgress(), null);
assertEquals(e.getMetadata(), null);
Experiment e2 = new Experiment.Builder().build();
assertEquals(e2.getId(), null);
assertEquals(e2.getProgress(), null);
assertEquals(e2.getMetadata(), null);
Experiment e3 = new Experiment.Builder().id(null).progress(null).metadata(null).build();
assertEquals(e3.getId(), null);
assertEquals(e3.getProgress(), null);
assertEquals(e3.getMetadata(), null);
}
@Test
public void testJson() throws Exception {
assertEquals(
"{\"bounds\":{\"min\":3.0}}",
new Parameter.Builder().bounds(new Bounds.Builder().min(3.0).build()).build().toJson()
);
assertEquals(new Experiment().toJson(), "{}");
assertEquals(new Experiment.Builder().build().toJson(), "{}");
assertEquals(new Experiment.Builder().name(null).build().toJson(), "{\"name\":null}");
Map<String, Object> assignments = new HashMap<String, Object>();
assignments.put("a", 1);
assignments.put("b", "c");
String observationJson = new Observation.Builder().assignments(assignments).build().toJson();
assertTrue(
"{\"assignments\":{\"a\":1,\"b\":\"c\"}}".equals(observationJson) ||
"{\"assignments\":{\"b\":\"c\",\"a\":1}}".equals(observationJson)
);
}
} |
package io.searchbox.core;
import io.searchbox.core.Sort.Missing;
import io.searchbox.core.Sort.Sorting;
import org.junit.Test;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import static junit.framework.Assert.*;
/**
* @author Riccardo Tasso
*/
public class SortTest {
@Test
public void simpleTest() {
Sort s = new Sort("my_field");
assertEquals("\"my_field\"", s.toString());
}
@Test
public void complexTest() {
Sort s = new Sort("my_field", Sort.Sorting.ASC);
JsonParser parser = new JsonParser();
JsonElement parsed = parser.parse(s.toString());
assertTrue(parsed.getAsJsonObject().has("my_field"));
JsonElement element = parsed.getAsJsonObject().get("my_field");
assertTrue(element.getAsJsonObject().has("order"));
element = element.getAsJsonObject().get("order");
assertEquals("asc", element.getAsString());
s = new Sort("my_field", Sort.Sorting.DESC);
parsed = parser.parse(s.toString());
assertTrue(parsed.getAsJsonObject().has("my_field"));
element = parsed.getAsJsonObject().get("my_field");
assertTrue(element.getAsJsonObject().has("order"));
element = element.getAsJsonObject().get("order");
assertEquals("desc", element.getAsString());
}
@Test
public void missingValueTest() {
// first
Sort s = new Sort("my_field");
s.setMissing(Missing.FIRST);
JsonParser parser = new JsonParser();
JsonElement parsed = parser.parse(s.toString());
assertTrue(parsed.getAsJsonObject().has("my_field"));
JsonObject myField = parsed.getAsJsonObject().get("my_field").getAsJsonObject();
assertTrue(myField.has("missing"));
assertEquals(myField.get("missing").getAsString(), "_first");
// last
s = new Sort("my_field");
s.setMissing(Missing.LAST);
parser = new JsonParser();
parsed = parser.parse(s.toString());
assertTrue(parsed.getAsJsonObject().has("my_field"));
myField = parsed.getAsJsonObject().get("my_field").getAsJsonObject();
assertTrue(myField.has("missing"));
assertEquals(myField.get("missing").getAsString(), "_last");
// value String
s = new Sort("my_field");
s.setMissing("***");
parser = new JsonParser();
parsed = parser.parse(s.toString());
assertTrue(parsed.getAsJsonObject().has("my_field"));
myField = parsed.getAsJsonObject().get("my_field").getAsJsonObject();
assertTrue(myField.has("missing"));
assertEquals(myField.get("missing").getAsString(), "***");
// value Integer
s = new Sort("my_field");
s.setMissing(new Integer(-1));
parser = new JsonParser();
parsed = parser.parse(s.toString());
assertTrue(parsed.getAsJsonObject().has("my_field"));
myField = parsed.getAsJsonObject().get("my_field").getAsJsonObject();
assertTrue(myField.has("missing"));
assertEquals(myField.get("missing").getAsInt(), -1);
// mixed
s = new Sort("my_field", Sorting.DESC);
s.setMissing(new Integer(-1));
parser = new JsonParser();
parsed = parser.parse(s.toString());
assertTrue(parsed.getAsJsonObject().has("my_field"));
myField = parsed.getAsJsonObject().get("my_field").getAsJsonObject();
assertTrue(myField.has("missing"));
assertEquals(myField.get("missing").getAsInt(), -1);
assertTrue(myField.has("order"));
assertEquals(myField.get("order").getAsString(), "desc");
}
@Test
public void unmappedTest() {
// simple
Sort s = new Sort("my_field");
s.setIgnoreUnmapped();
JsonParser parser = new JsonParser();
JsonElement parsed = parser.parse(s.toString());
assertTrue(parsed.getAsJsonObject().has("my_field"));
JsonObject myField = parsed.getAsJsonObject().get("my_field").getAsJsonObject();
assertTrue(myField.has("ignore_unmapped"));
assertTrue(myField.get("ignore_unmapped").getAsBoolean());
// complex
s = new Sort("my_field", Sorting.DESC);
s.setMissing(Missing.LAST);
s.setIgnoreUnmapped();
parser = new JsonParser();
parsed = parser.parse(s.toString());
assertTrue(parsed.getAsJsonObject().has("my_field"));
myField = parsed.getAsJsonObject().get("my_field").getAsJsonObject();
assertTrue(myField.has("ignore_unmapped"));
assertTrue(myField.get("ignore_unmapped").getAsBoolean());
}
} |
package com.bigkoo.pickerviewdemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.model.IPickerViewData;
import com.bigkoo.pickerviewdemo.bean.PickerViewData;
import com.bigkoo.pickerviewdemo.bean.ProvinceBean;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class MainActivity extends Activity {
private ArrayList<ProvinceBean> options1Items = new ArrayList<>();
private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
private ArrayList<ArrayList<ArrayList<IPickerViewData>>> options3Items = new ArrayList<>();
private Button tvTime, tvOptions;
TimePickerView pvTime;
OptionsPickerView pvOptions;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvTime=(Button) findViewById(R.id.tvTime);
tvOptions=(Button) findViewById(R.id.tvOptions);
//,setRange setDate ()
Calendar calendar = Calendar.getInstance();
//sample use
/*pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
@Override
public void onTimeSelect(Date date) {
tvTime.setText(getTime(date));
}
}).build();*/
//DIY
pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
@Override
public void onTimeSelect(Date date) {
tvTime.setText(getTime(date));
}
})
.setType(TimePickerView.Type.ALL)//default all
.setCancelText("Cancel")
.setSubmitText("Sure")
.setOutSideCancelable(false)// default true
/*.isCyclic(true)// default false */
/*.setBackgroundColor(0xFF000000)// Night mode*/
/*.setRange(calendar.get(Calendar.YEAR) - 20, calendar.get(Calendar.YEAR) + 20)//default 1990-2100 years */
/*.setDate(new Date())// default system*/
.build();
tvTime.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (pvTime!=null){
pvTime.show();
}
}
});
pvOptions = new OptionsPickerView(this);
options1Items.add(new ProvinceBean(0,"","",""));
options1Items.add(new ProvinceBean(1,"","","TV"));
options1Items.add(new ProvinceBean(3,"","",""));
ArrayList<String> options2Items_01=new ArrayList<>();
options2Items_01.add("");
options2Items_01.add("");
options2Items_01.add("");
options2Items_01.add("");
options2Items_01.add("");
ArrayList<String> options2Items_02=new ArrayList<>();
options2Items_02.add("");
options2Items_02.add("");
ArrayList<String> options2Items_03=new ArrayList<>();
options2Items_03.add("");
options2Items.add(options2Items_01);
options2Items.add(options2Items_02);
options2Items.add(options2Items_03);
ArrayList<ArrayList<IPickerViewData>> options3Items_01 = new ArrayList<>();
ArrayList<ArrayList<IPickerViewData>> options3Items_02 = new ArrayList<>();
ArrayList<ArrayList<IPickerViewData>> options3Items_03 = new ArrayList<>();
ArrayList<IPickerViewData> options3Items_01_01=new ArrayList<>();
options3Items_01_01.add(new PickerViewData(""));
options3Items_01_01.add(new PickerViewData(""));
options3Items_01_01.add(new PickerViewData(""));
options3Items_01_01.add(new PickerViewData(""));
options3Items_01.add(options3Items_01_01);
ArrayList<IPickerViewData> options3Items_01_02=new ArrayList<>();
options3Items_01_02.add(new PickerViewData(""));
options3Items_01_02.add(new PickerViewData(""));
options3Items_01_02.add(new PickerViewData(""));
options3Items_01_02.add(new PickerViewData(""));
options3Items_01.add(options3Items_01_02);
ArrayList<IPickerViewData> options3Items_01_03=new ArrayList<>();
options3Items_01_03.add(new PickerViewData(""));
options3Items_01_03.add(new PickerViewData(""));
options3Items_01_03.add(new PickerViewData(""));
options3Items_01.add(options3Items_01_03);
ArrayList<IPickerViewData> options3Items_01_04=new ArrayList<>();
options3Items_01_04.add(new PickerViewData(""));
options3Items_01_04.add(new PickerViewData(""));
options3Items_01_04.add(new PickerViewData(""));
options3Items_01.add(options3Items_01_04);
ArrayList<IPickerViewData> options3Items_01_05=new ArrayList<>();
options3Items_01_05.add(new PickerViewData("1"));
options3Items_01_05.add(new PickerViewData("2"));
options3Items_01.add(options3Items_01_05);
ArrayList<IPickerViewData> options3Items_02_01=new ArrayList<>();
options3Items_02_01.add(new PickerViewData("1"));
options3Items_02_01.add(new PickerViewData("2"));
options3Items_02_01.add(new PickerViewData("3"));
options3Items_02_01.add(new PickerViewData("4"));
options3Items_02_01.add(new PickerViewData("5"));
options3Items_02.add(options3Items_02_01);
ArrayList<IPickerViewData> options3Items_02_02=new ArrayList<>();
options3Items_02_02.add(new PickerViewData(""));
options3Items_02_02.add(new PickerViewData("1"));
options3Items_02_02.add(new PickerViewData("2"));
options3Items_02_02.add(new PickerViewData("3"));
options3Items_02_02.add(new PickerViewData("4"));
options3Items_02_02.add(new PickerViewData("5"));
options3Items_02.add(options3Items_02_02);
ArrayList<IPickerViewData> options3Items_03_01=new ArrayList<>();
options3Items_03_01.add(new PickerViewData(""));
options3Items_03.add(options3Items_03_01);
options3Items.add(options3Items_01);
options3Items.add(options3Items_02);
options3Items.add(options3Items_03);
pvOptions.setPicker(options1Items, options2Items, options3Items, true);
// pwOptions.setLabels("", "", "");
pvOptions.setTitle("");
pvOptions.setCyclic(false, false, false);
//dismiss
pvOptions.setKeyBackCancelable(true);
pvOptions.setSelectOptions(1, 1, 1);
pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
@Override
public void onOptionsSelect(int options1, int option2, int options3) {
String tx = options1Items.get(options1).getPickerViewText()
+ options2Items.get(options1).get(option2)
+ options3Items.get(options1).get(option2).get(options3).getPickerViewText();
tvOptions.setText(tx);
}
});
tvOptions.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pvOptions.show();
}
});
}
public static String getTime(Date date) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return format.format(date);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if(pvTime.isShowing()){
pvTime.dismiss();
return true;
}
if(pvOptions.isShowing()){
pvOptions.dismiss();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
} |
package me.pagarme;
import me.pagar.model.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
public class TransactionTest extends BaseTest {
private Recipient recipient = new Recipient();
private SplitRule splitRule = new SplitRule();
private BankAccount bankAccount;
private static Integer AMOUNT = 100;
private static Integer PAID_AMOUNT_PARTIAL = 50;
@Before
public void setUp() {
super.setUp();
transaction = new Transaction();
}
@Test
public void testCreateAndCaptureTransactionWithCreditCardWithoutGoingThroughFraud() throws Throwable {
transaction = this.transactionCreditCardCommon();
transaction.setCapture(true);
transaction.save();
Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.CREDIT_CARD);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PAID);
}
@Test
public void testCreateAndCaptureTransactionMetaData() throws Throwable {
transaction = this.transactionCreditCardCommon();
transaction.setCapture(true);
Map<String, Object> metadata = new HashMap<String, Object>();
metadata.put("metadata1", "value1");
metadata.put("metadata2", "value2");
transaction.setMetadata(metadata);
transaction.save();
Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.CREDIT_CARD);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PAID);
}
@Test
public void testCreateAndCaptureTransactionMetaDataInCapture() throws Throwable {
transaction = this.transactionCreditCardCommon();
transaction.setCapture(false);
transaction.save();
Map<String, Object> metadata = new HashMap<String, Object>();
metadata.put("metadata1", "value1");
metadata.put("metadata2", "value2");
transaction.setMetadata(metadata);
transaction.capture(AMOUNT);
Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.CREDIT_CARD);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PAID);
}
@Test
public void testCreateAndAuthorizedTransactionWithCreditCardWithoutGoingThroughFraud() throws Throwable {
transaction = this.transactionCreditCardCommon();
transaction.setCapture(false);
transaction.save();
Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.CREDIT_CARD);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.AUTHORIZED);
}
@Test
public void testTransactionCreatePostbackUrl() throws Throwable {
transaction = this.transactionCreditCardCommon();
transaction.setPostbackUrl("http://pagar.me");
transaction.save();
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PROCESSING);
}
@Test
public void testTransactionAuthAndCaptureCaptureTotalValue() throws Throwable {
transaction = this.transactionCreditCardCommon();
transaction.setCapture(false);
transaction.save();
Assert.assertEquals(transaction.getStatus(), Transaction.Status.AUTHORIZED);
transaction.capture(AMOUNT);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PAID);
}
@Test
public void testTransactionCanBeMadeString() throws Throwable {
transaction = this.transactionCreditCardCommon();
transaction.toString();
}
@Test
public void testTransactionAuthAndCaptureCapturePartialValue() throws Throwable {
transaction = this.transactionCreditCardCommon();
transaction.setCapture(false);
transaction.save();
Assert.assertEquals(transaction.getStatus(), Transaction.Status.AUTHORIZED);
transaction.capture(50);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PAID);
Assert.assertEquals(transaction.getPaidAmount(), PAID_AMOUNT_PARTIAL);
Assert.assertEquals(transaction.getAuthorizedAmount(), AMOUNT);
}
@Test
public void testTransactionAuthAndCaptureRefoundPartialValue() throws Throwable {
transaction = this.transactionCreditCardCommon();
transaction.setCapture(true);
transaction.save();
transaction.refund(50);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.PAID);
Assert.assertEquals(transaction.getPaidAmount(), AMOUNT);
Assert.assertEquals(transaction.getRefundedAmount(), PAID_AMOUNT_PARTIAL);
Assert.assertEquals(transaction.getAuthorizedAmount(), AMOUNT);
}
@Test
public void testTransactionAuthAndCaptureRefoundTotalValue() throws Throwable {
transaction = this.transactionCreditCardCommon();
transaction.setCapture(true);
transaction.save();
transaction.refund(AMOUNT);
Assert.assertEquals(transaction.getStatus(), Transaction.Status.REFUNDED);
Assert.assertEquals(transaction.getRefundedAmount(), AMOUNT);
}
@Test
public void testCreateAndAuthorizedTransactionWithBoleto() throws Throwable {
transaction = this.transactionBoletoCommon();
transaction.save();
Assert.assertEquals(transaction.getStatus(), Transaction.Status.WAITING_PAYMENT);
Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.BOLETO);
}
@Test
public void testCreateTransactionWithBoleto() throws Throwable {
transaction = this.transactionBoletoCommon();
transaction.save();
Assert.assertEquals(transaction.getStatus(), Transaction.Status.WAITING_PAYMENT);
Assert.assertEquals(transaction.getPaymentMethod(), Transaction.PaymentMethod.BOLETO);
Assert.assertEquals(transaction.getBoletoUrl(), "https://pagar.me");
Assert.assertNotNull(transaction.getBoletoBarcode());
}
@Test
public void testFindTransactionById() throws Throwable {
transaction = this.transactionCreditCardCommon();
transaction.save();
Integer transactionId = transaction.getId();
transaction = transaction.find(transactionId);
Assert.assertEquals(transaction.getId(), transactionId);
}
@Test
public void testCreatingCustomerTransactionThroughTheTransaction() throws Throwable {
transaction = this.transactionCreditCardCommon();
transaction.setCapture(true);
Customer customer = this.customerCommon();
Address address = this.addressCommon();
Phone phone = this.phoneCommon();
customer.setAddress(address);
customer.setPhone(phone);
transaction.setCustomer(customer);
transaction.save();
Customer transactionCustomer = transaction.getCustomer();
Assert.assertEquals(transactionCustomer.getName(), "lucas santos");
Assert.assertEquals(transactionCustomer.getDocumentNumber(), "15317529506");
Assert.assertEquals(transactionCustomer.getEmail(), "testelibjava@pagar.me");
Address transactionAddress = transactionCustomer.getAddress();
Assert.assertEquals(transactionAddress.getStreet(), "Rua Piraju");
Assert.assertEquals(transactionAddress.getStreetNumber(), "218");
Assert.assertEquals(transactionAddress.getComplementary(), "ao lado da consigáz");
Assert.assertEquals(transactionAddress.getNeighborhood(), "Interlagos");
Phone transactionPhone = transactionCustomer.getPhone();
Assert.assertEquals(transactionPhone.getDdd(), "11");
Assert.assertEquals(transactionPhone.getNumber(), "55284132");
}
// @Test
// public void testSplitTransaction() throws Throwable {
// transaction = this.transactionCreditCardCommon();
// transaction.setCapture(true);
// Collection<SplitRule> splitRules = new ArrayList<SplitRule>();
// splitRule.setRecipientId(this.getRecipientId(false));
// splitRule.setPercentage(50);
// splitRule.setLiable(true);
// splitRule.setChargeProcessingFee(true);
// splitRules.add(splitRule);
// splitRule.setRecipientId(this.getRecipientId(true));
// splitRule.setPercentage(50);
// splitRule.setLiable(true);
// splitRule.setChargeProcessingFee(true);
// splitRules.add(splitRule);
// transaction.setSplitRules(splitRules);
// transaction.save();
// private String getRecipientId(Boolean documentNumber) {
// int bankAccountId = this.getBankAccountId(documentNumber);
// recipient.setTransferInterval(Recipient.TransferInterval.WEEKLY);
// recipient.setTransferDay(TRANSFER_DAY);
// recipient.setTransferEnabled(TRANSFER_ENABLE);
// recipient.setBankAccountId(bankAccountId);
// try {
// recipient.save();
// return recipient.getId();
// } catch (PagarMeException exception) {
// throw new UnsupportedOperationException(exception);
// /**
// *
// * @return
// */
// private Integer getBankAccountId(Boolean documentNumber) {
// System.out.print("Hello " + documentNumber);
// if (documentNumber == true) {
// bankAccount = new BankAccount();
// bankAccount.setAgencia(AGENCIA);
// bankAccount.setAgenciaDv(AGENCIA_DV);
// bankAccount.setConta(CONTA);
// bankAccount.setContaDv(CONTA_DV);
// bankAccount.setBankCode(BANK_CODE);
// bankAccount.setDocumentNumber(DOCUMENT_NUMBER);
// } else {
// bankAccount = new BankAccount();
// System.out.print("Hello " + bankAccount.getConta());
// bankAccount.setAgencia("0173");
// bankAccount.setAgenciaDv("1");
// bankAccount.setConta("506725");
// bankAccount.setContaDv(CONTA_DV);
// bankAccount.setBankCode(BANK_CODE);
// bankAccount.setDocumentNumber("55278368128");
// try {
// bankAccount.save();
// return bankAccount.getId();
// } catch (PagarMeException exception) {
// throw new UnsupportedOperationException(exception);
} |
package org.takes.http;
import com.jcabi.http.request.JdkRequest;
import com.jcabi.http.response.RestResponse;
import com.jcabi.matchers.RegexMatchers;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URI;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicReference;
import org.cactoos.io.BytesOf;
import org.cactoos.text.Joined;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Ignore;
import org.junit.Test;
import org.llorllale.cactoos.matchers.Assertion;
import org.llorllale.cactoos.matchers.TextHasString;
import org.takes.Request;
import org.takes.facets.fork.FkRegex;
import org.takes.facets.fork.TkFork;
import org.takes.misc.Href;
import org.takes.rq.RqFake;
import org.takes.rq.RqHeaders;
import org.takes.rq.RqPrint;
import org.takes.rq.RqSocket;
import org.takes.rs.ResponseOf;
import org.takes.tk.TkText;
/**
* Test case for {@link BkBasic}.
*
* @since 0.15.2
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
* @checkstyle MultipleStringLiteralsCheck (500 lines)
*/
@SuppressWarnings(
{
"PMD.ExcessiveImports",
"PMD.TooManyMethods"
})
public final class BkBasicTest {
/**
* Carriage return constant.
*/
private static final String CRLF = "\r\n";
/**
* POST header constant.
*/
private static final String POST = "POST / HTTP/1.1";
/**
* Host header constant.
*/
private static final String HOST = "Host:localhost";
/**
* BkBasic can handle socket data.
*
* @throws Exception If some problem inside
*/
@Test
public void handlesSocket() throws Exception {
final MkSocket socket = BkBasicTest.createMockSocket();
final ByteArrayOutputStream baos = socket.bufferedOutput();
final String hello = "Hello World";
new BkBasic(new TkText(hello)).accept(socket);
MatcherAssert.assertThat(
baos.toString(),
Matchers.containsString(hello)
);
}
/**
* BkBasic can return HTTP status 404 when accessing invalid URL.
*
* @throws Exception if any I/O error occurs.
*/
@Test
public void returnsProperResponseCodeOnInvalidUrl() throws Exception {
new FtRemote(
new TkFork(
new FkRegex("/path/a", new TkText("a")),
new FkRegex("/path/b", new TkText("b"))
)
).exec(
new FtRemote.Script() {
@Override
public void exec(final URI home) throws IOException {
new JdkRequest(String.format("%s/path/c", home))
.fetch()
.as(RestResponse.class)
.assertStatus(HttpURLConnection.HTTP_NOT_FOUND);
}
}
);
}
/**
* BkBasic produces headers with addresses without slashes.
*
* @throws Exception If some problem inside
*/
@Test
public void addressesInHeadersAddedWithoutSlashes() throws Exception {
final Socket socket = BkBasicTest.createMockSocket();
final AtomicReference<Request> ref = new AtomicReference<>();
new BkBasic(
req -> {
ref.set(req);
return new ResponseOf(
() -> Collections.singletonList("HTTP/1.1 200 OK"),
req::body
);
}
).accept(socket);
final Request request = ref.get();
final RqHeaders.Smart smart = new RqHeaders.Smart(
new RqHeaders.Base(request)
);
MatcherAssert.assertThat(
smart.single(
"X-Takes-LocalAddress",
""
),
Matchers.not(
Matchers.containsString("/")
)
);
MatcherAssert.assertThat(
smart.single(
"X-Takes-RemoteAddress",
""
),
Matchers.not(
Matchers.containsString("/")
)
);
MatcherAssert.assertThat(
new RqSocket(request).getLocalAddress(),
Matchers.notNullValue()
);
MatcherAssert.assertThat(
new RqSocket(request).getRemoteAddress(),
Matchers.notNullValue()
);
}
/**
* BkBasic can handle two requests in one connection.
*
* @throws Exception If some problem inside
*/
@Test
public void handlesTwoRequestInOneConnection() throws Exception {
final String text = "Hello Twice!";
final ByteArrayOutputStream output = new ByteArrayOutputStream();
try (ServerSocket server = new ServerSocket(0)) {
new Thread(
new Runnable() {
@Override
public void run() {
try {
new BkBasic(new TkText(text)).accept(
server.accept()
);
} catch (final IOException exception) {
throw new IllegalStateException(exception);
}
}
}
).start();
try (Socket socket = new Socket(
server.getInetAddress(),
server.getLocalPort()
)
) {
socket.getOutputStream().write(
new Joined(
BkBasicTest.CRLF,
BkBasicTest.POST,
BkBasicTest.HOST,
"Content-Length: 11",
"",
"Hello First",
BkBasicTest.POST,
BkBasicTest.HOST,
"Content-Length: 12",
"",
"Hello Second"
).asString().getBytes()
);
final InputStream input = socket.getInputStream();
// @checkstyle MagicNumber (1 line)
final byte[] buffer = new byte[4096];
for (int count = input.read(buffer); count != -1;
count = input.read(buffer)) {
output.write(buffer, 0, count);
}
}
}
MatcherAssert.assertThat(
output.toString(),
RegexMatchers.containsPattern(
String.format("(?s)%s.*?%s", text, text)
)
);
}
/**
* BkBasic can return HTTP status 411 when a persistent connection request
* has no Content-Length.
*
* @throws Exception If some problem inside
*/
@Ignore
@Test
public void returnsProperResponseCodeOnNoContentLength() throws Exception {
final ByteArrayOutputStream output = new ByteArrayOutputStream();
final String text = "Say hello!";
try (ServerSocket server = new ServerSocket(0)) {
new Thread(
new Runnable() {
@Override
public void run() {
try {
new BkBasic(new TkText("411 Test")).accept(
server.accept()
);
} catch (final IOException exception) {
throw new IllegalStateException(exception);
}
}
}
).start();
try (Socket socket = new Socket(
server.getInetAddress(),
server.getLocalPort()
)
) {
socket.getOutputStream().write(
new BytesOf(
new Joined(
BkBasicTest.CRLF,
BkBasicTest.POST,
BkBasicTest.HOST,
"",
text
)
).asBytes()
);
final InputStream input = socket.getInputStream();
// @checkstyle MagicNumber (1 line)
final byte[] buffer = new byte[4096];
for (int count = input.read(buffer); count != -1;
count = input.read(buffer)) {
output.write(buffer, 0, count);
}
}
}
MatcherAssert.assertThat(
output.toString(),
Matchers.containsString("HTTP/1.1 411 Length Required")
);
}
/**
* BkBasic can accept no content-length on closed connection.
*
* @throws Exception If some problem inside
*/
@Ignore
@Test
public void acceptsNoContentLengthOnClosedConnection() throws Exception {
final String text = "Close Test";
final ByteArrayOutputStream output = new ByteArrayOutputStream();
final String greetings = "Hi everyone";
try (ServerSocket server = new ServerSocket(0)) {
new Thread(
new Runnable() {
@Override
public void run() {
try {
new BkBasic(new TkText(text)).accept(
server.accept()
);
} catch (final IOException exception) {
throw new IllegalStateException(exception);
}
}
}
).start();
try (Socket socket = new Socket(
server.getInetAddress(),
server.getLocalPort()
)
) {
socket.getOutputStream().write(
new BytesOf(
new Joined(
BkBasicTest.CRLF,
BkBasicTest.POST,
BkBasicTest.HOST,
"Connection: Close",
"",
greetings
)
).asBytes()
);
final InputStream input = socket.getInputStream();
// @checkstyle MagicNumber (1 line)
final byte[] buffer = new byte[4096];
for (int count = input.read(buffer); count != -1;
count = input.read(buffer)) {
output.write(buffer, 0, count);
}
}
}
MatcherAssert.assertThat(
output.toString(),
Matchers.containsString(text)
);
}
/**
* BkBasic can return HTTP status 400 (Bad Request) when a request has an
* invalid URI.
* @todo #1058:30min This test address the bug reported by issue #1058.
* The problem is {@link Href#createUri} method is recursive and
* isn't working properly (the index doesn't match with the correct
* position). But even fixing it, this leave a other question: should or
* not Takes send a 400 Bad Request response? By the HTTP protocol, the
* answer is yes. So, you should: 1) fix the recursive call in
* {@link Href#createUri} 2) change {@link BkBasic#print} to return a
* 400 Bad Request response and finally 3) unignore this test (that should
* pass).
*/
@Ignore
@Test
public void returnsABadRequestToAnInvalidRequestUri() {
final ByteArrayOutputStream output = new ByteArrayOutputStream();
new Assertion<>(
"Must return bad request to an invalid request URI",
() -> {
try (ServerSocket server = new ServerSocket(0)) {
new Thread(
() -> {
try {
new BkBasic(
new TkFork(
new FkRegex("/", new TkText("hello"))
)
).accept(
server.accept()
);
} catch (final IOException exception) {
throw new IllegalStateException(exception);
}
}
).start();
try (
Socket socket = new Socket(
server.getInetAddress(),
server.getLocalPort()
)
) {
socket.getOutputStream().write(
new RqPrint(
new RqFake("GET", "\\")
).asString().getBytes()
);
final InputStream input = socket.getInputStream();
// @checkstyle MagicNumber (1 line)
final byte[] buffer = new byte[4096];
for (
int count = input.read(buffer); count != -1;
count = input.read(buffer)
) {
output.write(buffer, 0, count);
}
}
}
return output.toString();
},
new TextHasString("400 Bad Request")
).affirm();
}
/**
* Creates Socket mock for reuse.
*
* @return Prepared Socket mock
* @throws Exception If some problem inside
*/
private static MkSocket createMockSocket() throws Exception {
return new MkSocket(
new ByteArrayInputStream(
new BytesOf(
new Joined(
BkBasicTest.CRLF,
"GET / HTTP/1.1",
BkBasicTest.HOST,
"Content-Length: 2",
"",
"hi"
)
).asBytes()
)
);
}
} |
package com.noprestige.kanaquiz;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
abstract class OptionsControl
{
final static String CODE_HIRAGANA_1 = "hiragana_set_1";
final static String CODE_HIRAGANA_2 = "hiragana_set_2";
final static String CODE_HIRAGANA_3 = "hiragana_set_3";
final static String CODE_HIRAGANA_4 = "hiragana_set_4";
final static String CODE_HIRAGANA_5 = "hiragana_set_5";
final static String CODE_HIRAGANA_6 = "hiragana_set_6";
final static String CODE_HIRAGANA_7 = "hiragana_set_7";
final static String CODE_HIRAGANA_8 = "hiragana_set_8";
final static String CODE_HIRAGANA_9 = "hiragana_set_9";
final static String CODE_HIRAGANA_10 = "hiragana_set_10";
final static String CODE_KATAKANA_1 = "katakana_set_1";
final static String CODE_KATAKANA_2 = "katakana_set_2";
final static String CODE_KATAKANA_3 = "katakana_set_3";
final static String CODE_KATAKANA_4 = "katakana_set_4";
final static String CODE_KATAKANA_5 = "katakana_set_5";
final static String CODE_KATAKANA_6 = "katakana_set_6";
final static String CODE_KATAKANA_7 = "katakana_set_7";
final static String CODE_KATAKANA_8 = "katakana_set_8";
final static String CODE_KATAKANA_9 = "katakana_set_9";
final static String CODE_KATAKANA_10 = "katakana_set_10";
final static String CODE_ON_INCORRECT_CHEAT = "show_answer_on_incorrect";
final static String CODE_ON_INCORRECT_RETRY = "retry_on_incorrect";
static private SharedPreferences sharedPreferences;
static private SharedPreferences.Editor editor;
static void initialize(Context context)
{
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
editor = sharedPreferences.edit();
}
static boolean getBoolean(String prefId)
{
return sharedPreferences.getBoolean(prefId, false);
}
static void setBoolean(String prefId, boolean setting)
{
editor.putBoolean(prefId, setting);
editor.apply();
}
} |
package com.stest.neteasycloud;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.stest.model.MusicInfoDetail;
import com.stest.utils.BitmapUtils;
import com.stest.utils.NetWorkUtils;
import com.stest.utils.ToastUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import jp.wasabeef.glide.transformations.BlurTransformation;
public class PlayingActiivty extends AppCompatActivity {
@ViewInject(R.id.toolbar)
Toolbar toolbar;
@ViewInject(R.id.needle)
ImageView needle;
@ViewInject(R.id.playSeekBar)
SeekBar seekBar;
@ViewInject(R.id.default_disk_img)
ImageView img_disk;
@ViewInject(R.id.img_disc)
ImageView img_disc;
@ViewInject(R.id.currentTime)
TextView currentTime;
@ViewInject(R.id.totalTime)
TextView endTime;
@ViewInject(R.id.song)
TextView song_txt;
@ViewInject(R.id.singer)
TextView singer_txt;
@ViewInject(R.id.play_back)
ImageView play_back;
private ActionBar actionBar;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_playing);
EventBus.getDefault().register(this);
ViewUtils.inject(this);
initWidgets();
}
@Override
protected void onStart() {
super.onStart();
}
public static void start(Context context) {
Intent intent = new Intent(context, PlayingActiivty.class);
context.startActivity(intent);
}
private void initWidgets() {
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.actionbar_back);
}
toolbar.inflateMenu(R.menu.music_playing_item);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
overridePendingTransition(R.anim.right_slide_in, R.anim.right_slide_out);
}
});
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_share:
if (!NetWorkUtils.isNetworkConnected(PlayingActiivty.this)) {
ToastUtils.show(PlayingActiivty.this, getResources().getString(R.string.net_wrong), Toast.LENGTH_SHORT);
} else {
}
break;
}
return false;
}
});
}
@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
public void onStickyUpdateUI(final MusicInfoDetail info) {
new Handler().post(new Runnable() {
@Override
public void run() {
song_txt.setText(info.getTitle());
singer_txt.setText(info.getArtist());
Glide.with(PlayingActiivty.this)
.load(info.getCoverUri())
.placeholder(R.drawable.fm_run_result_bg)
.error(R.drawable.fm_run_result_bg)
.crossFade()
.bitmapTransform(new BlurTransformation(PlayingActiivty.this,50))
.into(play_back);
Glide.with(PlayingActiivty.this)
.load(info.getCoverUri())
.placeholder(R.drawable.placeholder_disk_play_song)
.error(R.drawable.placeholder_disk_play_song)
.centerCrop()
.crossFade()
.into(img_disk);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.music_playing_item, menu);
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
overridePendingTransition(R.anim.right_slide_in, R.anim.right_slide_out);
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
} |
package info.vourja.airline;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.twitter.sdk.android.Twitter;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import com.twitter.sdk.android.core.TwitterAuthToken;
import com.twitter.sdk.android.core.TwitterSession;
import info.vourja.airline.NetService.AirLineService;
import io.fabric.sdk.android.Fabric;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class AirLineApplication extends Application {
// Note: Your consumer key and secret should be obfuscated in your source code before shipping.
private static final String TWITTER_KEY = "L6StgFi57qsxCS3GOvzRrj5I7";
private static final String TWITTER_SECRET = "DYu4bES4onS68ZSf6jViuHjqXzDr6GaBBAAhHAhywo3ju6DPIP";
private TwitterSession twitterSession;
private String accessToken;
Retrofit mRetrofit;
@Override
public void onCreate() {
super.onCreate();
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new Twitter(authConfig));
SharedPreferences data = getSharedPreferences("Twitter", Context.MODE_PRIVATE);
if(data != null) {
String token = data.getString("token", null);
String secret = data.getString("secret", null);
long userid = data.getLong("userid", 0);
String username = data.getString("username", null);
if(token == null || secret == null || userid == 0 || username == null) {
// Do Nothing
} else {
TwitterAuthToken authToken = new TwitterAuthToken(token, secret);
twitterSession = new TwitterSession(authToken, userid, username);
}
}
}
public TwitterSession getTwitterSession() {
return twitterSession;
}
public void setTwitterSession(TwitterSession twitterSession) {
this.twitterSession = twitterSession;
writeTwitterPreference();
}
public String getAccessToken() {
return this.accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public AirLineService getAirlineService() {
if(mRetrofit == null) {
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
.create();
mRetrofit = new Retrofit.Builder()
.baseUrl("http://vourja.info")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return mRetrofit.create(AirLineService.class);
}
private void writeTwitterPreference() {
SharedPreferences data = getSharedPreferences("Twitter", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
editor.putString("token", twitterSession.getAuthToken().token);
editor.putString("secret", twitterSession.getAuthToken().secret);
editor.putLong("userid", twitterSession.getUserId());
editor.putString("username", twitterSession.getUserName());
editor.apply();
}
} |
package org.catinthedark.wallpepper;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.catinthedark.wallpepper.asynctask.RequestTask;
public class MyActivity extends Activity {
public static final String TAG = "WallPepper";
public static final String API_KEY = "2cc3659a84bb322d7523a89e53d58578";
private final String SHARED_PREFS_NAME = "wallpepper_sharedprefs";
private final String TAGS_KEY = "tags";
private final String RANDOM_RANGE_KEY = "random_range";
private EditText randomRangeEditText;
private EditText tagsEditText;
private SharedPreferences preferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
randomRangeEditText = (EditText) findViewById(R.id.randomRangeEditText);
tagsEditText = (EditText) findViewById(R.id.tagsEditText);
Button setWallpaperButton = (Button) findViewById(R.id.setWallpaperButton);
preferences = getSharedPreferences(SHARED_PREFS_NAME, MODE_PRIVATE);
if (preferences.contains(RANDOM_RANGE_KEY)) {
randomRangeEditText.setText(String.valueOf(preferences.getInt(RANDOM_RANGE_KEY, 10)));
}
if (preferences.contains(TAGS_KEY)) {
tagsEditText.setText(preferences.getString(TAGS_KEY, ""));
}
setWallpaperButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (tagsEditText.getText().toString().isEmpty()) {
Toast.makeText(
getApplicationContext(), "Please fill tags", Toast.LENGTH_SHORT)
.show();
} else {
int randomNumber = Integer.valueOf(randomRangeEditText.getText().toString());
String tags = tagsEditText.getText().toString();
new RequestTask().execute(getApplicationContext(), randomNumber, tags);
}
}
});
}
@Override
protected void onPause() {
preferences.edit()
.putInt(RANDOM_RANGE_KEY, Integer.valueOf(randomRangeEditText.getText().toString()))
.putString(TAGS_KEY, tagsEditText.getText().toString())
.apply();
super.onPause();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
} |
package org.ollide.xposed.instagram;
public final class ClassNames {
public static final String TARGET_PACKAGE = "com.instagram.android";
private static final int VERSION_6_10_1 = 5257472;
private static final int VERSION_6_15_0 = 6891295;
private static final int VERSION_6_16_0_BETA = 7097676;
private static final int VERSION_6_16_1 = 7369808;
// last reviewed version
private static final int VERSION_6_17_0 = 7483428;
/**
* The BaseActivity's obfuscated class name.
* Has never changed so far (since 6.10.1 | 5257472).
*/
private static String sBaseActivityName = "com.instagram.base.activity.e";
/**
* Last changed with version 6.17.0, first checked with version 6.10.1.
*/
private static String sDoubleTabListenerName = "com.instagram.android.feed.a.b.ao";
/**
* Last changed with version 6.17.0, first checked with version 6.10.1.
*/
private static String sHeartIconTapListenerName = "com.instagram.android.feed.a.b.aa";
public static void initWithVersion(int versionCode) {
if (versionCode >= VERSION_6_17_0) {
sDoubleTabListenerName = "com.instagram.android.feed.a.b.ao";
sHeartIconTapListenerName = "com.instagram.android.feed.a.b.aa";
} else if (versionCode >= VERSION_6_16_0_BETA) {
sDoubleTabListenerName = "com.instagram.android.feed.a.b.ac";
sHeartIconTapListenerName = "com.instagram.android.feed.a.b.o";
} else {
sDoubleTabListenerName = "com.instagram.android.feed.a.b.z";
sHeartIconTapListenerName = "com.instagram.android.feed.a.b.b";
}
}
public static String getBaseActivityName() {
return sBaseActivityName;
}
public static String getDoubleTapListenerName() {
return sDoubleTabListenerName;
}
public static String getHeartIconTapListenerName() {
return sHeartIconTapListenerName;
}
} |
package se.sics.cooja.plugins;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.RenderingHints;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Observable;
import java.util.Observer;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;
import javax.swing.MenuElement;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.plaf.basic.BasicInternalFrameUI;
import org.apache.log4j.Logger;
import org.jdom.Element;
import se.sics.cooja.ClassDescription;
import se.sics.cooja.GUI;
import se.sics.cooja.HasQuickHelp;
import se.sics.cooja.Mote;
import se.sics.cooja.MoteInterface;
import se.sics.cooja.PluginType;
import se.sics.cooja.RadioMedium;
import se.sics.cooja.Simulation;
import se.sics.cooja.SupportedArguments;
import se.sics.cooja.VisPlugin;
import se.sics.cooja.GUI.MoteRelation;
import se.sics.cooja.SimEventCentral.MoteCountListener;
import se.sics.cooja.interfaces.LED;
import se.sics.cooja.interfaces.Position;
import se.sics.cooja.interfaces.SerialPort;
import se.sics.cooja.plugins.skins.AddressVisualizerSkin;
import se.sics.cooja.plugins.skins.AttributeVisualizerSkin;
import se.sics.cooja.plugins.skins.GridVisualizerSkin;
import se.sics.cooja.plugins.skins.IDVisualizerSkin;
import se.sics.cooja.plugins.skins.LEDVisualizerSkin;
import se.sics.cooja.plugins.skins.LogVisualizerSkin;
import se.sics.cooja.plugins.skins.MoteTypeVisualizerSkin;
import se.sics.cooja.plugins.skins.PositionVisualizerSkin;
import se.sics.cooja.plugins.skins.TrafficVisualizerSkin;
import se.sics.cooja.plugins.skins.UDGMVisualizerSkin;
/**
* Simulation visualizer supporting different visualizers
* Motes are painted in the XY-plane, as seen from positive Z axis.
*
* Supports drag-n-drop motes, right-click popup menu, and visualizers
*
* Observes the simulation and all mote positions.
*
* @see #registerMoteMenuAction(Class)
* @see #registerSimulationMenuAction(Class)
* @see #registerVisualizerSkin(Class)
* @see UDGMVisualizerSkin
* @author Fredrik Osterlind
*/
@ClassDescription("Network...")
@PluginType(PluginType.SIM_STANDARD_PLUGIN)
public class Visualizer extends VisPlugin implements HasQuickHelp {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(Visualizer.class);
public static final int MOTE_RADIUS = 8;
private static final Color[] DEFAULT_MOTE_COLORS = { Color.WHITE };
private GUI gui = null;
private Simulation simulation = null;
private final JPanel canvas;
private boolean loadedConfig = false;
private final JMenu viewMenu;
/* Viewport */
private AffineTransform viewportTransform;
public int resetViewport = 0;
/* Actions: move motes, pan view, and zoom view */
private boolean panning = false;
private Position panningPosition = null; /* Panning start position */
private boolean zooming = false;
private double zoomStart = 0;
private Position zoomingPosition = null; /* Zooming center position */
private Point zoomingPixel = null; /* Zooming center pixel */
private boolean moving = false;
private Mote movedMote = null;
public Mote clickedMote = null;
private long moveStartTime = -1;
private boolean moveConfirm;
private Cursor moveCursor = new Cursor(Cursor.MOVE_CURSOR);
/* Visualizers */
private final JButton skinButton = new JButton("Select visualizer skins");
private static ArrayList<Class<? extends VisualizerSkin>> visualizerSkins =
new ArrayList<Class<? extends VisualizerSkin>>();
static {
/* Register default visualizer skins */
registerVisualizerSkin(IDVisualizerSkin.class);
registerVisualizerSkin(AddressVisualizerSkin.class);
registerVisualizerSkin(LogVisualizerSkin.class);
registerVisualizerSkin(LEDVisualizerSkin.class);
registerVisualizerSkin(TrafficVisualizerSkin.class);
registerVisualizerSkin(PositionVisualizerSkin.class);
registerVisualizerSkin(GridVisualizerSkin.class);
registerVisualizerSkin(MoteTypeVisualizerSkin.class);
registerVisualizerSkin(AttributeVisualizerSkin.class);
}
private ArrayList<VisualizerSkin> currentSkins = new ArrayList<VisualizerSkin>();
/* Generic visualization */
private MoteCountListener newMotesListener;
private Observer posObserver = null;
private Observer moteHighligtObserver = null;
private ArrayList<Mote> highlightedMotes = new ArrayList<Mote>();
private final static Color HIGHLIGHT_COLOR = Color.CYAN;
private final static Color MOVE_COLOR = Color.WHITE;
private Observer moteRelationsObserver = null;
/* Popup menu */
public static interface SimulationMenuAction {
public boolean isEnabled(Visualizer visualizer, Simulation simulation);
public String getDescription(Visualizer visualizer, Simulation simulation);
public void doAction(Visualizer visualizer, Simulation simulation);
}
public static interface MoteMenuAction {
public boolean isEnabled(Visualizer visualizer, Mote mote);
public String getDescription(Visualizer visualizer, Mote mote);
public void doAction(Visualizer visualizer, Mote mote);
}
private ArrayList<Class<? extends SimulationMenuAction>> simulationMenuActions =
new ArrayList<Class<? extends SimulationMenuAction>>();
private ArrayList<Class<? extends MoteMenuAction>> moteMenuActions =
new ArrayList<Class<? extends MoteMenuAction>>();
public Visualizer(Simulation simulation, GUI gui) {
super("Network", gui);
this.gui = gui;
this.simulation = simulation;
/* Register external visualizers */
String[] skins = gui.getProjectConfig().getStringArrayValue(Visualizer.class, "SKINS");
if (skins != null) {
for (String skinClass: skins) {
Class<? extends VisualizerSkin> skin = gui.tryLoadClass(this, VisualizerSkin.class, skinClass);
if (registerVisualizerSkin(skin)) {
logger.info("Registered external visualizer: " + skinClass);
}
}
}
/* Menus */
JMenuBar menuBar = new JMenuBar();
viewMenu = new JMenu("View");
JMenu zoomMenu = new JMenu("Zoom");
menuBar.add(viewMenu);
menuBar.add(zoomMenu);
this.setJMenuBar(menuBar);
JMenuItem zoomInItem = new JMenuItem("Zoom in");
zoomInItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
zoomToFactor(zoomFactor() * 1.2);
}
});
zoomMenu.add(zoomInItem);
JMenuItem zoomOutItem = new JMenuItem("Zoom out");
zoomOutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
zoomToFactor(zoomFactor() / 1.2);
}
});
zoomMenu.add(zoomOutItem);
JMenuItem resetViewportItem = new JMenuItem("Reset viewport");
resetViewportItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
resetViewport = 1;
repaint();
}
});
zoomMenu.add(resetViewportItem);
/* Main canvas */
canvas = new JPanel() {
private static final long serialVersionUID = 1L;
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (resetViewport > 0) {
resetViewport();
resetViewport
}
((Graphics2D)g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for (VisualizerSkin skin: currentSkins) {
skin.paintBeforeMotes(g);
}
paintMotes(g);
for (VisualizerSkin skin: currentSkins) {
skin.paintAfterMotes(g);
}
}
};
canvas.setBackground(Color.WHITE);
viewportTransform = new AffineTransform();
/* Skin selector */
skinButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Point mouse = MouseInfo.getPointerInfo().getLocation();
JPopupMenu skinPopupMenu = new JPopupMenu();
populateSkinMenu(skinPopupMenu);
skinPopupMenu.setLocation(mouse);
skinPopupMenu.setInvoker(skinButton);
skinPopupMenu.setVisible(true);
}
});
/*this.add(BorderLayout.NORTH, skinButton);*/
this.add(BorderLayout.CENTER, canvas);
/* Observe simulation and mote positions */
posObserver = new Observer() {
public void update(Observable obs, Object obj) {
repaint();
}
};
simulation.getEventCentral().addMoteCountListener(newMotesListener = new MoteCountListener() {
public void moteWasAdded(Mote mote) {
Position pos = mote.getInterfaces().getPosition();
if (pos != null) {
pos.addObserver(posObserver);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
resetViewport = 1;
repaint();
}
});
}
}
public void moteWasRemoved(Mote mote) {
Position pos = mote.getInterfaces().getPosition();
if (pos != null) {
pos.deleteObserver(posObserver);
repaint();
}
}
});
for (Mote mote: simulation.getMotes()) {
Position pos = mote.getInterfaces().getPosition();
if (pos != null) {
pos.addObserver(posObserver);
}
}
/* Observe mote highlights */
gui.addMoteHighlightObserver(moteHighligtObserver = new Observer() {
public void update(Observable obs, Object obj) {
if (!(obj instanceof Mote)) {
return;
}
final Timer timer = new Timer(100, null);
final Mote mote = (Mote) obj;
timer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
/* Count down */
if (timer.getDelay() < 90) {
timer.stop();
highlightedMotes.remove(mote);
repaint();
return;
}
/* Toggle highlight state */
if (highlightedMotes.contains(mote)) {
highlightedMotes.remove(mote);
} else {
highlightedMotes.add(mote);
}
timer.setDelay(timer.getDelay()-1);
repaint();
}
});
timer.start();
}
});
/* Observe mote relations */
gui.addMoteRelationsObserver(moteRelationsObserver = new Observer() {
public void update(Observable obs, Object obj) {
repaint();
}
});
/* Popup menu */
canvas.addMouseMotionListener(new MouseMotionListener() {
public void mouseMoved(MouseEvent e) {
handleMouseMove(e, false);
}
public void mouseDragged(MouseEvent e) {
handleMouseMove(e, false);
}
});
canvas.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
handlePopupRequest(e.getPoint().x, e.getPoint().y);
return;
}
if (SwingUtilities.isLeftMouseButton(e)){
handleMousePress(e);
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
handlePopupRequest(e.getPoint().x, e.getPoint().y);
return;
}
handleMouseMove(e, true);
}
public void mouseClicked(MouseEvent e) {
if (e.isPopupTrigger()) {
handlePopupRequest(e.getPoint().x, e.getPoint().y);
}
handleMouseMove(e, true);
repaint();
}
});
/* Register mote menu actions */
registerMoteMenuAction(MoveMoteMenuAction.class);
registerMoteMenuAction(ButtonClickMoteMenuAction.class);
registerMoteMenuAction(ShowLEDMoteMenuAction.class);
registerMoteMenuAction(ShowSerialMoteMenuAction.class);
registerMoteMenuAction(DeleteMoteMenuAction.class);
/* Register simulation menu actions */
registerSimulationMenuAction(ResetViewportAction.class);
registerSimulationMenuAction(ToggleDecorationsMenuAction.class);
/* Drag and drop files to motes */
DropTargetListener dTargetListener = new DropTargetListener() {
public void dragEnter(DropTargetDragEvent dtde) {
if (acceptOrRejectDrag(dtde)) {
dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
} else {
dtde.rejectDrag();
}
}
public void dragExit(DropTargetEvent dte) {
}
public void dropActionChanged(DropTargetDragEvent dtde) {
if (acceptOrRejectDrag(dtde)) {
dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
} else {
dtde.rejectDrag();
}
}
public void dragOver(DropTargetDragEvent dtde) {
if (acceptOrRejectDrag(dtde)) {
dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
} else {
dtde.rejectDrag();
}
}
public void drop(DropTargetDropEvent dtde) {
Transferable transferable = dtde.getTransferable();
/* Only accept single files */
File file = null;
if (!transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
dtde.rejectDrop();
return;
}
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
try {
List<Object> transferList = Arrays.asList(
transferable.getTransferData(DataFlavor.javaFileListFlavor)
);
if (transferList.size() != 1) {
return;
}
List<File> list = (List<File>) transferList.get(0);
if (list.size() != 1) {
return;
}
file = list.get(0);
}
catch (Exception e) {
return;
}
if (file == null || !file.exists()) {
return;
}
handleDropFile(file, dtde.getLocation());
}
private boolean acceptOrRejectDrag(DropTargetDragEvent dtde) {
Transferable transferable = dtde.getTransferable();
/* Make sure one, and only one, mote exists under mouse pointer */
Point point = dtde.getLocation();
Mote[] motes = findMotesAtPosition(point.x, point.y);
if (motes == null || motes.length != 1) {
return false;
}
/* Only accept single files */
File file;
if (!transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
return false;
}
try {
List<Object> transferList = Arrays.asList(
transferable.getTransferData(DataFlavor.javaFileListFlavor)
);
if (transferList.size() != 1) {
return false;
}
List<File> list = (List<File>) transferList.get(0);
if (list.size() != 1) {
return false;
}
file = list.get(0);
} catch (UnsupportedFlavorException e) {
return false;
} catch (IOException e) {
return false;
}
/* Extract file extension */
return isDropFileAccepted(file);
}
};
canvas.setDropTarget(
new DropTarget(canvas, DnDConstants.ACTION_COPY_OR_MOVE, dTargetListener, true, null)
);
resetViewport = 3; /* XXX Quick-fix */
/* XXX HACK: here we set the position and size of the window when it appears on a blank simulation screen. */
this.setLocation(1, 1);
this.setSize(400, 400);
}
private void generateAndActivateSkin(Class<? extends VisualizerSkin> skinClass) {
for (VisualizerSkin skin: currentSkins) {
if (skinClass == skin.getClass()) {
logger.warn("Selected visualizer already active: " + skinClass);
return;
}
}
if (!isSkinCompatible(skinClass)) {
/*logger.warn("Skin is not compatible with current simulation: " + skinClass);*/
return;
}
/* Create and activate new skin */
try {
VisualizerSkin newSkin = skinClass.newInstance();
newSkin.setActive(Visualizer.this.simulation, Visualizer.this);
currentSkins.add(newSkin);
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
}
skinButton.setText("Select visualizer " +
"(" + currentSkins.size() + "/" + visualizerSkins.size() + ")");
repaint();
}
public void startPlugin() {
super.startPlugin();
if (loadedConfig) {
return;
}
/* Activate default skins */
String[] defaultSkins = GUI.getExternalToolsSetting("VISUALIZER_DEFAULT_SKINS", "").split(";");
for (String skin: defaultSkins) {
if (skin.isEmpty()) {
continue;
}
Class<? extends VisualizerSkin> skinClass =
simulation.getGUI().tryLoadClass(this, VisualizerSkin.class, skin);
generateAndActivateSkin(skinClass);
}
populateSkinMenu(viewMenu);
}
public VisualizerSkin[] getCurrentSkins() {
VisualizerSkin[] skins = new VisualizerSkin[currentSkins.size()];
return currentSkins.toArray(skins);
}
/**
* Register simulation menu action.
*
* @see SimulationMenuAction
* @param menuAction Menu action
*/
public void registerSimulationMenuAction(Class<? extends SimulationMenuAction> menuAction) {
if (simulationMenuActions.contains(menuAction)) {
return;
}
simulationMenuActions.add(menuAction);
}
public void unregisterSimulationMenuAction(Class<? extends SimulationMenuAction> menuAction) {
simulationMenuActions.remove(menuAction);
}
/**
* Register mote menu action.
*
* @see MoteMenuAction
* @param menuAction Menu action
*/
public void registerMoteMenuAction(Class<? extends MoteMenuAction> menuAction) {
if (moteMenuActions.contains(menuAction)) {
return;
}
moteMenuActions.add(menuAction);
}
public void unregisterMoteMenuAction(Class<? extends MoteMenuAction> menuAction) {
moteMenuActions.remove(menuAction);
}
public static boolean registerVisualizerSkin(Class<? extends VisualizerSkin> skin) {
if (visualizerSkins.contains(skin)) {
return false;
}
visualizerSkins.add(skin);
return true;
}
public static void unregisterVisualizerSkin(Class<? extends VisualizerSkin> skin) {
visualizerSkins.remove(skin);
}
private void handlePopupRequest(final int x, final int y) {
JPopupMenu menu = new JPopupMenu();
/* Mote specific actions */
final Mote[] motes = findMotesAtPosition(x, y);
if (motes != null && motes.length > 0) {
menu.add(new JSeparator());
/* Add registered mote actions */
for (final Mote mote : motes) {
menu.add(simulation.getGUI().createMotePluginsSubmenu(mote));
for (Class<? extends MoteMenuAction> menuActionClass: moteMenuActions) {
try {
final MoteMenuAction menuAction = menuActionClass.newInstance();
if (menuAction.isEnabled(this, mote)) {
JMenuItem menuItem = new JMenuItem(menuAction.getDescription(this, mote));
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
menuAction.doAction(Visualizer.this, mote);
}
});
menu.add(menuItem);
}
} catch (InstantiationException e1) {
logger.fatal("Error: " + e1.getMessage(), e1);
} catch (IllegalAccessException e1) {
logger.fatal("Error: " + e1.getMessage(), e1);
}
}
}
}
/* Simulation specific actions */
menu.add(new JSeparator());
for (Class<? extends SimulationMenuAction> menuActionClass: simulationMenuActions) {
try {
final SimulationMenuAction menuAction = menuActionClass.newInstance();
if (menuAction.isEnabled(this, simulation)) {
JMenuItem menuItem = new JMenuItem(menuAction.getDescription(this, simulation));
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
menuAction.doAction(Visualizer.this, simulation);
}
});
menu.add(menuItem);
}
} catch (InstantiationException e1) {
logger.fatal("Error: " + e1.getMessage(), e1);
} catch (IllegalAccessException e1) {
logger.fatal("Error: " + e1.getMessage(), e1);
}
}
/* Visualizer skin actions */
menu.add(new JSeparator());
/*JMenu skinMenu = new JMenu("Visualizers");
populateSkinMenu(skinMenu);
menu.add(skinMenu);
makeSkinsDefaultAction.putValue(Action.NAME, "Set default visualizers");
JMenuItem skinDefaultItem = new JMenuItem(makeSkinsDefaultAction);
menu.add(skinDefaultItem);*/
/* Show menu */
menu.setLocation(new Point(
canvas.getLocationOnScreen().x + x,
canvas.getLocationOnScreen().y + y));
menu.setInvoker(canvas);
menu.setVisible(true);
}
private void populateSkinMenu(MenuElement skinMenu) {
JCheckBoxMenuItem item;
for (Class<? extends VisualizerSkin> skinClass: visualizerSkins) {
String description = GUI.getDescriptionOf(skinClass);
item = new JCheckBoxMenuItem(description, false);
item.putClientProperty("skinclass", skinClass);
/* Select skin if active */
for (VisualizerSkin skin: currentSkins) {
if (skin.getClass() == skinClass) {
item.setSelected(true);
break;
}
}
item.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
JCheckBoxMenuItem menuItem = ((JCheckBoxMenuItem)e.getItem());
if (menuItem == null) {
logger.fatal("No menu item");
return;
}
Class<VisualizerSkin> skinClass =
(Class<VisualizerSkin>) menuItem.getClientProperty("skinclass");
if (skinClass == null) {
logger.fatal("Unknown visualizer skin class: " + skinClass);
return;
}
if (menuItem.isSelected()) {
/* Create and activate new skin */
generateAndActivateSkin(skinClass);
} else {
/* Deactivate skin */
VisualizerSkin skinToDeactivate = null;
for (VisualizerSkin skin: currentSkins) {
if (skin.getClass() == skinClass) {
skinToDeactivate = skin;
break;
}
}
if (skinToDeactivate == null) {
logger.fatal("Unknown visualizer to deactivate: " + skinClass);
return;
}
skinToDeactivate.setInactive();
repaint();
currentSkins.remove(skinToDeactivate);
skinButton.setText("Select visualizers " +
"(" + currentSkins.size() + "/" + visualizerSkins.size() + ")");
}
}
});
/* Should skin be enabled in this simulation? */
if (!isSkinCompatible(skinClass)) {
continue;
}
if (skinMenu instanceof JMenu) {
((JMenu)skinMenu).add(item);
}
if (skinMenu instanceof JPopupMenu) {
((JPopupMenu)skinMenu).add(item);
}
}
}
public boolean isSkinCompatible(Class<? extends VisualizerSkin> skinClass) {
if (skinClass == null) {
return false;
}
/* Check if skin depends on any particular radio medium */
boolean showMenuItem = true;
if (skinClass.getAnnotation(SupportedArguments.class) != null) {
showMenuItem = false;
Class<? extends RadioMedium>[] radioMediums = skinClass.getAnnotation(SupportedArguments.class).radioMediums();
for (Class<? extends Object> o: radioMediums) {
if (o.isAssignableFrom(simulation.getRadioMedium().getClass())) {
showMenuItem = true;
break;
}
}
}
if (!showMenuItem) {
return false;
}
return true;
}
private void handleMousePress(MouseEvent mouseEvent) {
int x = mouseEvent.getX();
int y = mouseEvent.getY();
clickedMote = null;
if (mouseEvent.isControlDown()) {
/* Zoom */
zooming = true;
zoomingPixel = new Point(x, y);
zoomingPosition = transformPixelToPosition(zoomingPixel);
zoomStart = viewportTransform.getScaleX();
return;
}
final Mote[] motes = findMotesAtPosition(x, y);
if (mouseEvent.isShiftDown() ||
(!mouseEvent.isAltDown() && (motes == null || motes.length == 0))) {
/* No motes clicked or shift pressed: We should pan */
panning = true;
panningPosition = transformPixelToPosition(x, y);
return;
}
if (motes != null && motes.length > 0) {
/* One of the clicked motes should be moved */
clickedMote = motes[0];
beginMoveRequest(motes[0], false, false);
}
}
private void beginMoveRequest(Mote moteToMove, boolean withTiming, boolean confirm) {
if (withTiming) {
moveStartTime = System.currentTimeMillis();
} else {
moveStartTime = -1;
}
moving = true;
moveConfirm = confirm;
movedMote = moteToMove;
repaint();
}
private double zoomFactor()
{
return viewportTransform.getScaleX();
}
private void zoomToFactor(double newZoom) {
viewportTransform.setToScale(
newZoom,
newZoom
);
/*Position moved = transformPixelToPosition(zoomingPixel);
viewportTransform.translate(
moved.getXCoordinate() - zoomingPosition.getXCoordinate(),
moved.getYCoordinate() - zoomingPosition.getYCoordinate()
);*/
repaint();
}
private void handleMouseMove(MouseEvent e, boolean stop) {
int x = e.getX();
int y = e.getY();
/* Panning */
if (panning) {
if (panningPosition == null || stop) {
panning = false;
return;
}
/* The current mouse position should correspond to where panning started */
Position moved = transformPixelToPosition(x,y);
viewportTransform.translate(
moved.getXCoordinate() - panningPosition.getXCoordinate(),
moved.getYCoordinate() - panningPosition.getYCoordinate()
);
repaint();
return;
}
/* Zooming */
if (zooming) {
if (zoomingPosition == null || zoomingPixel == null || stop) {
zooming = false;
return;
}
/* The zooming start pixel should correspond to the zooming center position */
/* The current mouse position should correspond to where panning started */
double zoomFactor = 1.0 + Math.abs((double) zoomingPixel.y - y)/100.0;
double newZoom = (zoomingPixel.y - y)>0?zoomStart*zoomFactor: zoomStart/zoomFactor;
if (newZoom < 0.00001) {
newZoom = 0.00001;
}
viewportTransform.setToScale(
newZoom,
newZoom
);
Position moved = transformPixelToPosition(zoomingPixel);
viewportTransform.translate(
moved.getXCoordinate() - zoomingPosition.getXCoordinate(),
moved.getYCoordinate() - zoomingPosition.getYCoordinate()
);
repaint();
return;
}
/* Moving */
if (moving) {
Position newPos = transformPixelToPosition(x, y);
if (!stop) {
canvas.setCursor(moveCursor);
movedMote.getInterfaces().getPosition().setCoordinates(
newPos.getXCoordinate(),
newPos.getYCoordinate(),
movedMote.getInterfaces().getPosition().getZCoordinate()
);
repaint();
return;
}
/* Restore cursor */
canvas.setCursor(Cursor.getDefaultCursor());
/* Move mote */
if (moveStartTime < 0 || System.currentTimeMillis() - moveStartTime > 300) {
if (moveConfirm) {
String options[] = {"Yes", "Cancel"};
int returnValue = JOptionPane.showOptionDialog(Visualizer.this,
"Move mote to" +
"\nX=" + newPos.getXCoordinate() +
"\nY=" + newPos.getYCoordinate() +
"\nZ=" + movedMote.getInterfaces().getPosition().getZCoordinate(),
"Move mote?",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
null, options, options[0]);
moving = returnValue == JOptionPane.YES_OPTION;
}
if (moving) {
movedMote.getInterfaces().getPosition().setCoordinates(
newPos.getXCoordinate(),
newPos.getYCoordinate(),
movedMote.getInterfaces().getPosition().getZCoordinate()
);
repaint();
}
}
moving = false;
movedMote = null;
repaint();
}
}
/**
* Returns all motes at given position.
*
* @param clickedX
* X coordinate
* @param clickedY
* Y coordinate
* @return All motes at given position
*/
public Mote[] findMotesAtPosition(int clickedX, int clickedY) {
double xCoord = transformToPositionX(clickedX);
double yCoord = transformToPositionY(clickedY);
ArrayList<Mote> motes = new ArrayList<Mote>();
// Calculate painted mote radius in coordinates
double paintedMoteWidth = transformToPositionX(MOTE_RADIUS)
- transformToPositionX(0);
double paintedMoteHeight = transformToPositionY(MOTE_RADIUS)
- transformToPositionY(0);
for (int i = 0; i < simulation.getMotesCount(); i++) {
Position pos = simulation.getMote(i).getInterfaces().getPosition();
// Transform to unit circle before checking if mouse hit this mote
double distanceX = Math.abs(xCoord - pos.getXCoordinate())
/ paintedMoteWidth;
double distanceY = Math.abs(yCoord - pos.getYCoordinate())
/ paintedMoteHeight;
if (distanceX * distanceX + distanceY * distanceY <= 1) {
motes.add(simulation.getMote(i));
}
}
if (motes.size() == 0) {
return null;
}
Mote[] motesArr = new Mote[motes.size()];
return motes.toArray(motesArr);
}
public void paintMotes(Graphics g) {
Mote[] allMotes = simulation.getMotes();
/* Paint mote relations */
MoteRelation[] relations = simulation.getGUI().getMoteRelations();
for (MoteRelation r: relations) {
Position sourcePos = r.source.getInterfaces().getPosition();
Position destPos = r.dest.getInterfaces().getPosition();
Point sourcePoint = transformPositionToPixel(sourcePos);
Point destPoint = transformPositionToPixel(destPos);
g.setColor(r.color == null ? Color.black : r.color);
drawArrow(g, sourcePoint.x, sourcePoint.y, destPoint.x, destPoint.y, MOTE_RADIUS + 1);
}
for (Mote mote: allMotes) {
/* Use the first skin's non-null mote colors */
Color moteColors[] = null;
for (VisualizerSkin skin: currentSkins) {
moteColors = skin.getColorOf(mote);
if (moteColors != null) {
break;
}
}
if (moteColors == null) {
moteColors = DEFAULT_MOTE_COLORS;
}
Position motePos = mote.getInterfaces().getPosition();
Point pixelCoord = transformPositionToPixel(motePos);
int x = pixelCoord.x;
int y = pixelCoord.y;
if (mote == movedMote) {
g.setColor(MOVE_COLOR);
g.fillOval(x - MOTE_RADIUS, y - MOTE_RADIUS, 2 * MOTE_RADIUS,
2 * MOTE_RADIUS);
} else if (!highlightedMotes.isEmpty() && highlightedMotes.contains(mote)) {
g.setColor(HIGHLIGHT_COLOR);
g.fillOval(x - MOTE_RADIUS, y - MOTE_RADIUS, 2 * MOTE_RADIUS,
2 * MOTE_RADIUS);
} else if (moteColors.length >= 2) {
g.setColor(moteColors[0]);
g.fillOval(x - MOTE_RADIUS, y - MOTE_RADIUS, 2 * MOTE_RADIUS,
2 * MOTE_RADIUS);
g.setColor(moteColors[1]);
g.fillOval(x - MOTE_RADIUS / 2, y - MOTE_RADIUS / 2, MOTE_RADIUS,
MOTE_RADIUS);
} else if (moteColors.length >= 1) {
g.setColor(moteColors[0]);
g.fillOval(x - MOTE_RADIUS, y - MOTE_RADIUS, 2 * MOTE_RADIUS,
2 * MOTE_RADIUS);
}
g.setColor(Color.BLACK);
g.drawOval(x - MOTE_RADIUS, y - MOTE_RADIUS, 2 * MOTE_RADIUS,
2 * MOTE_RADIUS);
}
}
private Polygon arrowPoly = new Polygon();
private void drawArrow(Graphics g, int xSource, int ySource, int xDest, int yDest, int delta) {
double dx = xSource - xDest;
double dy = ySource - yDest;
double dir = Math.atan2(dx, dy);
double len = Math.sqrt(dx * dx + dy * dy);
dx /= len;
dy /= len;
len -= delta;
xDest = xSource - (int) (dx * len);
yDest = ySource - (int) (dy * len);
g.drawLine(xDest, yDest, xSource, ySource);
final int size = 8;
arrowPoly.reset();
arrowPoly.addPoint(xDest, yDest);
arrowPoly.addPoint(xDest + xCor(size, dir + 0.5), yDest + yCor(size, dir + 0.5));
arrowPoly.addPoint(xDest + xCor(size, dir - 0.5), yDest + yCor(size, dir - 0.5));
arrowPoly.addPoint(xDest, yDest);
g.fillPolygon(arrowPoly);
}
private int yCor(int len, double dir) {
return (int)(0.5 + len * Math.cos(dir));
}
private int xCor(int len, double dir) {
return (int)(0.5 + len * Math.sin(dir));
}
/**
* Reset transform to show all motes.
*/
protected void resetViewport() {
Mote[] motes = simulation.getMotes();
if (motes.length == 0) {
/* No motes */
viewportTransform.setToIdentity();
return;
}
final double BORDER_SCALE_FACTOR = 1.1;
double smallX, bigX, smallY, bigY, scaleX, scaleY;
/* Init values */
{
Position pos = motes[0].getInterfaces().getPosition();
smallX = bigX = pos.getXCoordinate();
smallY = bigY = pos.getYCoordinate();
}
/* Extremes */
for (Mote mote: motes) {
Position pos = mote.getInterfaces().getPosition();
smallX = Math.min(smallX, pos.getXCoordinate());
bigX = Math.max(bigX, pos.getXCoordinate());
smallY = Math.min(smallY, pos.getYCoordinate());
bigY = Math.max(bigY, pos.getYCoordinate());
}
/* Scale viewport */
if (smallX == bigX) {
scaleX = 1;
} else {
scaleX = (bigX - smallX) / (canvas.getWidth());
}
if (smallY == bigY) {
scaleY = 1;
} else {
scaleY = (bigY - smallY) / (canvas.getHeight());
}
viewportTransform.setToIdentity();
double newZoom = (1.0/(BORDER_SCALE_FACTOR*Math.max(scaleX, scaleY)));
viewportTransform.setToScale(
newZoom,
newZoom
);
/* Center visible motes */
final double smallXfinal = smallX, bigXfinal = bigX, smallYfinal = smallY, bigYfinal = bigY;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Position viewMid =
transformPixelToPosition(canvas.getWidth()/2, canvas.getHeight()/2);
double motesMidX = (smallXfinal + bigXfinal) / 2.0;
double motesMidY = (smallYfinal + bigYfinal) / 2.0;
viewportTransform.translate(
viewMid.getXCoordinate() - motesMidX,
viewMid.getYCoordinate() - motesMidY);
canvas.repaint();
}
});
}
/**
* Transforms a real-world position to a pixel which can be painted onto the
* current sized canvas.
*
* @param pos
* Real-world position
* @return Pixel coordinates
*/
public Point transformPositionToPixel(Position pos) {
return transformPositionToPixel(
pos.getXCoordinate(),
pos.getYCoordinate(),
pos.getZCoordinate()
);
}
/**
* Transforms real-world coordinates to a pixel which can be painted onto the
* current sized canvas.
*
* @param x Real world X
* @param y Real world Y
* @param z Real world Z (ignored)
* @return Pixel coordinates
*/
public Point transformPositionToPixel(double x, double y, double z) {
return new Point(transformToPixelX(x), transformToPixelY(y));
}
/**
* @return Canvas
*/
public JPanel getCurrentCanvas() {
return canvas;
}
/**
* Transforms a pixel coordinate to a real-world. Z-value will always be 0.
*
* @param pixelPos
* On-screen pixel coordinate
* @return Real world coordinate (z=0).
*/
public Position transformPixelToPosition(Point pixelPos) {
return transformPixelToPosition(pixelPos.x, pixelPos.y);
}
public Position transformPixelToPosition(int x, int y) {
Position position = new Position(null);
position.setCoordinates(
transformToPositionX(x),
transformToPositionY(y),
0.0
);
return position;
}
private int transformToPixelX(double x) {
return (int) (viewportTransform.getScaleX()*x + viewportTransform.getTranslateX());
}
private int transformToPixelY(double y) {
return (int) (viewportTransform.getScaleY()*y + viewportTransform.getTranslateY());
}
private double transformToPositionX(int x) {
return (x - viewportTransform.getTranslateX())/viewportTransform.getScaleX() ;
}
private double transformToPositionY(int y) {
return (y - viewportTransform.getTranslateY())/viewportTransform.getScaleY() ;
}
public void closePlugin() {
for (VisualizerSkin skin: currentSkins) {
skin.setInactive();
}
currentSkins.clear();
if (moteHighligtObserver != null) {
gui.deleteMoteHighlightObserver(moteHighligtObserver);
}
if (moteRelationsObserver != null) {
gui.deleteMoteRelationsObserver(moteRelationsObserver);
}
simulation.getEventCentral().removeMoteCountListener(newMotesListener);
for (Mote mote: simulation.getMotes()) {
Position pos = mote.getInterfaces().getPosition();
if (pos != null) {
pos.deleteObserver(posObserver);
}
}
}
protected boolean isDropFileAccepted(File file) {
return true; /* TODO */
}
protected void handleDropFile(File file, Point point) {
logger.fatal("Drag and drop not implemented: " + file);
}
/**
* @return Selected mote
*/
public Mote getSelectedMote() {
return clickedMote;
}
public Collection<Element> getConfigXML() {
ArrayList<Element> config = new ArrayList<Element>();
Element element;
/* Skins */
for (VisualizerSkin skin: currentSkins) {
element = new Element("skin");
element.setText(skin.getClass().getName());
config.add(element);
}
/* Viewport */
element = new Element("viewport");
double[] matrix = new double[6];
viewportTransform.getMatrix(matrix);
element.setText(
matrix[0] + " " +
matrix[1] + " " +
matrix[2] + " " +
matrix[3] + " " +
matrix[4] + " " +
matrix[5]
);
config.add(element);
/* Hide decorations */
BasicInternalFrameUI ui = (BasicInternalFrameUI) getUI();
if (ui.getNorthPane().getPreferredSize() == null ||
ui.getNorthPane().getPreferredSize().height == 0) {
element = new Element("hidden");
config.add(element);
}
return config;
}
public boolean setConfigXML(Collection<Element> configXML, boolean visAvailable) {
loadedConfig = true;
for (Element element : configXML) {
if (element.getName().equals("skin")) {
String wanted = element.getText();
for (Class<? extends VisualizerSkin> skinClass: visualizerSkins) {
if (wanted.equals(skinClass.getName())
/* Backwards compatibility */
|| wanted.equals(GUI.getDescriptionOf(skinClass))) {
final Class<? extends VisualizerSkin> skin = skinClass;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
generateAndActivateSkin(skin);
}
});
wanted = null;
break;
}
}
if (wanted != null) {
logger.warn("Could not load visualizer: " + element.getText());
}
} else if (element.getName().equals("viewport")) {
try {
String[] matrix = element.getText().split(" ");
viewportTransform.setTransform(
Double.parseDouble(matrix[0]),
Double.parseDouble(matrix[1]),
Double.parseDouble(matrix[2]),
Double.parseDouble(matrix[3]),
Double.parseDouble(matrix[4]),
Double.parseDouble(matrix[5])
);
resetViewport = 0;
} catch (Exception e) {
logger.warn("Bad viewport: " + e.getMessage());
resetViewport();
}
} else if (element.getName().equals("hidden")) {
BasicInternalFrameUI ui = (BasicInternalFrameUI) getUI();
ui.getNorthPane().setPreferredSize(new Dimension(0,0));
skinButton.setVisible(false);
}
}
return true;
}
private AbstractAction makeSkinsDefaultAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
StringBuilder sb = new StringBuilder();
for (VisualizerSkin skin: currentSkins) {
if (sb.length() > 0) {
sb.append(';');
}
sb.append(skin.getClass().getName());
}
GUI.setExternalToolsSetting("VISUALIZER_DEFAULT_SKINS", sb.toString());
}
};
protected static class ButtonClickMoteMenuAction implements MoteMenuAction {
public boolean isEnabled(Visualizer visualizer, Mote mote) {
return mote.getInterfaces().getButton() != null
&& !mote.getInterfaces().getButton().isPressed();
}
public String getDescription(Visualizer visualizer, Mote mote) {
return "Click button on " + mote;
}
public void doAction(Visualizer visualizer, Mote mote) {
mote.getInterfaces().getButton().clickButton();
}
};
protected static class DeleteMoteMenuAction implements MoteMenuAction {
public boolean isEnabled(Visualizer visualizer, Mote mote) {
return true;
}
public String getDescription(Visualizer visualizer, Mote mote) {
return "Delete " + mote;
}
public void doAction(Visualizer visualizer, Mote mote) {
mote.getSimulation().removeMote(mote);
}
};
protected static class ShowLEDMoteMenuAction implements MoteMenuAction {
public boolean isEnabled(Visualizer visualizer, Mote mote) {
return mote.getInterfaces().getLED() != null;
}
public String getDescription(Visualizer visualizer, Mote mote) {
return "Show LEDs on " + mote;
}
public void doAction(Visualizer visualizer, Mote mote) {
Simulation simulation = mote.getSimulation();
LED led = mote.getInterfaces().getLED();
if (led == null) {
return;
}
/* Extract description (input to plugin) */
String desc = GUI.getDescriptionOf(mote.getInterfaces().getLED());
MoteInterfaceViewer viewer =
(MoteInterfaceViewer) simulation.getGUI().tryStartPlugin(
MoteInterfaceViewer.class,
simulation.getGUI(),
simulation,
mote);
if (viewer == null) {
return;
}
viewer.setSelectedInterface(desc);
viewer.pack();
}
};
protected static class ShowSerialMoteMenuAction implements MoteMenuAction {
public boolean isEnabled(Visualizer visualizer, Mote mote) {
for (MoteInterface intf: mote.getInterfaces().getInterfaces()) {
if (intf instanceof SerialPort) {
return true;
}
}
return false;
}
public String getDescription(Visualizer visualizer, Mote mote) {
return "Show serial port on " + mote;
}
public void doAction(Visualizer visualizer, Mote mote) {
Simulation simulation = mote.getSimulation();
SerialPort serialPort = null;
for (MoteInterface intf: mote.getInterfaces().getInterfaces()) {
if (intf instanceof SerialPort) {
serialPort = (SerialPort) intf;
break;
}
}
if (serialPort == null) {
return;
}
/* Extract description (input to plugin) */
String desc = GUI.getDescriptionOf(serialPort);
MoteInterfaceViewer viewer =
(MoteInterfaceViewer) simulation.getGUI().tryStartPlugin(
MoteInterfaceViewer.class,
simulation.getGUI(),
simulation,
mote);
if (viewer == null) {
return;
}
viewer.setSelectedInterface(desc);
viewer.pack();
}
};
protected static class MoveMoteMenuAction implements MoteMenuAction {
public boolean isEnabled(Visualizer visualizer, Mote mote) {
return true;
}
public String getDescription(Visualizer visualizer, Mote mote) {
return "Move " + mote;
}
public void doAction(Visualizer visualizer, Mote mote) {
visualizer.beginMoveRequest(mote, false, false);
}
};
protected static class ResetViewportAction implements SimulationMenuAction {
public void doAction(Visualizer visualizer, Simulation simulation) {
visualizer.resetViewport = 1;
visualizer.repaint();
}
public String getDescription(Visualizer visualizer, Simulation simulation) {
return "Reset viewport";
}
public boolean isEnabled(Visualizer visualizer, Simulation simulation) {
return true;
}
};
protected static class ToggleDecorationsMenuAction implements SimulationMenuAction {
public void doAction(final Visualizer visualizer, Simulation simulation) {
if (!(visualizer.getUI() instanceof BasicInternalFrameUI)) {
return;
}
BasicInternalFrameUI ui = (BasicInternalFrameUI) visualizer.getUI();
if (ui.getNorthPane().getPreferredSize() == null ||
ui.getNorthPane().getPreferredSize().height == 0) {
/* Restore window decorations */
ui.getNorthPane().setPreferredSize(null);
visualizer.skinButton.setVisible(true);
} else {
/* Hide window decorations */
ui.getNorthPane().setPreferredSize(new Dimension(0,0));
visualizer.skinButton.setVisible(false);
}
visualizer.revalidate();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
visualizer.repaint();
}
});
}
public String getDescription(Visualizer visualizer, Simulation simulation) {
if (!(visualizer.getUI() instanceof BasicInternalFrameUI)) {
return "Hide window decorations";
}
BasicInternalFrameUI ui = (BasicInternalFrameUI) visualizer.getUI();
if (ui.getNorthPane().getPreferredSize() == null ||
ui.getNorthPane().getPreferredSize().height == 0) {
return "Restore window decorations";
}
return "Hide window decorations";
}
public boolean isEnabled(Visualizer visualizer, Simulation simulation) {
if (!(visualizer.getUI() instanceof BasicInternalFrameUI)) {
return false;
}
return true;
}
}
public String getQuickHelp() {
return
"<b>Network</b> " +
"<p>The network windo shows the positions of simulated motes. " +
"It is possible to zoom (CRTL+Mouse drag) and pan (Shift+Mouse drag) the current view. Motes can be moved by dragging them. " +
"Mouse right-click motes for options. " +
"<p>The network window suppors different views. " +
"Each view provides some specific information, such as the IP addresses of motes. " +
"Multiple views can be active at the same time. " +
"Use the View menu to select views. ";
};
} |
package org.worshipsongs.activity;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceFragment;
import android.support.v4.app.FragmentActivity;
import android.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import org.worshipsongs.page.component.drawer.NavDrawerItem;
import org.worshipsongs.adapter.NavDrawerListAdapter;
import org.worshipsongs.WorshipSongApplication;
import org.worshipsongs.dao.SongDao;
import org.worshipsongs.domain.Song;
import org.worshipsongs.page.component.fragment.AuthorListFragment;
import org.worshipsongs.page.component.fragment.ServiceListFragment;
import org.worshipsongs.page.component.fragment.SongBookListFragment;
import org.worshipsongs.page.component.fragment.SongsListFragment;
import org.worshipsongs.page.component.fragment.WorshipSongsPreference;
import org.worshipsongs.service.IMobileNetworkService;
import org.worshipsongs.service.MobileNetworkService;
import org.worshipsongs.task.AsyncGitHubRepositoryTask;
import org.worshipsongs.worship.R;
public class MainActivity extends FragmentActivity
{
private DrawerLayout drawerLayout;
private ListView drawerListView;
private SongDao songDao;
private ActionBarDrawerToggle actionBarDrawerToggle;
private Context context = WorshipSongApplication.getContext();
// nav drawer title
private CharSequence drawerTitle;
private List<Song> songList;
// used to store app title
private CharSequence appTitle;
// slide menu items
private String[] navigationMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
private IMobileNetworkService mobileNetworkService = new MobileNetworkService();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_drawer);
appTitle = drawerTitle = getTitle();
songDao = new SongDao(this);
songDao.open();
songList = songDao.findTitles();
// load slide menu items
navigationMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerListView = (ListView) findViewById(R.id.list_slidermenu);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
// Songs
navDrawerItems.add(new NavDrawerItem(navigationMenuTitles[0], navMenuIcons.getResourceId(0, -1), true, Integer.toString(songList.size())));
// Authors
navDrawerItems.add(new NavDrawerItem(navigationMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
// Song books
navDrawerItems.add(new NavDrawerItem(navigationMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
// Services
navDrawerItems.add(new NavDrawerItem(navigationMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
// Settings
navDrawerItems.add(new NavDrawerItem(navigationMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
//Check database updates
navDrawerItems.add(new NavDrawerItem(navigationMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
// About
navDrawerItems.add(new NavDrawerItem(navigationMenuTitles[6], navMenuIcons.getResourceId(5, -1)));
// Recycle the typed array
navMenuIcons.recycle();
drawerListView.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(),
navDrawerItems);
drawerListView.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout,
R.drawable.ic_drawer, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
)
{
public void onDrawerClosed(View view)
{
getActionBar().setTitle(appTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView)
{
getActionBar().setTitle(drawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
drawerLayout.setDrawerListener(actionBarDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
/**
* Slide menu item click listener
*/
private class SlideMenuClickListener implements
ListView.OnItemClickListener
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id)
{
// display view for selected nav drawer item
displayView(position);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// toggle nav drawer on selecting action bar app icon/title
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
// case R.id.action_settings:
// return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* *
* Called when invalidateOptionsMenu() is triggered
*/
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
// if nav drawer is opened, hide the action items
boolean drawerOpen = drawerLayout.isDrawerOpen(drawerListView);
//menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
*/
private void displayView(int position)
{
// update the main content by replacing fragments
Fragment fragment = null;
PreferenceFragment preferenceFragment = null;
switch (position) {
case 0:
fragment = new SongsListFragment();
break;
case 1:
fragment = new AuthorListFragment();
break;
case 2:
fragment = new SongBookListFragment();
break;
case 3:
fragment = new ServiceListFragment();
break;
case 4:
preferenceFragment = new WorshipSongsPreference();
break;
case 5:
checkUpdates();
break;
case 6:
fragment = new AboutWebViewActivity();
break;
default:
break;
}
if (fragment != null || preferenceFragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
if (preferenceFragment != null) {
getFragmentManager().beginTransaction()
.replace(R.id.frame_container, new WorshipSongsPreference()).commit();
} else {
getFragmentManager().beginTransaction()
.replace(R.id.frame_container, fragment).commit();
}
// update selected item and title, then close the drawer
drawerListView.setItemChecked(position, true);
drawerListView.setSelection(position);
setTitle(navigationMenuTitles[position]);
drawerLayout.closeDrawer(drawerListView);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
public final boolean isWifi() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null) {
if (networkInfo.isConnected()) {
if ((networkInfo.getType() == ConnectivityManager.TYPE_WIFI)) {
return true;
}
}
}
Log.i(MainActivity.class.getSimpleName(), "System does not connect with wifi");
return false;
}
private void checkUpdates()
{
try {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
if(mobileNetworkService.isWifi(getSystemService(Context.CONNECTIVITY_SERVICE)) ||
mobileNetworkService.isMobileData(getSystemService(CONNECTIVITY_SERVICE))) {
Log.i(MainActivity.class.getSimpleName(), "System does connect with wifi");
AsyncGitHubRepositoryTask asyncGitHubRepositoryTask = new AsyncGitHubRepositoryTask(this);
if (asyncGitHubRepositoryTask.execute().get()) {
alertDialogBuilder.setTitle("Update is available");
alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
// continue to download database updates.
}
});
alertDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
}
});
} else {
alertDialogBuilder.setTitle("Update is not available");
alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
// continue with delete
}
});
}
}else{
alertDialogBuilder.setMessage("Atleast you need mobile data or wifi to check database updates");
alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
// continue with delete
}
});
}
alertDialogBuilder.setCancelable(true);
alertDialogBuilder.show();
} catch (Exception e) {
}
}
@Override
public void setTitle(CharSequence title)
{
appTitle = title;
getActionBar().setTitle(appTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
@Override
protected void onPostCreate(Bundle savedInstanceState)
{
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
actionBarDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
} |
package xal.tools.apputils;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Frame;
import javax.swing.*;
import javax.swing.table.*;
import java.util.*;
import xal.model.probe.Probe;
import xal.model.IAlgorithm;
import xal.tools.bricks.*;
import xal.tools.swing.*;
import xal.tools.data.*;
import java.beans.*;
import java.lang.reflect.*;
/** SimpleProbeEditor */
public class SimpleProbeEditor extends JDialog {
/** Private serializable version ID */
private static final long serialVersionUID = 1L;
/** Table model of ProbeProperty records */
final private KeyValueFilteredTableModel<PropertyRecord> PROPERTY_TABLE_MODEL;
/** List of properties that appear in the properties table */
final private List<PropertyRecord> PROBE_PROPERTY_RECORDS;
/** Probe that is being edited */
final private Probe PROBE;
/* Constructor that takes a window parent
* and a probe to fetch properties from
*/
public SimpleProbeEditor( final Frame owner, final Probe probe ) {
super( owner, "Probe Editor", true ); //Set JDialog's owner, title, and modality
PROBE = probe; // Set the probe to edit
// generate the probe property tree
final EditablePropertyContainer probePropertyTree = EditableProperty.getInstanceWithRoot( "Probe", probe );
//System.out.println( probePropertyTree );
PROBE_PROPERTY_RECORDS = PropertyRecord.toRecords( probePropertyTree );
PROPERTY_TABLE_MODEL = new KeyValueFilteredTableModel<>( PROBE_PROPERTY_RECORDS, "displayLabel", "value", "units" );
PROPERTY_TABLE_MODEL.setMatchingKeyPaths( "path" ); // match on the path
PROPERTY_TABLE_MODEL.setColumnName( "displayLabel", "Property" );
PROPERTY_TABLE_MODEL.setColumnEditKeyPath( "value", "editable" ); // the value is editable if the record is editable
setSize( 600, 600 ); // Set the window size
initializeComponents(); // Set up each component in the editor
pack(); // Fit the components in the window
setLocationRelativeTo( owner ); // Center the editor in relation to the frame that constructed the editor
setVisible(true); // Make the window visible
}
/**
* Get the probe to edit
* @return probe associated with this editor
*/
public Probe getProbe() {
return PROBE;
}
/** publish record values to the probe */
private void publishToProbe() {
for ( final PropertyRecord record : PROBE_PROPERTY_RECORDS ) {
record.publishIfNeeded();
}
}
/** revert the record values from the probe */
private void revertFromProbe() {
for ( final PropertyRecord record : PROBE_PROPERTY_RECORDS ) {
record.revertIfNeeded();
}
PROPERTY_TABLE_MODEL.fireTableDataChanged();
}
/** Initialize the components of the probe editor */
public void initializeComponents() {
//main view containing all components
final Box mainContainer = new Box( BoxLayout.Y_AXIS );
// button to revert changes back to last saved state
final JButton revertButton = new JButton( "Revert" );
revertButton.setToolTipText( "Revert values back to those in probe." );
revertButton.setEnabled( false );
// button to publish changes
final JButton publishButton = new JButton( "Publish" );
publishButton.setToolTipText( "Publish values to the probe." );
publishButton.setEnabled( false );
// button to publish changes and dismiss the panel
final JButton okayButton = new JButton( "Okay" );
okayButton.setToolTipText( "Publish values to the probe and dismiss the dialog." );
okayButton.setEnabled( true );
//Add the action listener as the ApplyButtonListener
revertButton.addActionListener( new ActionListener() {
public void actionPerformed( final ActionEvent event ) {
revertFromProbe();
revertButton.setEnabled( false );
publishButton.setEnabled( false );
}
});
//Add the action listener as the ApplyButtonListener
publishButton.addActionListener( new ActionListener() {
public void actionPerformed( final ActionEvent event ) {
publishToProbe();
revertButton.setEnabled( false );
publishButton.setEnabled( false );
}
});
//Add the action listener as the ApplyButtonListener
okayButton.addActionListener( new ActionListener() {
public void actionPerformed( final ActionEvent event ) {
try {
publishToProbe();
dispose();
}
catch( Exception exception ) {
JOptionPane.showMessageDialog( SimpleProbeEditor.this, exception.getMessage(), "Error Publishing", JOptionPane.ERROR_MESSAGE );
System.err.println( "Exception publishing values to probe: " + exception );
}
}
});
PROPERTY_TABLE_MODEL.addKeyValueRecordListener( new KeyValueRecordListener<KeyValueTableModel<PropertyRecord>,PropertyRecord>() {
public void recordModified( final KeyValueTableModel<PropertyRecord> source, final PropertyRecord record, final String keyPath, final Object value ) {
revertButton.setEnabled( true );
publishButton.setEnabled( true );
}
});
//Table containing the properties that can be modified
final JTable propertyTable = new JTable() {
/** Serializable version ID */
private static final long serialVersionUID = 1L;
/** renderer for a table section */
private final TableCellRenderer SECTION_RENDERER = makeSectionRenderer();
//Get the cell editor for the table
@Override
public TableCellEditor getCellEditor( final int row, final int col ) {
//Value at [row, col] of the table
final Object value = getValueAt( row, col );
if ( value == null ) {
return super.getCellEditor( row, col );
}
else {
return getDefaultEditor( value.getClass() );
}
}
//Get the cell renderer for the table to change how values are displayed
@Override
public TableCellRenderer getCellRenderer( final int row, final int col ) {
// index of the record in the model
final int recordIndex = this.convertRowIndexToModel( row );
final PropertyRecord record = PROPERTY_TABLE_MODEL.getRecordAtRow( recordIndex );
final Object value = getValueAt( row, col );
//Set the renderer according to the property type (e.g. Boolean => checkbox display, numeric => right justified)
if ( !record.isEditable() ) {
return SECTION_RENDERER;
}
else if ( value == null ) {
return super.getCellRenderer( row, col );
}
else {
return getDefaultRenderer( value.getClass() );
}
}
private TableCellRenderer makeSectionRenderer() {
final DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setBackground( Color.GRAY );
renderer.setForeground( Color.WHITE );
return renderer;
}
};
//Set the table to allow one-click edit
((DefaultCellEditor) propertyTable.getDefaultEditor(Object.class)).setClickCountToStart(1);
//Resize the last column
propertyTable.setAutoResizeMode( JTable.AUTO_RESIZE_LAST_COLUMN);
//Allow single selection only
propertyTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
//Set the model to the table
propertyTable.setModel( PROPERTY_TABLE_MODEL );
//Configure the text field to filter the table
final JTextField filterTextField = new JTextField();
filterTextField.setMaximumSize( new Dimension( 32000, filterTextField.getPreferredSize().height ) );
filterTextField.putClientProperty( "JTextField.variant", "search" );
filterTextField.putClientProperty( "JTextField.Search.Prompt", "Property Filter" );
PROPERTY_TABLE_MODEL.setInputFilterComponent( filterTextField );
mainContainer.add( filterTextField, BorderLayout.NORTH );
//Add the scrollpane to the table with a vertical scrollbar
final JScrollPane scrollPane = new JScrollPane( propertyTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
mainContainer.add( scrollPane );
//Add the buttons to the bottom of the dialog
final Box controlPanel = new Box( BoxLayout.X_AXIS );
controlPanel.add( revertButton );
controlPanel.add( Box.createHorizontalGlue() );
controlPanel.add( publishButton );
controlPanel.add( okayButton );
mainContainer.add( controlPanel );
//Add everything to the dialog
add( mainContainer );
}
}
/** Wraps a property for display as a record in a table */
class PropertyRecord {
/** wrapped property */
final private EditableProperty PROPERTY;
/** current value which may be pending */
private Object _value;
/** indicates that this record has unsaved changes */
private boolean _hasChanges;
/** Constructor */
public PropertyRecord( final EditableProperty property ) {
PROPERTY = property;
// initialize the value and status from the underlying property
revert();
}
/** name of the property */
public String getName() {
return PROPERTY.getName();
}
/** Get the path to this property */
public String getPath() {
return PROPERTY.getPath();
}
/** Get the label for display. */
public String getDisplayLabel() {
return isEditable() ? getName() : getPath();
}
/** Get the property type */
public Class<?> getPropertyType() {
return PROPERTY.getPropertyType();
}
/** Get the value for this property */
public Object getValue() {
return _value;
}
/** set the pending value */
public void setValueAsObject( final Object value ) {
if ( isEditable() ) {
_hasChanges = true;
_value = value;
}
}
/** set the pending value */
public void setValue( final boolean value ) {
setValueAsObject( Boolean.valueOf( value ) );
}
/** Set the pending string value. Most values (except for boolean) are set as string since the table cell editor does so. */
public void setValue( final String value ) {
final Class<?> rawType = getPropertyType();
if ( rawType == String.class ) {
setValueAsObject( value );
}
else {
try {
final Class<?> type = rawType.isPrimitive() ? _value.getClass() : rawType; // convert to wrapper type (e.g. double.class to Double.class) if necessary
final Object objectValue = toObjectOfType( value, type );
setValueAsObject( objectValue );
}
catch( Exception exception ) {
System.err.println( "Exception: " + exception );
System.err.println( "Error parsing the value: " + value + " as " + rawType );
}
}
}
/** Convert the string to an Object of the specified type */
static private Object toObjectOfType( final String stringValue, final Class<?> type ) {
try {
// every wrapper class has a static method named "valueOf" that takes a String and returns a corresponding instance of the wrapper
final Method converter = type.getMethod( "valueOf", String.class );
return converter.invoke( null, stringValue );
}
catch ( Exception exception ) {
throw new RuntimeException( "No match to parse string: " + stringValue + " as " + type );
}
}
/** synonym for isEditable so the table model will work */
public boolean getEditable() {
return isEditable();
}
/** only primitive properties are editable */
public boolean isEditable() {
return PROPERTY.isPrimitive();
}
/** indicates whether this record has unpublished changes */
public boolean hasChanges() {
return _hasChanges;
}
/** revert to the property value if this record is editable and has unpublished changes */
public void revertIfNeeded() {
if ( isEditable() && hasChanges() ) {
revert();
}
}
/** revert back to the current value of the underlying property */
public void revert() {
// the value is only meaningful for primitive properties (only thing we want to display)
_value = PROPERTY.isPrimitive() ? PROPERTY.getValue() : null;
_hasChanges = false;
}
/** publish the pending value to the underlying property if editable and marked with unpublished changes */
public void publishIfNeeded() {
if ( isEditable() && hasChanges() ) {
publish();
}
}
/** publish the pending value to the underlying property */
public void publish() {
PROPERTY.setValue( _value );
_hasChanges = false;
}
/** Get the units */
public String getUnits() {
return PROPERTY.getUnits();
}
/** Generate a flat list of records from the given property tree */
static public List<PropertyRecord> toRecords( final EditablePropertyContainer propertyTree ) {
final List<PropertyRecord> records = new ArrayList<>();
appendPropertiesToRecords( propertyTree, records );
return records;
}
/** append the properties in the given tree to the records nesting deeply */
static private void appendPropertiesToRecords( final EditablePropertyContainer propertyTree, final List<PropertyRecord> records ) {
records.add( new PropertyRecord( propertyTree ) ); // add the container itself
// add all the primitive properties
final List<EditablePrimitiveProperty> properties = propertyTree.getChildPrimitiveProperties();
for ( final EditablePrimitiveProperty property : properties ) {
records.add( new PropertyRecord( property ) );
}
// navigate down through each container and append their sub trees
final List<EditablePropertyContainer> containers = propertyTree.getChildPropertyContainers();
for ( final EditablePropertyContainer container : containers ) {
appendPropertiesToRecords( container, records ); // add the containers descendents
}
}
}
/** base class for a editable property */
abstract class EditableProperty {
/** array of classes for which the property can be edited directly */
final static protected Set<Class<?>> EDITABLE_PROPERTY_TYPES = new HashSet<>();
/** property name */
final protected String NAME;
/** path to this property */
final protected String PATH;
/** target object which is assigned the property */
final protected Object TARGET;
/** property descriptor */
final protected PropertyDescriptor PROPERTY_DESCRIPTOR;
// static initializer
static {
// cache the editable properties in a set for quick comparison later
final Class<?>[] editablePropertyTypes = { Double.class, Double.TYPE, Float.class, Float.TYPE, Integer.class, Integer.TYPE, Short.class, Short.TYPE, Long.class, Long.TYPE, Boolean.class, Boolean.TYPE, String.class };
for ( final Class<?> type : editablePropertyTypes ) {
EDITABLE_PROPERTY_TYPES.add( type );
}
}
/** Constructor */
protected EditableProperty( final String pathPrefix, final String name, final Object target, final PropertyDescriptor descriptor ) {
NAME = name;
PATH = pathPrefix != null && pathPrefix.length() > 0 ? pathPrefix + "." + name : name;
TARGET = target;
PROPERTY_DESCRIPTOR = descriptor;
}
/** Constructor */
protected EditableProperty( final String pathPrefix, final Object target, final PropertyDescriptor descriptor ) {
this( pathPrefix, descriptor.getName(), target, descriptor );
}
/** Get an instance starting at the root object */
static public EditablePropertyContainer getInstanceWithRoot( final String name, final Object root ) {
return EditablePropertyContainer.getInstanceWithRoot( name, root );
}
/** name of the property */
public String getName() {
return NAME;
}
/** Get the path to this property */
public String getPath() {
return PATH;
}
/** Get the property type */
public Class<?> getPropertyType() {
return PROPERTY_DESCRIPTOR != null ? PROPERTY_DESCRIPTOR.getPropertyType() : null;
}
/** Get the value for this property */
public Object getValue() {
if ( TARGET != null && PROPERTY_DESCRIPTOR != null ) {
final Method getter = PROPERTY_DESCRIPTOR.getReadMethod();
try {
return getter.invoke( TARGET );
}
catch( Exception exception ) {
System.err.println( exception );
return null;
}
}
else {
return null;
}
}
/** set the value */
abstract public void setValue( final Object value );
/** Get the units */
public String getUnits() {
return null;
}
/** determine whether the property is a container */
abstract public boolean isContainer();
/** determine whether the property is a primitive */
abstract public boolean isPrimitive();
/*
* Get the property descriptors for the given bean info
* @param target object for which to get the descriptors
* @return the property descriptors for non-null beanInfo otherwise null
*/
static protected PropertyDescriptor[] getPropertyDescriptors( final Object target ) {
if ( target != null ) {
final BeanInfo beanInfo = getBeanInfo( target );
return getPropertyDescriptorsForBeanInfo( beanInfo );
}
else {
return null;
}
}
/*
* Get the property descriptors for the given bean info
* @param beanInfo bean info
* @return the property descriptors for non-null beanInfo otherwise null
*/
static private PropertyDescriptor[] getPropertyDescriptorsForBeanInfo( final BeanInfo beanInfo ) {
return beanInfo != null ? beanInfo.getPropertyDescriptors() : null;
}
/** Convenience method to get the BeanInfo for an object's class */
static private BeanInfo getBeanInfo( final Object object ) {
if ( object != null ) {
return getBeanInfoForType( object.getClass() );
}
else {
return null;
}
}
/** Convenience method to get the BeanInfo for the given type */
static private BeanInfo getBeanInfoForType( final Class<?> propertyType ) {
if ( propertyType != null ) {
try {
return Introspector.getBeanInfo( propertyType );
}
catch( IntrospectionException exception ) {
return null;
}
}
else {
return null;
}
}
/** Get a string represenation of this property */
public String toString() {
return getPath();
}
}
/** editable property representing a primitive that is directly editable */
class EditablePrimitiveProperty extends EditableProperty {
/** property's units */
final private String UNITS;
/** Constructor */
protected EditablePrimitiveProperty( final String pathPrefix, final Object target, final PropertyDescriptor descriptor ) {
super( pathPrefix, target, descriptor );
UNITS = fetchUnits();
}
/** fetch the units */
private String fetchUnits() {
// form the accessor as get<PropertyName>Units() replacing <PropertyName> with the property's name whose first character is upper case
final char[] nameChars = getName().toCharArray();
nameChars[0] = Character.toUpperCase( nameChars[0] ); // capitalize the first character of the name
final String propertyName = String.valueOf( nameChars ); // property name whose first character is upper case
// first look for a method of the form get<PropertyName>Units() taking no arguments and returning a String
final String unitsAccessorName = "get" + propertyName + "Units";
try {
final Method unitsAccessor = TARGET.getClass().getMethod( unitsAccessorName );
if ( unitsAccessor.getReturnType() == String.class ) {
return (String)unitsAccessor.invoke( TARGET );
}
}
catch ( NoSuchMethodException exception ) {
// fallback look for a method of the form getUnitsForProperty( String name ) returning a String
try {
final Method unitsAccessor = TARGET.getClass().getMethod( "getUnitsForProperty", String.class );
if ( unitsAccessor.getReturnType() == String.class ) {
return (String)unitsAccessor.invoke( TARGET, getName() );
}
return "";
}
catch( Exception fallbackException ) {
return "";
}
}
catch( Exception exception ) {
System.out.println( exception );
return "";
}
return "";
}
/** determine whether the property is a container */
public boolean isContainer() {
return false;
}
/** determine whether the property is a primitive */
public boolean isPrimitive() {
return true;
}
/** Set the value for this property */
public void setValue( final Object value ) {
if ( TARGET != null && PROPERTY_DESCRIPTOR != null ) {
final Method setter = PROPERTY_DESCRIPTOR.getWriteMethod();
try {
setter.invoke( TARGET, value );
}
catch( Exception exception ) {
throw new RuntimeException( "Cannot set value " + value + " on target: " + TARGET + " with descriptor: " + PROPERTY_DESCRIPTOR.getName(), exception );
}
}
else {
if ( TARGET == null && PROPERTY_DESCRIPTOR == null ) {
throw new RuntimeException( "Cannot set value " + value + " on target because both the target and descriptor are null." );
}
else if ( TARGET == null ) {
throw new RuntimeException( "Cannot set value " + value + " on target with descriptor: " + PROPERTY_DESCRIPTOR.getName() + " because the target is null." );
}
else if ( PROPERTY_DESCRIPTOR == null ) {
throw new RuntimeException( "Cannot set value " + value + " on target: " + TARGET + " because the property descriptor is null." );
}
}
}
/** Get the units */
public String getUnits() {
return UNITS;
}
/** Get a string represenation of this property */
public String toString() {
return getPath() + ": " + getValue() + " " + getUnits();
}
}
/** base class for a container of editable properties */
class EditablePropertyContainer extends EditableProperty {
/** target for child properties */
final protected Object CHILD_TARGET;
/** set of ancestors to reference to prevent cycles */
final private Set<Object> ANCESTORS;
/** list of child primitive properties */
protected List<EditablePrimitiveProperty> _childPrimitiveProperties;
/** list of child property containers */
protected List<EditablePropertyContainer> _childPropertyContainers;
/** Primary Constructor */
protected EditablePropertyContainer( final String pathPrefix, final String name, final Object target, final PropertyDescriptor descriptor, final Object childTarget, final Set<Object> ancestors ) {
super( pathPrefix, name, target, descriptor );
CHILD_TARGET = childTarget;
ANCESTORS = ancestors;
}
/** Constructor */
protected EditablePropertyContainer( final String pathPrefix, final Object target, final PropertyDescriptor descriptor, final Object childTarget, final Set<Object> ancestors ) {
this( pathPrefix, descriptor.getName(), target, descriptor, childTarget, ancestors );
}
/** Constructor */
protected EditablePropertyContainer( final String pathPrefix, final Object target, final PropertyDescriptor descriptor, final Set<Object> ancestors ) {
this( pathPrefix, target, descriptor, generateChildTarget( target, descriptor ), ancestors );
}
/** Create an instance with the specified root Object */
static public EditablePropertyContainer getInstanceWithRoot( final String name, final Object rootObject ) {
final Set<Object> ancestors = new HashSet<Object>();
return new EditablePropertyContainer( "", name, null, null, rootObject, ancestors );
}
/** Generat the child target from the target and descriptor */
static private Object generateChildTarget( final Object target, final PropertyDescriptor descriptor ) {
try {
final Method readMethod = descriptor.getReadMethod();
return readMethod.invoke( target );
}
catch( Exception exception ) {
return null;
}
}
/** determine whether the property is a container */
public boolean isContainer() {
return true;
}
/** determine whether the property is a primitive */
public boolean isPrimitive() {
return false;
}
/** set the value */
public void setValue( final Object value ) {
throw new RuntimeException( "Usupported operation attempting to set the value of the editable property container: " + getPath() + " with value " + value );
}
/** determine whether this container has any child properties */
public boolean isEmpty() {
return getChildCount() == 0;
}
/** get the number of child properties */
public int getChildCount() {
generateChildPropertiesIfNeeded();
return _childPrimitiveProperties.size() + _childPropertyContainers.size();
}
/** Get the child properties */
public List<EditableProperty> getChildProperties() {
generateChildPropertiesIfNeeded();
final List<EditableProperty> properties = new ArrayList<>();
properties.addAll( _childPrimitiveProperties );
properties.addAll( _childPropertyContainers );
return properties;
}
/** Get the list of child primitive properties */
public List<EditablePrimitiveProperty> getChildPrimitiveProperties() {
generateChildPropertiesIfNeeded();
return _childPrimitiveProperties;
}
/** Get the list of child property containers */
public List<EditablePropertyContainer> getChildPropertyContainers() {
generateChildPropertiesIfNeeded();
return _childPropertyContainers;
}
/** generate the child properties if needed */
protected void generateChildPropertiesIfNeeded() {
if ( _childPrimitiveProperties == null ) {
generateChildProperties();
}
}
/** Generate the child properties this container's child target */
protected void generateChildProperties() {
_childPrimitiveProperties = new ArrayList<>();
_childPropertyContainers = new ArrayList<>();
final PropertyDescriptor[] descriptors = getPropertyDescriptors( CHILD_TARGET );
if ( descriptors != null ) {
for ( final PropertyDescriptor descriptor : descriptors ) {
if ( descriptor.getPropertyType() != Class.class ) {
generateChildPropertyForDescriptor( descriptor );
}
}
}
}
/** Generate the child properties starting at the specified descriptor for this container's child target */
protected void generateChildPropertyForDescriptor( final PropertyDescriptor descriptor ) {
final Method getter = descriptor.getReadMethod();
// include only properties whether the getter exists and is not deprecated
if ( getter != null && getter.getAnnotation( Deprecated.class ) == null ) {
final Class<?> propertyType = descriptor.getPropertyType();
if ( EDITABLE_PROPERTY_TYPES.contains( propertyType ) ) {
// if the property is an editable primitive with both a getter and setter then return the primitive property instance otherwise null
final Method setter = descriptor.getWriteMethod();
// include only properties whether the setter exists and is not deprecated (getter was already filtered in an enclosing block)
if ( setter != null && setter.getAnnotation( Deprecated.class ) == null ) {
_childPrimitiveProperties.add( new EditablePrimitiveProperty( PATH, CHILD_TARGET, descriptor ) );
}
return; // reached end of branch so we are done
}
else if ( propertyType == null ) {
return;
}
else if ( propertyType.isArray() ) {
// property is an array
// System.out.println( "Property type is array for target: " + CHILD_TARGET + " with descriptor: " + descriptor.getName() );
return;
}
else {
// property is a plain container
if ( !ANCESTORS.contains( CHILD_TARGET ) ) { // only propagate down the branch if the targets are unique (avoid cycles)
final Set<Object> ancestors = new HashSet<Object>( ANCESTORS );
ancestors.add( CHILD_TARGET );
final EditablePropertyContainer container = new EditablePropertyContainer( PATH, CHILD_TARGET, descriptor, ancestors );
if ( container.getChildCount() > 0 ) { // only care about containers that lead to editable properties
_childPropertyContainers.add( container );
}
}
return;
}
}
}
/** Get a string represenation of this property */
public String toString() {
final StringBuilder buffer = new StringBuilder();
buffer.append( getPath() + ":\n" );
for ( final EditableProperty property : getChildProperties() ) {
buffer.append( "\t" + property.toString() + "\n" );
}
return buffer.toString();
}
}
/** container for an editable property that is an array */
class EditableArrayProperty extends EditablePropertyContainer {
/** Constructor */
protected EditableArrayProperty( final String pathPrefix, final Object target, final PropertyDescriptor descriptor, final Set<Object> ancestors ) {
super( pathPrefix, target, descriptor, ancestors );
}
// TODO: complete implementation of array property
} |
package nl.mpi.arbil.data;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ResourceBundle;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import nl.mpi.arbil.ArbilIcons;
import nl.mpi.arbil.templates.ArbilTemplate;
import nl.mpi.arbil.ui.ArbilTrackingTree;
import nl.mpi.arbil.userstorage.SessionStorage;
import nl.mpi.arbil.util.BugCatcherManager;
import nl.mpi.arbil.util.MessageDialogHandler;
import nl.mpi.arbil.util.TreeHelper;
import nl.mpi.flap.model.DataNodeType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class AbstractTreeHelper implements TreeHelper {
public static final String SHOW_HIDDEN_FILES_IN_TREE_OPTION = "showHiddenFilesInTree";
public static final String GROUP_FAVOURITES_BY_TYPE_OPTION = "groupFavouritesByType";
private final static Logger logger = LoggerFactory.getLogger(AbstractTreeHelper.class);
private static final ResourceBundle widgets = ResourceBundle.getBundle("nl/mpi/arbil/localisation/Widgets");
private DefaultTreeModel localCorpusTreeModel;
private DefaultTreeModel remoteCorpusTreeModel;
private DefaultTreeModel localDirectoryTreeModel;
private DefaultTreeModel favouritesTreeModel;
private ArbilDataNode[] remoteCorpusNodes = new ArbilDataNode[]{};
private ArbilDataNode[] localCorpusNodes = new ArbilDataNode[]{};
private ArbilDataNode[] localFileNodes = new ArbilDataNode[]{};
private ArbilDataNode[] favouriteNodes = new ArbilDataNode[]{};
private boolean showHiddenFilesInTree = false;
private MessageDialogHandler messageDialogHandler;
private DataNodeLoader dataNodeLoader;
private boolean groupFavouritesByType = true;
/**
* ArbilRootNode for local corpus tree
*/
protected final ArbilRootNode localCorpusRootNodeObject;
/**
* ArbilRootNode for remote corpus tree
*/
protected final ArbilRootNode remoteCorpusRootNodeObject;
/**
* ArbilRootNode for working directories tree ('files')
*/
protected final ArbilRootNode localDirectoryRootNodeObject;
/**
* ArbilRootNode for favourites tree
*/
protected final ArbilRootNode favouritesRootNodeObject;
public AbstractTreeHelper(MessageDialogHandler messageDialogHandler) {
this.messageDialogHandler = messageDialogHandler;
this.localCorpusRootNodeObject = new ArbilRootNode(URI.create("LOCALCORPUS"), java.util.ResourceBundle.getBundle("nl/mpi/arbil/localisation/Widgets").getString("LOCAL CORPUS"), ArbilIcons.getSingleInstance().directoryIcon, true) {
public ArbilDataNode[] getChildArray() {
return getLocalCorpusNodes();
}
@Override
public DataNodeType getType() {
throw new UnsupportedOperationException("Not supported yet.");
}
public void setType(DataNodeType dataNodeType) {
throw new UnsupportedOperationException("Not supported yet.");
}
};
remoteCorpusRootNodeObject = new ArbilRootNode(URI.create("REMOTECORPUS"), java.util.ResourceBundle.getBundle("nl/mpi/arbil/localisation/Widgets").getString("REMOTE CORPUS"), ArbilIcons.getSingleInstance().serverIcon, false) {
public ArbilDataNode[] getChildArray() {
return getRemoteCorpusNodes();
}
@Override
public DataNodeType getType() {
throw new UnsupportedOperationException("Not supported yet.");
}
public void setType(DataNodeType dataNodeType) {
throw new UnsupportedOperationException("Not supported yet.");
}
};
localDirectoryRootNodeObject = new ArbilRootNode(URI.create("WORKINGDIRECTORIES"), java.util.ResourceBundle.getBundle("nl/mpi/arbil/localisation/Widgets").getString("WORKING DIRECTORIES"), ArbilIcons.getSingleInstance().computerIcon, true) {
public ArbilDataNode[] getChildArray() {
return getLocalFileNodes();
}
@Override
public DataNodeType getType() {
throw new UnsupportedOperationException("Not supported yet.");
}
public void setType(DataNodeType dataNodeType) {
throw new UnsupportedOperationException("Not supported yet.");
}
};
favouritesRootNodeObject = new ArbilRootNode(URI.create("FAVOURITES"), java.util.ResourceBundle.getBundle("nl/mpi/arbil/localisation/Widgets").getString("FAVOURITES"), ArbilIcons.getSingleInstance().favouriteIcon, true) {
Map<String, ContainerNode> containerNodeMap = new HashMap<String, ContainerNode>();
public ArbilNode[] getChildArray() {
if (groupFavouritesByType) {
containerNodeMap = groupTreeNodesByType(getFavouriteNodes(), containerNodeMap);
return containerNodeMap.values().toArray(new ArbilNode[]{});
} else {
return getFavouriteNodes();
}
}
@Override
public DataNodeType getType() {
throw new UnsupportedOperationException("Not supported yet.");
}
public void setType(DataNodeType dataNodeType) {
throw new UnsupportedOperationException("Not supported yet.");
}
};
}
protected final void initTrees() {
initTreeModels();
}
protected void initTreeModels() {
// Create tree models using the ArbilRootNodes as user objects for the root tree nodes.
// Second parameter of DefaultTreeModel constructor:
// asksAllowsChildren - a boolean, true if each node is asked to see if it can have children
localCorpusTreeModel = new DefaultTreeModel(new DefaultMutableTreeNode(localCorpusRootNodeObject), true);
remoteCorpusTreeModel = new DefaultTreeModel(new DefaultMutableTreeNode(remoteCorpusRootNodeObject), true);
localDirectoryTreeModel = new DefaultTreeModel(new DefaultMutableTreeNode(localDirectoryRootNodeObject), true);
favouritesTreeModel = new DefaultTreeModel(new DefaultMutableTreeNode(favouritesRootNodeObject), true);
}
@Override
public int addDefaultCorpusLocations() {
try {
addLocations(getClass().getResourceAsStream("/nl/mpi/arbil/defaults/imdiLocations"));
return remoteCorpusNodes.length;
} catch (IOException ex) {
BugCatcherManager.getBugCatcher().logError(ex);
return 0;
}
}
public int addDefaultCorpusLocationsOld() {
HashSet<ArbilDataNode> remoteCorpusNodesSet = new HashSet<ArbilDataNode>();
remoteCorpusNodesSet.addAll(Arrays.asList(remoteCorpusNodes));
for (String currentUrlString : new String[]{
"http://corpus1.mpi.nl/IMDI/metadata/IMDI.imdi",
"http://corpus1.mpi.nl/qfs1/media-archive/Corpusstructure/MPI.imdi",
"http://corpus1.mpi.nl/qfs1/media-archive/Corpusstructure/sign_language.imdi"
}) {
try {
remoteCorpusNodesSet.add(dataNodeLoader.getArbilDataNode(null, new URI(currentUrlString)));
} catch (URISyntaxException ex) {
BugCatcherManager.getBugCatcher().logError(ex);
}
}
remoteCorpusNodes = remoteCorpusNodesSet.toArray(new ArbilDataNode[]{});
return remoteCorpusNodesSet.size();
}
@Override
public void saveLocations(ArbilDataNode[] nodesToAdd, ArbilDataNode[] nodesToRemove) {
try {
final HashSet<String> locationsSet = new HashSet<String>();
for (ArbilDataNode[] currentTreeArray : new ArbilDataNode[][]{remoteCorpusNodes, localCorpusNodes, localFileNodes, favouriteNodes}) {
for (ArbilDataNode currentLocation : currentTreeArray) {
locationsSet.add(currentLocation.getUrlString());
}
}
if (nodesToAdd != null) {
for (ArbilDataNode currentAddable : nodesToAdd) {
if (currentAddable != null) {
logger.debug("Adding location {} from locations list", currentAddable.getUrlString());
locationsSet.add(currentAddable.getUrlString());
}
}
}
if (nodesToRemove != null) {
for (ArbilDataNode currentRemoveable : nodesToRemove) {
logger.debug("Removing location {} from locations list", currentRemoveable.getUrlString());
locationsSet.remove(currentRemoveable.getUrlString());
}
}
List<String> locationsList = new ArrayList<String>(); // this vector is kept for backwards compatability
for (String currentLocation : locationsSet) {
locationsList.add(URLDecoder.decode(currentLocation, "UTF-8"));
}
//LinorgSessionStorage.getSingleInstance().saveObject(locationsList, "locationsList");
getSessionStorage().saveStringArray("locationsList", locationsList.toArray(new String[]{}));
logger.debug("saved locationsList");
} catch (Exception ex) {
BugCatcherManager.getBugCatcher().logError(ex);
// logger.debug("save locationsList exception: " + ex.getMessage());
}
}
@Override
public final void loadLocationsList() {
logger.debug("loading locationsList");
String[] locationsArray = null;
try {
locationsArray = getSessionStorage().loadStringArray("locationsList");
} catch (IOException ex) {
BugCatcherManager.getBugCatcher().logError(ex);
messageDialogHandler.addMessageDialogToQueue(java.util.ResourceBundle.getBundle("nl/mpi/arbil/localisation/Widgets").getString("COULD NOT FIND OR LOAD LOCATIONS. ADDING DEFAULT LOCATIONS."), java.util.ResourceBundle.getBundle("nl/mpi/arbil/localisation/Widgets").getString("ERROR"));
}
if (locationsArray != null) {
ArrayList<ArbilDataNode> remoteCorpusNodesList = new ArrayList<ArbilDataNode>();
ArrayList<ArbilDataNode> localCorpusNodesList = new ArrayList<ArbilDataNode>();
ArrayList<ArbilDataNode> localFileNodesList = new ArrayList<ArbilDataNode>();
ArrayList<ArbilDataNode> favouriteNodesList = new ArrayList<ArbilDataNode>();
int failedLoads = 0;
// this also removes all locations and replaces them with normalised paths
for (String currentLocationString : locationsArray) {
URI currentLocation = null;
try {
currentLocation = ArbilDataNodeService.conformStringToUrl(currentLocationString);
} catch (URISyntaxException ex) {
BugCatcherManager.getBugCatcher().logError(ex);
}
if (currentLocation == null) {
BugCatcherManager.getBugCatcher().logError("Could conform string to url: " + currentLocationString, null);
failedLoads++;
} else {
try {
ArbilDataNode currentTreeObject = dataNodeLoader.getArbilDataNode(null, currentLocation);
if (currentTreeObject.isLocal()) {
if (currentTreeObject.isFavorite()) {
favouriteNodesList.add(currentTreeObject);
} else if (getSessionStorage().pathIsInsideCache(currentTreeObject.getFile())) {
if (currentTreeObject.isMetaDataNode() && !currentTreeObject.isChildNode()) {
localCorpusNodesList.add(currentTreeObject);
}
} else {
localFileNodesList.add(currentTreeObject);
}
} else {
remoteCorpusNodesList.add(currentTreeObject);
}
} catch (Exception ex) {
BugCatcherManager.getBugCatcher().logError("Failure in trying to load " + currentLocationString, ex);
failedLoads++;
}
}
}
if (failedLoads > 0) {
messageDialogHandler.addMessageDialogToQueue(java.text.MessageFormat.format(java.util.ResourceBundle.getBundle("nl/mpi/arbil/localisation/Widgets").getString("FAILED TO LOAD {0} LOCATIONS. SEE ERROR LOG FOR DETAILS."), new Object[]{failedLoads}), java.util.ResourceBundle.getBundle("nl/mpi/arbil/localisation/Widgets").getString("WARNING"));
}
remoteCorpusNodes = remoteCorpusNodesList.toArray(new ArbilDataNode[]{});
localCorpusNodes = localCorpusNodesList.toArray(new ArbilDataNode[]{});
localFileNodes = localFileNodesList.toArray(new ArbilDataNode[]{});
favouriteNodes = favouriteNodesList.toArray(new ArbilDataNode[]{});
}
showHiddenFilesInTree = getSessionStorage().loadBoolean(SHOW_HIDDEN_FILES_IN_TREE_OPTION, showHiddenFilesInTree);
groupFavouritesByType = getSessionStorage().loadBoolean(GROUP_FAVOURITES_BY_TYPE_OPTION, groupFavouritesByType);
}
@Override
public void setShowHiddenFilesInTree(boolean showState) {
showHiddenFilesInTree = showState;
reloadNodesInTree(localDirectoryTreeModel);
try {
getSessionStorage().saveBoolean(SHOW_HIDDEN_FILES_IN_TREE_OPTION, showHiddenFilesInTree);
} catch (Exception ex) {
logger.warn("save showHiddenFilesInTree failed", ex);
}
}
@Override
public void setGroupFavouritesByType(boolean groupFavouritesByType) {
this.groupFavouritesByType = groupFavouritesByType;
reloadNodesInTree(favouritesTreeModel);
try {
getSessionStorage().saveBoolean(GROUP_FAVOURITES_BY_TYPE_OPTION, groupFavouritesByType);
} catch (Exception ex) {
logger.warn("save groupFavouritesByType failed", ex);
}
}
public void addLocations(List<URI> locations) {
ArbilDataNode[] addedNodes = new ArbilDataNode[locations.size()];
for (int i = 0; i < locations.size(); i++) {
URI addedLocation = locations.get(i);
logger.debug("addLocation: " + addedLocation.toString());
// make sure the added location url matches that of the imdi node format
addedNodes[i] = dataNodeLoader.getArbilDataNode(null, addedLocation);
}
saveLocations(addedNodes, null);
loadLocationsList();
}
public void addLocations(InputStream inputStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
List<URI> locationsList = new LinkedList<URI>();
String location = reader.readLine();
while (location != null) {
try {
URI uri = new URI(location);
locationsList.add(uri);
} catch (URISyntaxException ex) {
BugCatcherManager.getBugCatcher().logError(ex);
}
location = reader.readLine();
}
addLocations(locationsList);
}
public void clearRemoteLocations() {
for (ArbilDataNode removeNode : remoteCorpusNodes) {
removeLocation(removeNode.getURI());
}
}
@Override
public boolean addLocationInteractive(URI addableLocation) {
return addLocation(addableLocation);
}
@Override
public boolean addLocation(URI addedLocation) {
logger.debug("addLocation: " + addedLocation.toString());
// make sure the added location url matches that of the imdi node format
final ArbilDataNode addedLocationObject = dataNodeLoader.getArbilDataNode(null, addedLocation);
//TODO: Synchronize this
if (addedLocationObject != null) {
addedLocationObject.reloadNode();
saveLocations(new ArbilDataNode[]{addedLocationObject}, null);
loadLocationsList();
return true;
} else {
logger.warn("Could not retrieve data node for location added to tree {}", addedLocation);
return false;
}
}
@Override
public void removeLocation(ArbilDataNode removeObject) {
if (removeObject != null) {
//TODO: Synchronize this
saveLocations(null, new ArbilDataNode[]{removeObject});
removeObject.removeFromAllContainers();
loadLocationsList();
}
}
@Override
public void removeLocation(URI removeLocation) {
logger.debug("removeLocation: " + removeLocation);
removeLocation(dataNodeLoader.getArbilDataNode(null, removeLocation));
}
private void reloadNodesInTree(DefaultTreeModel treeModel) {
final DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) treeModel.getRoot();
reloadNodesInTree(rootNode);
applyRootLocations();
}
private void reloadNodesInTree(DefaultMutableTreeNode parentTreeNode) {
// this will reload all nodes in a tree but not create any new child nodes
for (Enumeration<DefaultMutableTreeNode> childNodesEnum = parentTreeNode.children(); childNodesEnum.hasMoreElements();) {
reloadNodesInTree(childNodesEnum.nextElement());
}
if (parentTreeNode.getUserObject() instanceof ArbilDataNode) {
if (((ArbilDataNode) parentTreeNode.getUserObject()).isDataLoaded()) {
((ArbilDataNode) parentTreeNode.getUserObject()).reloadNodeShallowly();
}
}
}
@Override
public boolean locationsHaveBeenAdded() {
return localCorpusNodes.length > 0;
}
@Override
public abstract void applyRootLocations();
@Override
public abstract void deleteNodes(Object sourceObject);
protected void deleteNodesFromParent(Collection<ArbilDataNode> nodesToDeleteFromParent) {
final Map<ArbilDataNode, Collection<ArbilDataNode>> nodesToDelete = determineNodesToDelete(nodesToDeleteFromParent);
// Ask confirmation for deletion for each set of child nodes (grouped by parent node)
askDeleteNodes(nodesToDelete);
// If nodes were selected that do not have a parent, give notification
if (nodesToDelete.containsKey(null)) {
final int nodeCount = nodesToDelete.get(null).size();
if (nodeCount > 1) {
messageDialogHandler.addMessageDialogToQueue(MessageFormat.format(widgets.getString("%D NODES COULD NOT BE DELETED BECAUSE THEY HAVE NO PARENT"), nodeCount), widgets.getString("DELETE FROM PARENT"));
} else {
messageDialogHandler.addMessageDialogToQueue(widgets.getString("COULD NOT DELETE NODE BECAUSE IT HAS NO PARENT"), widgets.getString("DELETE FROM PARENT"));
}
}
}
private Map<ArbilDataNode, Collection<ArbilDataNode>> determineNodesToDelete(final Collection<ArbilDataNode> nodesToDeleteFromParent) {
final Map<ArbilDataNode, Collection<ArbilDataNode>> deletionMap = new HashMap<ArbilDataNode, Collection<ArbilDataNode>>();
for (ArbilDataNode selectedNode : nodesToDeleteFromParent) {
final ArbilDataNode parentNode = selectedNode.getParentNode();
// Look for existing collection for parent node
Collection<ArbilDataNode> children = deletionMap.get(parentNode);
if (children == null) {
// First encounter of parent node, make list to store children
children = new ArrayList<ArbilDataNode>();
deletionMap.put(parentNode, children);
}
// Add child to parent's list
children.add(selectedNode);
}
return deletionMap;
}
private void askDeleteNodes(final Map<ArbilDataNode, Collection<ArbilDataNode>> nodesToDelete) {
MessageDialogHandler.DialogBoxResult dialogResult = null;
for (Entry<ArbilDataNode, Collection<ArbilDataNode>> entry : nodesToDelete.entrySet()) {
final ArbilDataNode parentNode = entry.getKey();
if (parentNode != null) {
final Collection<ArbilDataNode> children = entry.getValue();
if (dialogResult == null || !dialogResult.isRememberChoice()) {
dialogResult = messageDialogHandler.showDialogBoxRememberChoice(getNodeDeleteMessage(parentNode, children), widgets.getString("DELETE FROM PARENT"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
}
if (dialogResult.getResult() == JOptionPane.OK_OPTION) {
deleteChildNodes(parentNode, children);
} else if (dialogResult.getResult() == JOptionPane.CANCEL_OPTION) {
return;
}
}
}
}
private String getNodeDeleteMessage(ArbilDataNode parentNode, Collection<ArbilDataNode> children) {
if (children.size() == 1) {
return MessageFormat.format(widgets.getString("DELETE THE NODE '%S' FROM ITS PARENT '%S'?"), children.iterator().next(), parentNode.toString());
} else {
return MessageFormat.format(widgets.getString("DELETE %D NODES FROM THEIR PARENT '%S'?"), children.size(), parentNode.toString());
}
}
public void deleteChildNodes(ArbilDataNode parent, Collection<ArbilDataNode> children) {
Map<ArbilDataNode, List<ArbilDataNode>> dataNodesDeleteList = new HashMap<ArbilDataNode, List<ArbilDataNode>>();
Map<ArbilDataNode, List<String>> childNodeDeleteList = new HashMap<ArbilDataNode, List<String>>();
Map<ArbilDataNode, List<ArbilDataNode>> cmdiLinksDeleteList = new HashMap<ArbilDataNode, List<ArbilDataNode>>();
for (ArbilDataNode child : children) {
determineDeleteFromParent(child, parent, childNodeDeleteList, dataNodesDeleteList, cmdiLinksDeleteList);
}
// delete child nodes
deleteNodesByChidXmlIdLink(childNodeDeleteList);
// delete parent nodes
deleteNodesByCorpusLink(dataNodesDeleteList);
// delete cmdi links
deleteCmdiLinks(cmdiLinksDeleteList);
}
protected void determineNodesToDelete(TreePath[] nodePaths, Map<ArbilDataNode, List<String>> childNodeDeleteList, Map<ArbilDataNode, List<ArbilDataNode>> dataNodesDeleteList, Map<ArbilDataNode, List<ArbilDataNode>> cmdiLinksDeleteList) {
final Vector<ArbilDataNode> dataNodesToRemove = new Vector<ArbilDataNode>();
for (TreePath currentNodePath : nodePaths) {
if (currentNodePath != null) {
final DefaultMutableTreeNode selectedTreeNode = (DefaultMutableTreeNode) currentNodePath.getLastPathComponent();
final Object selectedNode = selectedTreeNode.getUserObject();
if (selectedNode instanceof ArbilDataNode) {
final boolean rootLevelNode = currentNodePath.getPath().length == 2;
final DefaultMutableTreeNode parentTreeNode = (DefaultMutableTreeNode) selectedTreeNode.getParent();
determineNodesToDelete((ArbilDataNode) selectedNode, rootLevelNode, parentTreeNode, childNodeDeleteList, dataNodesDeleteList, cmdiLinksDeleteList, dataNodesToRemove);
} else {
logger.warn("Cannot delete selected node {}, not an ArbilDataNode", selectedNode);
}
}
}
}
private void determineNodesToDelete(ArbilDataNode selectedNode, boolean rootLevelNode, DefaultMutableTreeNode parentTreeNode, Map<ArbilDataNode, List<String>> childNodeDeleteList, Map<ArbilDataNode, List<ArbilDataNode>> dataNodesDeleteList, Map<ArbilDataNode, List<ArbilDataNode>> cmdiLinksDeleteList, Vector<ArbilDataNode> dataNodesToRemove) {
logger.debug("trying to delete: {}", selectedNode);
if (rootLevelNode || selectedNode.isFavorite()) {
// In locations list (i.e. child of root node)
logger.debug("removing by location: {}", selectedNode);
removeLocation(selectedNode);
applyRootLocations();
} else {
logger.debug("deleting from parent");
if (parentTreeNode != null) {
logger.debug("found parent to remove from");
final Object parentTreeNodeObject = parentTreeNode.getUserObject();
if (parentTreeNodeObject instanceof ArbilDataNode) {
ArbilDataNode parentDataNode = (ArbilDataNode) parentTreeNodeObject;
determineDeleteFromParent(selectedNode, parentDataNode, childNodeDeleteList, dataNodesDeleteList, cmdiLinksDeleteList);
} else {
logger.warn("Cannot delete from selected parent node {}, not an ArbilDataNode", parentTreeNodeObject);
}
}
}
// todo: this fixes some of the nodes left after a delete EXCEPT; for example, the "actors" node when all the actors are deleted
// ArbilTreeHelper.getSingleInstance().removeAndDetatchDescendantNodes(selectedTreeNode);
// make a list of all child nodes so that they can be removed from any tables etc
dataNodesToRemove.add((ArbilDataNode) selectedNode);
((ArbilDataNode) selectedNode).getAllChildren(dataNodesToRemove);
}
private void determineDeleteFromParent(ArbilDataNode childDataNode, ArbilDataNode parentDataNode, Map<ArbilDataNode, List<String>> childNodeDeleteList, Map<ArbilDataNode, List<ArbilDataNode>> dataNodesDeleteList, Map<ArbilDataNode, List<ArbilDataNode>> cmdiLinksDeleteList) {
if (childDataNode.isChildNode()) {
// there is a risk of the later deleted nodes being outof sync with the xml, so we add them all to a list and delete all at once before the node is reloaded
if (!childNodeDeleteList.containsKey(childDataNode.getParentDomNode())) {
childNodeDeleteList.put(childDataNode.getParentDomNode(), new Vector());
}
if (childDataNode.isEmptyMetaNode()) {
for (ArbilDataNode metaChildNode : childDataNode.getChildArray()) {
childNodeDeleteList.get(childDataNode.getParentDomNode()).add(metaChildNode.getURIFragment());
}
}
childNodeDeleteList.get(childDataNode.getParentDomNode()).add(childDataNode.getURIFragment());
childDataNode.removeFromAllContainers();
} else if (parentDataNode.isCmdiMetaDataNode()) {
// CMDI link
if (!cmdiLinksDeleteList.containsKey(parentDataNode)) {
cmdiLinksDeleteList.put(parentDataNode, new ArrayList<ArbilDataNode>());
}
cmdiLinksDeleteList.get(parentDataNode).add(childDataNode);
} else {
// Not a child node or CMDI resource, ergo corpus child
// Add the parent and the child node to the deletelist
if (!dataNodesDeleteList.containsKey(parentDataNode)) {
dataNodesDeleteList.put(parentDataNode, new Vector());
}
dataNodesDeleteList.get(parentDataNode).add(childDataNode);
}
// remove the deleted node from the favourites list if it is an imdichild node
// if (userObject instanceof ImdiTreeObject) {
// if (((ImdiTreeObject) userObject).isImdiChild()){
// LinorgTemplates.getSingleInstance().removeFromFavourites(((ImdiTreeObject) userObject).getUrlString());
}
protected void deleteNodesByChidXmlIdLink(Map<ArbilDataNode, List<String>> childNodeDeleteList) {
for (Entry<ArbilDataNode, List<String>> deleteEntry : childNodeDeleteList.entrySet()) {
ArbilDataNode currentParent = deleteEntry.getKey();
logger.debug("deleting by child xml id link");
// TODO: There is an issue when deleting child nodes that the remaining nodes xml path (x) will be incorrect as will the xmlnode id hence the node in a table may be incorrect after a delete
//currentParent.deleteFromDomViaId(((Vector<String>) imdiChildNodeDeleteList.get(currentParent)).toArray(new String[]{}));
ArbilComponentBuilder componentBuilder = new ArbilComponentBuilder();
boolean result = componentBuilder.removeChildNodes(currentParent, deleteEntry.getValue().toArray(new String[]{}));
if (result) {
// Invalidate all thumbnails for the parent node. If MediaFiles are deleted, this prevents the thumbnails to get 'shifted'
// i.e. stick on the wrong note. This could perhaps be done a bit more sophisticated, it is not actually needed
// unless MediaFiles are deleted
currentParent.invalidateThumbnails();
currentParent.reloadNode();
} else {
messageDialogHandler.addMessageDialogToQueue(java.util.ResourceBundle.getBundle("nl/mpi/arbil/localisation/Widgets").getString("ERROR DELETING NODE, CHECK THE LOG FILE VIA THE HELP MENU FOR MORE INFORMATION."), java.util.ResourceBundle.getBundle("nl/mpi/arbil/localisation/Widgets").getString("DELETE NODE"));
}
}
}
protected void deleteNodesByCorpusLink(Map<ArbilDataNode, List<ArbilDataNode>> dataNodesDeleteList) {
for (Entry<ArbilDataNode, List<ArbilDataNode>> deleteEntry : dataNodesDeleteList.entrySet()) {
logger.debug("deleting by corpus link");
deleteEntry.getKey().deleteCorpusLink(deleteEntry.getValue().toArray(new ArbilDataNode[]{}));
}
}
protected void deleteCmdiLinks(Map<ArbilDataNode, List<ArbilDataNode>> cmdiLinks) {
ArbilComponentBuilder componentBuilder = new ArbilComponentBuilder();
for (Entry<ArbilDataNode, List<ArbilDataNode>> deleteEntry : cmdiLinks.entrySet()) {
ArrayList<String> references = new ArrayList<String>(deleteEntry.getValue().size());
for (ArbilDataNode node : deleteEntry.getValue()) {
references.add(node.getUrlString());
}
if (componentBuilder.removeResourceProxyReferences(deleteEntry.getKey(), references)) {
deleteEntry.getKey().reloadNode();
} else {
messageDialogHandler.addMessageDialogToQueue(java.util.ResourceBundle.getBundle("nl/mpi/arbil/localisation/Widgets").getString("ERROR DELETING NODE, CHECK THE LOG FILE VIA THE HELP MENU FOR MORE INFORMATION."), java.util.ResourceBundle.getBundle("nl/mpi/arbil/localisation/Widgets").getString("DELETE NODE"));
}
}
}
@Override
public void jumpToSelectionInTree(boolean silent, ArbilDataNode cellDataNode) {
// TODO: Now does not work for nodes that have not been exposed in the tree. This is because the tree
// is not registered as container for those nodes. This needs to be detected and worked around, or if that is too messy
// the jump to tree item should be disabled for those nodes.
for (ArbilDataNodeContainer container : cellDataNode.getRegisteredContainers()) {
if (container instanceof ArbilTrackingTree) {
boolean found = false;
if (cellDataNode.isChildNode()) {
// Try from parent first
found = ((ArbilTrackingTree) container).jumpToNode(cellDataNode.getParentDomNode(), cellDataNode);
}
if (!found) {
// Try from tree root
((ArbilTrackingTree) container).jumpToNode(null, cellDataNode);
}
}
}
}
@Override
public boolean isInFavouritesNodes(ArbilDataNode dataNode) {
return Arrays.asList(favouriteNodes).contains(dataNode);
}
/**
* @return the localCorpusTreeModel
*/
@Override
public DefaultTreeModel getLocalCorpusTreeModel() {
return localCorpusTreeModel;
}
/**
* @return the remoteCorpusTreeModel
*/
@Override
public DefaultTreeModel getRemoteCorpusTreeModel() {
return remoteCorpusTreeModel;
}
/**
* @return the localDirectoryTreeModel
*/
@Override
public DefaultTreeModel getLocalDirectoryTreeModel() {
return localDirectoryTreeModel;
}
/**
* @return the favouritesTreeModel
*/
@Override
public DefaultTreeModel getFavouritesTreeModel() {
return favouritesTreeModel;
}
/**
* @return the remoteCorpusNodes
*/
@Override
public ArbilDataNode[] getRemoteCorpusNodes() {
return remoteCorpusNodes;
}
/**
* @return the localCorpusNodes
*/
@Override
public ArbilDataNode[] getLocalCorpusNodes() {
return localCorpusNodes;
}
/**
* @return the localFileNodes
*/
@Override
public ArbilDataNode[] getLocalFileNodes() {
return localFileNodes;
}
/**
* @return the favouriteNodes
*/
@Override
public ArbilDataNode[] getFavouriteNodes() {
return favouriteNodes;
}
protected Map<String, ContainerNode> groupTreeNodesByType(ArbilDataNode[] favouriteNodes, Map<String, ContainerNode> containerNodeMap) {
final Map<String, HashSet<ArbilDataNode>> metaNodeMap = new HashMap<String, HashSet<ArbilDataNode>>();
for (ArbilDataNode arbilDataNode : favouriteNodes) {
String containerNodeLabel = java.util.ResourceBundle.getBundle("nl/mpi/arbil/localisation/Widgets").getString("OTHER");
if (arbilDataNode.isChildNode()) {
final String urlString = arbilDataNode.getUrlString();
containerNodeLabel = urlString.substring(urlString.lastIndexOf(".") + 1);
containerNodeLabel = containerNodeLabel.replaceFirst("\\([0-9]*\\)", "");
if (arbilDataNode.isCmdiMetaDataNode()) {
final ArbilTemplate nodeTemplate = arbilDataNode.getParentDomNode().nodeTemplate;
if (nodeTemplate != null) {
containerNodeLabel = containerNodeLabel + " (" + nodeTemplate.getTemplateName() + ")";
} else {
containerNodeLabel = containerNodeLabel + java.util.ResourceBundle.getBundle("nl/mpi/arbil/localisation/Widgets").getString(" (LOADING)");
}
}
} else if (arbilDataNode.isSession()) {
containerNodeLabel = java.util.ResourceBundle.getBundle("nl/mpi/arbil/localisation/Widgets").getString("SESSION");
} else if (arbilDataNode.isCatalogue()) {
containerNodeLabel = java.util.ResourceBundle.getBundle("nl/mpi/arbil/localisation/Widgets").getString("CATALOGUE");
} else if (arbilDataNode.isCmdiMetaDataNode()) {
if (arbilDataNode.nodeTemplate == null) {
containerNodeLabel = java.util.ResourceBundle.getBundle("nl/mpi/arbil/localisation/Widgets").getString("CLARIN INSTANCE");
} else {
containerNodeLabel = arbilDataNode.nodeTemplate.getTemplateName();
}
}
if (!metaNodeMap.containsKey(containerNodeLabel)) {
metaNodeMap.put(containerNodeLabel, new HashSet<ArbilDataNode>());
}
metaNodeMap.get(containerNodeLabel).add(arbilDataNode);
}
final Map<String, ContainerNode> containerNodeMapUpdated = new HashMap<String, ContainerNode>();
for (Map.Entry<String, HashSet<ArbilDataNode>> filteredNodeEntry : metaNodeMap.entrySet()) {
if (containerNodeMapUpdated.containsKey(filteredNodeEntry.getKey())) {
containerNodeMapUpdated.get(filteredNodeEntry.getKey()).setChildNodes(filteredNodeEntry.getValue().toArray(new ArbilDataNode[]{}));
} else if (containerNodeMap.containsKey(filteredNodeEntry.getKey())) {
// use the entry from the
final ContainerNode foundEntry = containerNodeMap.get(filteredNodeEntry.getKey());
foundEntry.setChildNodes(filteredNodeEntry.getValue().toArray(new ArbilDataNode[]{}));
containerNodeMapUpdated.put(filteredNodeEntry.getKey(), foundEntry);
} else {
URI containerNodeUri = URI.create("ContainerNode");
ContainerNode containerNode = new ContainerNode(containerNodeUri, filteredNodeEntry.getKey(), null, filteredNodeEntry.getValue().toArray(new ArbilDataNode[]{}));
containerNodeMapUpdated.put(filteredNodeEntry.getKey(), containerNode);
}
}
return containerNodeMapUpdated;
}
/**
* @return the showHiddenFilesInTree
*/
@Override
public boolean isShowHiddenFilesInTree() {
return showHiddenFilesInTree;
}
@Override
public boolean isGroupFavouritesByType() {
return groupFavouritesByType;
}
protected abstract SessionStorage getSessionStorage();
/**
* @return the messageDialogHandler
*/
protected MessageDialogHandler getMessageDialogHandler() {
return messageDialogHandler;
}
public void setDataNodeLoader(DataNodeLoader dataNodeLoaderInstance) {
dataNodeLoader = dataNodeLoaderInstance;
}
/**
* @return the dataNodeLoader
*/
protected DataNodeLoader getDataNodeLoader() {
return dataNodeLoader;
}
} |
package org.intermine.bio.web.export;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.log4j.Logger;
import org.intermine.api.results.ResultElement;
import org.intermine.bio.io.gff3.GFF3Record;
import org.intermine.bio.ontology.SequenceOntology;
import org.intermine.bio.ontology.SequenceOntologyFactory;
import org.intermine.metadata.ClassDescriptor;
import org.intermine.model.bio.SequenceFeature;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.pathquery.Path;
import org.intermine.util.IntPresentSet;
import org.intermine.util.PropertiesUtil;
import org.intermine.web.logic.export.ExportException;
import org.intermine.web.logic.export.ExportHelper;
import org.intermine.web.logic.export.Exporter;
/**
* Exports LocatedSequenceFeature objects in GFF3 format.
* @author Kim Rutherford
* @author Jakub Kulaviak
*/
public class GFF3Exporter implements Exporter
{
private static final Logger LOG = Logger.getLogger(GFF3Exporter.class);
/**
* the fields we don't want to display as attributes
*/
public static final Set<String> GFF_FIELDS = Collections
.unmodifiableSet(new HashSet<String>(Arrays.asList("chromosome.primaryIdentifier",
"primaryIdentifier", "score")));
/**
* for the gff header, link to taxomony
*/
public static final String WORM_LINK =
"http:
/**
* for the gff header, link to taxomony
*/
public static final String FLY_LINK =
"http:
PrintWriter out;
private List<Integer> featureIndexes;
private Map<String, String> soClassNames;
private int writtenResultsCount = 0;
private boolean headerPrinted = false;
private IntPresentSet exportedIds = new IntPresentSet();
private List<String> attributesNames;
private String sourceName;
private Set<Integer> organisms;
// this one to store the lower case class names of soClassNames,
// for comparison with path elements classes.
private Set<String> cNames = new HashSet<String>();
private boolean makeUcscCompatible = false;
private List<Path> paths = Collections.emptyList();
/**
* Constructor.
* @param out output stream
* @param indexes index of column with exported sequence
* @param soClassNames mapping
* @param attributesNames names of attributes that are printed in record,
* they are names of columns in results table, they are in the same order
* as corresponding columns in results table
* @param sourceName name of Mine to put in GFF source column
* @param organisms taxon id of the organisms
* @param makeUcscCompatible true if chromosome ids should be prefixed by 'chr'
*/
public GFF3Exporter(PrintWriter out, List<Integer> indexes, Map<String, String> soClassNames,
List<String> attributesNames, String sourceName, Set<Integer> organisms,
boolean makeUcscCompatible) {
this.out = out;
this.featureIndexes = indexes;
this.soClassNames = soClassNames;
this.attributesNames = attributesNames;
this.sourceName = sourceName;
this.organisms = organisms;
this.makeUcscCompatible = makeUcscCompatible;
for (String s : soClassNames.keySet()) {
this.cNames.add(s.toLowerCase());
}
}
/**
* Constructor.
* @param out output stream
* @param indexes index of column with exported sequence
* @param soClassNames mapping
* @param attributesNames names of attributes that are printed in record,
* they are names of columns in results table, they are in the same order
* as corresponding columns in results table
* @param sourceName name of Mine to put in GFF source column
* @param organisms taxon id of the organisms
* @param makeUcscCompatible true if chromosome ids should be prefixed by 'chr'
*/
public GFF3Exporter(PrintWriter out, List<Integer> indexes, Map<String, String> soClassNames,
List<String> attributesNames, String sourceName, Set<Integer> organisms,
boolean makeUcscCompatible, List<Path> paths) {
this.out = out;
this.featureIndexes = indexes;
this.soClassNames = soClassNames;
this.attributesNames = attributesNames;
this.sourceName = sourceName;
this.organisms = organisms;
this.makeUcscCompatible = makeUcscCompatible;
this.paths = paths;
for (String s : soClassNames.keySet()) {
this.cNames.add(s.toLowerCase());
}
}
/**
* to read genome and project versions
* @return header further info about versions
*/
private String getHeaderParts() {
StringBuffer header = new StringBuffer();
Properties props = PropertiesUtil.getProperties();
if (organisms != null) {
for (Integer taxId : organisms) {
if (taxId == 7227) {
String fV = props.getProperty("genomeVersion.fly");
if (fV != null && fV.length() > 0) {
header.append("\n##species " + FLY_LINK);
header.append("\n##genome-build FlyBase r" + fV);
}
}
}
for (Integer taxId : organisms) {
if (taxId == 6239) {
String wV = props.getProperty("genomeVersion.worm");
if (wV != null && wV.length() > 0) {
header.append("\n##species " + WORM_LINK);
header.append("\n##genome-build WormBase ws" + wV);
}
}
}
// display only if organism is set
String mV = props.getProperty("project.releaseVersion");
if (mV != null && mV.length() > 0) {
header.append("\n#" + this.sourceName + " " + mV);
header.append("\n# #index-subfeatures 1");
}
}
return header.toString();
}
private String getHeader() {
return "##gff-version 3" + getHeaderParts();
}
/**
* {@inheritDoc}
*/
public void export(Iterator<? extends List<ResultElement>> resultIt,
Collection<Path> unionPathCollection, Collection<Path> newPathCollection) {
if (featureIndexes.size() == 0) {
throw new ExportException("No columns with sequence");
}
try {
// LOG.info("SOO:" + cNames.toString());
while (resultIt.hasNext()) {
List<ResultElement> row = resultIt.next();
exportRow(row, unionPathCollection, newPathCollection);
}
if (writtenResultsCount == 0) {
out.println("Nothing to export. Sequence features might miss some information, " +
"e.g. chromosome location, etc.");
}
out.flush();
} catch (Exception ex) {
throw new ExportException("Export failed", ex);
}
}
@Override
public void export(Iterator<? extends List<ResultElement>> resultIt) {
export(resultIt, paths, paths);
}
/* State for the exportRow method, to allow several rows to be merged. */
private Map<String, Integer> attributeVersions = new HashMap<String, Integer>();
private Integer lastLsfId = null;
private SequenceFeature lastLsf = null;
private Map<String, List<String>> attributes = null;
private Map<String, Set<Integer>> seenAttributes = new HashMap<String, Set<Integer>>();
private void exportRow(List<ResultElement> row,
Collection<Path> unionPathCollection, Collection<Path> newPathCollection)
throws ObjectStoreException, IllegalAccessException {
List<ResultElement> elWithObject = getResultElements(row);
if (elWithObject == null) {
return;
}
// In order to find the parents of a feature, e.g.
// Gene.interactions.interactingGenes.exons.transcripts, we assuse each
// feature's parents have unique path, e.g. transcript's parents paths
// are interactingGene.exons and interactingGene, but exon is not a
// parent of transcript, correct this by using SO.
Map<String, Integer> pathToIdMap = new HashMap<String, Integer>();
Map<Integer, List<String>> idToParentPathMap = new HashMap<Integer, List<String>>();
Map<Integer, ResultElement> idToResultElementMap = new HashMap<Integer, ResultElement>();
for (ResultElement el : elWithObject) {
if (el == null) {
continue;
}
List<Path> pathList = el.getPath().decomposePath();
// remove the last element in the list, it is a field
pathList.remove(pathList.size() - 1);
String lastClassPath = pathList.get(pathList.size() - 1).toStringNoConstraints();
Integer id = null;
try {
id = ((SequenceFeature) el.getObject()).getId();
} catch (Exception e) {
LOG.info("Object cannot be cast to SequenceFeature");
continue;
}
idToResultElementMap.put(id, el);
// from last sequence feature path to intermine id
pathToIdMap.put(lastClassPath, id);
// clsdList should have the same size as pathList
List<ClassDescriptor> clsdList = el.getPath()
.getElementClassDescriptors();
List<String> parentPaths = new LinkedList<String>();
for (int i = clsdList.size() - 2; i >= 0; i
if (SequenceFeature.class.isAssignableFrom(clsdList.get(i)
.getType())) {
parentPaths.add(pathList.get(i).toStringNoConstraints());
} else {
break;
}
}
idToParentPathMap.put(id, parentPaths);
}
SequenceOntology so = SequenceOntologyFactory.getSequenceOntology();
Path lastLsfPath = null;
for (ResultElement re : elWithObject) {
try {
SequenceFeature lsf = (SequenceFeature) re.getObject();
if (exportedIds.contains(lsf.getId()) && !(lsf.getId().equals(lastLsfId))) {
continue;
}
// processing parent for last cell
if ((lastLsfId != null) && !(lsf.getId().equals(lastLsfId))) {
processAttributes(row, unionPathCollection, newPathCollection, re.getPath());
processParent(pathToIdMap, idToParentPathMap, idToResultElementMap, so);
makeRecord();
}
if (lastLsfId == null) {
attributes = new LinkedHashMap<String, List<String>>();
}
// processAttributes should run here for collection attributes, e.g. Gene.pathways.name,
lastLsfId = lsf.getId();
lastLsf = lsf;
lastLsfPath = re.getPath();
} catch (Exception ex) {
LOG.error("Failed to write GFF3 file: " + ex);
continue;
}
}
// Export the last feature in the row
if (lastLsfId != null && !exportedIds.contains(lastLsfId)) {
processAttributes(row, unionPathCollection, newPathCollection, lastLsfPath);
processParent(pathToIdMap, idToParentPathMap, idToResultElementMap, so);
makeRecord();
}
}
private void processAttributes(List<ResultElement> row,
Collection<Path> unionPathCollection,
Collection<Path> newPathCollection, Path p) {
List<ResultElement> newRow = filterResultRow(row, unionPathCollection,
newPathCollection);
boolean isCollection = p.containsCollections();
for (int i = 0; i < newRow.size(); i++) {
ResultElement el = newRow.get(i);
if (el == null) {
continue;
}
// Disable collection export until further bug diagnose
if (isCollection || el.getPath().containsCollections()) {
continue;
}
// checks for attributes:
// if (isCollection && !el.getPath().containsCollections()) {
// // one is collection, the other is not: do not show
// continue;
// if (!isCollection && el.getPath().containsCollections()
// && soClassNames.containsKey(el.getType())) {
// // show attributes only if they are not linked to features
// // (they will be displayed with the relevant one, see below)
// continue;
// if (isCollection && el.getPath().containsCollections()) {
// // show only if of the same class
// Class<?> reType = p.getLastClassDescriptor().getType();
// Class<?> elType = el.getPath().getLastClassDescriptor().getType();
// if (!reType.isAssignableFrom(elType)) {
// continue;
if ("location".equalsIgnoreCase(el.getPath()
.getLastClassDescriptor().getUnqualifiedName())) {
// don't show locations (they are already displayed
// parts of the element)
continue;
}
if (el.getField() != null) {
String unqualName = el.getPath()
.getLastClassDescriptor().getUnqualifiedName();
String attributeName = trimAttribute(
attributesNames.get(i), unqualName);
checkAttribute(el, attributeName);
}
}
}
private void processParent(Map<String, Integer> pathToIdMap,
Map<Integer, List<String>> idToParentPathMap,
Map<Integer, ResultElement> idToResultElementMap, SequenceOntology so) {
Set<String> addPar = new LinkedHashSet<String>();
List<String> parentPaths = idToParentPathMap.get(lastLsfId);
if (!parentPaths.isEmpty()) {
for (String parentPath : parentPaths) {
Integer parentId = pathToIdMap.get(parentPath);
// parents not in view, e.g. Gene.transcripts.exons, gene or/and
// transcripts not display, thus Gene or/and Gene.transcripts
// will not be in pathToIdMap
if (parentId == null) {
continue;
}
SequenceFeature parent = (SequenceFeature) idToResultElementMap
.get(parentId).getObject();
String parentClassName = idToResultElementMap.get(parentId)
.getPath().getLastClassDescriptor()
.getUnqualifiedName().toLowerCase();
String featureClassName = idToResultElementMap.get(lastLsfId)
.getPath().getLastClassDescriptor()
.getUnqualifiedName().toLowerCase();
// reverse relationship, e.g. Gene.exons.transcripts, exon
// is not parent of transcript, use SO to validate the correct
// parents
// TODO Limitation - exon doesn't know transcript is a parent
// since the parents are found reversely from path string, but
// transcript is behind it
Set<String> parentsSOTerms = so.getAllPartOfs(featureClassName);
if (parentsSOTerms.contains(parentClassName)) {
addPar.add(parent.getPrimaryIdentifier());
}
}
}
if (addPar.size() > 0) {
attributes.put("Parent", new ArrayList<String>(addPar));
}
}
private String trimAttribute(String attribute, String unqualName) {
if (!attribute.contains(".")) {
return attribute;
}
// check if a feature attribute (display only name) or not (display all path)
if (cNames.contains(unqualName.toLowerCase())) {
String plainAttribute = attribute.substring(attribute.lastIndexOf('.') + 1);
// LOG.info("LCC: " +attribute+"->"+unqualName +"|"+ plainAttribute );
return plainAttribute;
}
// LOG.info("LCCno: " + attribute + "|" + unqualName);
return attribute;
}
private void makeRecord() {
GFF3Record gff3Record = GFF3Util.makeGFF3Record(lastLsf, soClassNames, sourceName,
attributes, makeUcscCompatible);
if (gff3Record != null) {
// have a chromosome ref and chromosomeLocation ref
if (!headerPrinted) {
out.println(getHeader());
headerPrinted = true;
}
out.println(gff3Record.toGFF3());
exportedIds.add(lastLsf.getId());
writtenResultsCount++;
}
lastLsfId = null;
attributeVersions.clear();
seenAttributes.clear();
}
/**
* @param el
* @param attributeName
*/
private void checkAttribute(ResultElement el, String attributeName) {
if (!GFF_FIELDS.contains(attributeName)) {
Set<Integer> seenAttributeValues = seenAttributes.get(attributeName);
if (seenAttributeValues == null) {
seenAttributeValues = new HashSet<Integer>();
seenAttributes.put(attributeName, seenAttributeValues);
}
if (!seenAttributeValues.contains(el.getId())) {
seenAttributeValues.add(el.getId());
Integer version = attributeVersions.get(attributeName);
if (version == null) {
version = new Integer(1);
attributes.put(attributeName, formatElementValue(el));
} else {
attributes.put(attributeName + version, formatElementValue(el));
}
attributeVersions.put(attributeName, new Integer(version.intValue() + 1));
}
}
}
private List<String> formatElementValue(ResultElement el) {
List<String> ret = new ArrayList<String>();
String s;
if (el == null) {
s = "-";
} else {
Object obj = el.getField();
if (obj == null) {
s = "-";
} else {
s = obj.toString();
}
}
ret.add(s);
return ret;
}
private List<ResultElement> getResultElements(List<ResultElement> row) {
List<ResultElement> els = new ArrayList<ResultElement>();
for (Integer index : featureIndexes) {
if (row.get(index) != null) {
els.add(row.get(index));
}
}
return els;
}
/**
* {@inheritDoc}
*/
public boolean canExport(List<Class<?>> clazzes) {
return canExportStatic(clazzes);
}
/* Method must have different name than canExport because canExport() method
* is inherited from Exporter interface */
/**
* @param clazzes classes of result row
* @return true if this exporter can export result composed of specified classes
*/
public static boolean canExportStatic(List<Class<?>> clazzes) {
return ExportHelper.getClassIndex(clazzes, SequenceFeature.class) >= 0;
}
/**
* {@inheritDoc}
*/
public int getWrittenResultsCount() {
return writtenResultsCount;
}
/**
* Remove the elements from row which are not in pathCollection
* @param row
* @param pathCollection
* @return
*/
private List<ResultElement> filterResultRow(List<ResultElement> row,
Collection<Path> unionPathCollection, Collection<Path> newPathCollection) {
List<ResultElement> newRow = new ArrayList<ResultElement>();
if (unionPathCollection == null && newPathCollection == null) {
return row;
}
if (unionPathCollection.containsAll(newPathCollection)) {
for (Path p : newPathCollection) {
ResultElement el = null;
if (!p.toString().endsWith(".id")) {
el = row.get(((List<Path>) unionPathCollection).indexOf(p));
}
newRow.add(el);
}
return newRow;
} else {
throw new RuntimeException("pathCollection: " + newPathCollection
+ ", elPathList contains pathCollection: "
+ unionPathCollection.containsAll(newPathCollection));
}
}
} |
package com.livefront.bridge;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import com.livefront.bridge.util.BundleUtil;
import com.livefront.bridge.wrapper.WrapperUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.WeakHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class BridgeDelegate {
private static final String TAG = BridgeDelegate.class.getName();
/**
* Time to wait (in milliseconds) while processing the parcel data when going into the
* background. This timeout simply serves as a safety precaution and is very unlikely to be
* reached under normal conditions.
*/
private static final long BACKGROUND_WAIT_TIMEOUT_MS = 5000;
private static final String KEY_BUNDLE = "bundle_%s";
private static final String KEY_UUID = "uuid_%s";
private static final String KEY_WRAPPED_VIEW_RESULT = "wrapped-view-result";
private int mActivityCount = 0;
private boolean mIsClearAllowed = false;
private boolean mIsConfigChange = false;
private boolean mIsFirstCreateCall = true;
private volatile CountDownLatch mPendingWriteTasksLatch = null;
private ExecutorService mExecutorService = Executors.newCachedThreadPool();
private List<Runnable> mPendingWriteTasks = new CopyOnWriteArrayList<>();
private Map<String, Bundle> mUuidBundleMap = new HashMap<>();
private Map<Object, String> mObjectUuidMap = new WeakHashMap<>();
private SavedStateHandler mSavedStateHandler;
private SharedPreferences mSharedPreferences;
private ViewSavedStateHandler mViewSavedStateHandler;
BridgeDelegate(@NonNull Context context,
@NonNull SavedStateHandler savedStateHandler,
@Nullable ViewSavedStateHandler viewSavedStateHandler) {
mSharedPreferences = context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
mSavedStateHandler = savedStateHandler;
mViewSavedStateHandler = viewSavedStateHandler;
registerForLifecycleEvents(context);
}
private void checkForViewSavedStateHandler() {
if (mViewSavedStateHandler == null) {
throw new IllegalStateException("To save and restore the state of Views, a "
+ "ViewSavedStateHandler must be specified when calling initialize.");
}
}
void clear(@NonNull Object target) {
if (!mIsClearAllowed) {
return;
}
String uuid = mObjectUuidMap.remove(target);
if (uuid == null) {
return;
}
clearDataForUuid(uuid);
}
void clearAll() {
mUuidBundleMap.clear();
mObjectUuidMap.clear();
mSharedPreferences.edit()
.clear()
.apply();
}
private void clearDataForUuid(@NonNull String uuid) {
mUuidBundleMap.remove(uuid);
clearDataFromDisk(uuid);
}
private void clearDataFromDisk(@NonNull String uuid) {
mSharedPreferences.edit()
.remove(getKeyForEncodedBundle(uuid))
.apply();
}
private String getKeyForEncodedBundle(@NonNull String uuid) {
return String.format(KEY_BUNDLE, uuid);
}
private String getKeyForUuid(@NonNull Object target) {
return String.format(KEY_UUID, target.getClass().getName());
}
private String getOrGenerateUuid(@NonNull Object target) {
String uuid = mObjectUuidMap.get(target);
if (uuid == null) {
uuid = UUID.randomUUID().toString();
mObjectUuidMap.put(target, uuid);
}
return uuid;
}
@Nullable
private Bundle getSavedBundleAndUnwrap(@NonNull String uuid) {
Bundle bundle = mUuidBundleMap.containsKey(uuid)
? mUuidBundleMap.get(uuid)
: readFromDisk(uuid);
if (bundle != null) {
WrapperUtils.unwrapOptimizedObjects(bundle);
}
clearDataForUuid(uuid);
return bundle;
}
@Nullable
private String getSavedUuid(@NonNull Object target,
@NonNull Bundle state) {
String uuid = mObjectUuidMap.containsKey(target)
? mObjectUuidMap.get(target)
: state.getString(getKeyForUuid(target), null);
if (uuid != null) {
mObjectUuidMap.put(target, uuid);
}
return uuid;
}
private boolean isAppInForeground() {
return mActivityCount > 0 || mIsConfigChange;
}
/**
* When the app is foregrounded, the given Bundle will be processed on a background thread and
* then persisted to disk. When the app is proceeding to the background, this method will wait
* for this task (and any others currently running in the background) to complete before
* proceeding in order to prevent the app from becoming fully "stopped" (and therefore killable
* by the OS before the data is saved).
*/
private void queueDiskWritingIfNecessary(@NonNull final String uuid,
@NonNull final Bundle bundle) {
Runnable runnable = new Runnable() {
@Override
public void run() {
// Process the Parcel and write the data to disk
writeToDisk(uuid, bundle);
// Remove this Runnable from the pending list
mPendingWriteTasks.remove(this);
// If the pending list is now empty, we can trigger the latch countdown to continue
if (mPendingWriteTasks.isEmpty() && mPendingWriteTasksLatch != null) {
mPendingWriteTasksLatch.countDown();
}
}
};
if (mPendingWriteTasksLatch == null) {
mPendingWriteTasksLatch = new CountDownLatch(1);
}
mPendingWriteTasks.add(runnable);
mExecutorService.execute(runnable);
if (isAppInForeground()) {
// Allow the data to be processed in the background.
return;
}
// Wait until (a) all pending tasks are complete or (b) we've reached the safety timeout.
// In the meantime we will block to avoid the app prematurely going into the "stopped"
// state.
try {
mPendingWriteTasksLatch.await(BACKGROUND_WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
// Interrupted for an unknown reason, simply proceed.
}
mPendingWriteTasksLatch = null;
}
@Nullable
private Bundle readFromDisk(@NonNull String uuid) {
String encodedString = mSharedPreferences.getString(getKeyForEncodedBundle(uuid), null);
if (encodedString == null) {
return null;
}
return BundleUtil.fromEncodedString(encodedString);
}
@SuppressLint("NewApi")
private void registerForLifecycleEvents(@NonNull Context context) {
((Application) context.getApplicationContext()).registerActivityLifecycleCallbacks(
new ActivityLifecycleCallbacksAdapter() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
mIsClearAllowed = true;
mIsConfigChange = false;
// Make sure we clear all data after creating the first Activity if it does
// does not have a saved stated Bundle. (During state restoration, the
// first Activity will always have a non-null saved state Bundle.)
if (!mIsFirstCreateCall) {
return;
}
mIsFirstCreateCall = false;
if (savedInstanceState == null) {
mSharedPreferences.edit()
.clear()
.apply();
}
}
@Override
public void onActivityDestroyed(Activity activity) {
// Don't allow clearing during known configuration changes (and other
// events unrelated to calling "finish()".)
mIsClearAllowed = activity.isFinishing();
}
@Override
public void onActivityPaused(Activity activity) {
// As soon as we have an indication that we are changing configurations for
// some Activity we'll remain in the "config change" state until the next
// time an Activity is created. We can ignore certain things (like
// processing the Bundle and writing it to disk on a background thread)
// during this period.
mIsConfigChange = activity.isChangingConfigurations();
}
@Override
public void onActivityStarted(Activity activity) {
mActivityCount++;
}
@Override
public void onActivityStopped(Activity activity) {
mActivityCount
}
}
);
}
void restoreInstanceState(@NonNull Object target, @Nullable Bundle state) {
if (state == null) {
return;
}
String uuid = getSavedUuid(target, state);
if (uuid == null) {
return;
}
Bundle bundle = getSavedBundleAndUnwrap(uuid);
if (bundle == null) {
return;
}
mSavedStateHandler.restoreInstanceState(target, bundle);
}
@Nullable
<T extends View> Parcelable restoreInstanceState(@NonNull T target,
@Nullable Parcelable state) {
checkForViewSavedStateHandler();
if (state == null) {
return null;
}
String uuid = getSavedUuid(target, (Bundle) state);
if (uuid == null) {
return null;
}
Bundle bundle = getSavedBundleAndUnwrap(uuid);
if (bundle == null) {
return null;
}
// Figure out if we had to wrap the original result coming from the ViewSavedStateHandler
// in our own Bundle. If so, grab the actual result. Otherwise the current Bundle *is* the
// result.
Parcelable originalResult = bundle.containsKey(KEY_WRAPPED_VIEW_RESULT)
? bundle.getParcelable(KEY_WRAPPED_VIEW_RESULT)
: bundle;
return mViewSavedStateHandler.restoreInstanceState(target, originalResult);
}
void saveInstanceState(@NonNull Object target, @NonNull Bundle state) {
String uuid = getOrGenerateUuid(target);
state.putString(getKeyForUuid(target), uuid);
Bundle bundle = new Bundle();
mSavedStateHandler.saveInstanceState(target, bundle);
if (bundle.isEmpty()) {
// Don't bother saving empty bundles
return;
}
saveToMemoryAndDiskIfNecessary(uuid, bundle);
}
@NonNull
<T extends View> Parcelable saveInstanceState(@NonNull T target,
@Nullable Parcelable parentState) {
checkForViewSavedStateHandler();
String uuid = getOrGenerateUuid(target);
Bundle outBundle = new Bundle();
outBundle.putString(getKeyForUuid(target), uuid);
Parcelable result = mViewSavedStateHandler.saveInstanceState(target, parentState);
Bundle saveBundle;
if (result instanceof Bundle) {
// The result is already a Bundle, so we can deal with it directly.
saveBundle = (Bundle) result;
} else {
// The result is not a Bundle so we'll wrap it in one with a special key.
saveBundle = new Bundle();
saveBundle.putParcelable(KEY_WRAPPED_VIEW_RESULT, result);
}
if (saveBundle.isEmpty()) {
// Don't bother saving empty bundles
return outBundle;
}
saveToMemoryAndDiskIfNecessary(uuid, saveBundle);
return outBundle;
}
private void saveToMemoryAndDiskIfNecessary(@NonNull String uuid,
@NonNull Bundle bundle) {
WrapperUtils.wrapOptimizedObjects(bundle);
mUuidBundleMap.put(uuid, bundle);
queueDiskWritingIfNecessary(uuid, bundle);
}
private void writeToDisk(@NonNull String uuid,
@NonNull Bundle bundle) {
String encodedString = BundleUtil.toEncodedString(bundle);
mSharedPreferences.edit()
.putString(getKeyForEncodedBundle(uuid), encodedString)
.apply();
}
} |
package org.ligi.snackengage;
public class Dependencies {
public static class Android {
public static final String APPLICATION_ID = "org.ligi.snackengage";
public static final String BUILD_TOOLS_VERSION = "29.0.3";
public static final int MIN_SDK_VERSION = 14;
public static final int COMPILE_SDK_VERSION = 28;
public static final int TARGET_SDK_VERSION = 28;
public static final int VERSION_CODE = 24;
public static final String VERSION_NAME = "0.24";
}
public static class GradlePlugins {
public static final String ANDROID = "com.android.tools.build:gradle:4.0.1";
public static final String MAVEN = "com.github.dcendents:android-maven-gradle-plugin:2.1";
public static final String VERSIONS = "com.github.ben-manes:gradle-versions-plugin:0.29.0";
}
public static class Libs {
public static final String ANNOTATION = "androidx.annotation:annotation:1.1.0";
public static final String APPCOMPAT = "androidx.appcompat:appcompat:1.1.0";
public static final String ASSERTJ_ANDROID = "com.squareup.assertj:assertj-android:1.2.0";
public static final String JUNIT = "junit:junit:4.13";
public static final String MATERIAL = "com.google.android.material:material:1.1.0";
public static final String MOCKITO = "org.mockito:mockito-core:3.4.0";
}
} |
package camelinaction;
import org.apache.camel.builder.RouteBuilder;
import org.wildfly.extension.camel.CamelAware;
import camelinaction.inventory.UpdateInventoryInput;
@CamelAware
public class InventoryRoute extends RouteBuilder {
@Override
public void configure() throws Exception {
// this is the file route which is started 2nd last
from("file://target/inventory/updates")
.routeId("file").startupOrder(2)
.split(body().tokenize("\n"))
.convertBodyTo(UpdateInventoryInput.class)
.to("direct:update");
// this is the shared route which then must be started first
from("direct:update")
.routeId("update").startupOrder(1)
.to("bean:inventoryService?method=updateInventory");
}
} |
package ru.job4j.calculator;
public class Calculator {
private double result;
void add(double first, double second) {
this.result = first + second;
}
void sub(double first, double second) {
this.result = first - second;
}
void div(double first, double second) {
this.result = first / second;
}
void mult(double first, double second) {
this.result = first * second;
}
public double getResult() {
return this.result;
}
} |
package com.map;
import static com.map.WaypointList.*;
import com.Context;
import com.Dashboard;
import com.graph.Graph;
import com.map.coordinateListener;
import com.map.Dot;
import com.serial.*;
import com.ui.DataWindow;
import com.ui.LogViewer;
import com.ui.ninePatch.NinePatchPanel;
import com.ui.SystemConfigWindow;
import com.ui.Theme;
import com.xml;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.util.*;
import java.util.logging.*;
import javax.imageio.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.xml.stream.XMLStreamException;
class WaypointPanel extends NinePatchPanel {
protected static final int MOVE_STEP = 32;
protected static final int BDR_SIZE = 25;
protected static final String NO_WAYPOINT_MSG = "N / A";
private Context context;
private MapPanel map;
private WaypointList waypoints;
private javax.swing.Timer zoomTimer;
TelemField latitude;
TelemField longitude;
TelemField altitude;
JLabel waypointIndexDisplay;
private class TelemField extends JTextField{
float lastSetValue = Float.NaN;
@Override
public void setText(String newString){
super.setText(newString);
lastSetValue = Float.NaN;
}
void update(float newValue){
/**
* editable float fields will get their cursor reset unless
* updates from possible waypointlistener events only change
* the text when the dot moves
*/
if(newValue != lastSetValue){
setText(Float.toString(newValue));
lastSetValue = newValue;
}
}
}
public WaypointPanel(Context cxt, MapPanel mapPanel) {
super(cxt.theme.panelPatch);
map = mapPanel;
context = cxt;
makeActions();
waypoints = context.getWaypointList();
setOpaque(false);
LayoutManager layout = new BoxLayout(this, BoxLayout.PAGE_AXIS);
setLayout(layout);
setBorder(BorderFactory.createEmptyBorder(BDR_SIZE,BDR_SIZE,BDR_SIZE,BDR_SIZE));
buildPanel();
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
//do nothing here to prevent clicks from falling through
//to the map panel in the background
}
});
waypoints.addListener(new WaypointListener(){
@Override public void unusedEvent() { updateDisplay(); }
});
updateDisplay();
}
private void makeActions(){
nextTileServer = new AbstractAction() {
java.util.List<String> serverLabels
= new LinkedList<String>(map.tileServerNames());
{ updateLabel();
}
private void updateLabel(){
putValue(Action.NAME, serverLabels.get(0));
}
public void actionPerformed(ActionEvent e) {
// cycle current server to the back of the list
String server = serverLabels.get(0);
serverLabels.remove(0);
serverLabels.add(server);
// switch the map's server
map.switchToServer(server);
updateLabel();
map.repaint();
}
};
}
/**
* Update the selected dot text field displays
*/
public void updateDisplay() {
int selectedWaypoint = waypoints.getSelected();
ExtendedWaypoint w = waypoints.get(selectedWaypoint);
Dot dot = w.dot();
String indexField = (selectedWaypoint+1) + " / " + waypoints.size();
// special dots that don't represent waypoints show names instead of index
switch(w.type()){
case ROVER: indexField = "Robot"; break;
case HOME: indexField = "Home "; break;
}
waypointIndexDisplay.setText(indexField);
latitude.update( (float)dot.getLatitude() );
longitude.update( (float)dot.getLongitude() );
altitude.update( (float)fixedToDouble(dot.getAltitude()) );
latitude.setForeground(Color.BLACK);
longitude.setForeground(Color.BLACK);
altitude.setForeground(Color.BLACK);
if(selectedWaypoint < 0){
latitude.setEditable(false);
longitude.setEditable(false);
altitude.setEditable(false);
} else {
latitude.setEditable(true);
longitude.setEditable(true);
altitude.setEditable(true);
}
}
private void buildPanel() {
final Theme theme = context.theme;
final Dimension space = new Dimension(0,5);
final Dimension buttonSize = new Dimension(140, 25);
//make all the buttons
JButton tileButton = theme.makeButton(nextTileServer);
JButton dataPanel = theme.makeButton(openDataPanel);
JButton graphButton = theme.makeButton(buildGraph);
JButton reTarget = theme.makeButton(reTargetRover);
JButton looping = theme.makeButton(toggleLooping);
JButton config = theme.makeButton(openConfigWindow);
JButton logPanelButton = theme.makeButton(logPanelAction);
JButton clearWaypoints = theme.makeButton(clearWaypointsAction);
JButton zoomInButton = theme.makeButton(zoomInAction);
zoomInButton.addMouseListener(zoomInMouseAdapter);
JButton zoomOutButton = theme.makeButton(zoomOutAction);
zoomOutButton.addMouseListener(zoomOutMouseAdapter);
JButton zoomFullButton = theme.makeButton(zoomFullAction);
JComponent[] format = new JComponent[] {
tileButton, dataPanel, graphButton,
reTarget, looping, config, logPanelButton, clearWaypoints
};
for(JComponent jc : format) {
jc.setAlignmentX(Component.CENTER_ALIGNMENT);
jc.setMaximumSize(buttonSize);
}
//make zoom button panel
JPanel zoom = new JPanel(new FlowLayout());
zoom.setOpaque(false);
zoom.add(zoomInButton);
zoom.add(zoomFullButton);
zoom.add(zoomOutButton);
//add selectedWaypoint flow layout
JPanel selector = new JPanel(new BorderLayout());
selector.setOpaque(false);
waypointIndexDisplay = new JLabel(NO_WAYPOINT_MSG);
waypointIndexDisplay.setHorizontalAlignment(SwingConstants.CENTER);
selector.add(theme.makeButton(previousWaypoint), BorderLayout.LINE_START);
selector.add(waypointIndexDisplay, BorderLayout.CENTER);
selector.add(theme.makeButton(nextWaypoint), BorderLayout.LINE_END);
//Make edit boxes
class EditBoxSpec {
public final JTextField ref;
public final String label;
public EditBoxSpec(JTextField ref, String label) {
this.ref = ref;
this.label = label;
}
}
ArrayList<EditBoxSpec> editorBoxes = new ArrayList<EditBoxSpec>();
latitude = new TelemField();
longitude = new TelemField();
altitude = new TelemField();
editorBoxes.add(new EditBoxSpec(latitude , "Lat: "));
editorBoxes.add(new EditBoxSpec(longitude, "Lng: "));
editorBoxes.add(new EditBoxSpec(altitude , context.getResource("waypointExtra")+" "));
ArrayList<JPanel> editorPanels = new ArrayList<JPanel>();
for(EditBoxSpec box : editorBoxes) {
//construct panel
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
panel.setOpaque(false);
//add label box
JLabel label = new JLabel(box.label);
label.setFont(context.theme.text);
panel.add(label);
//add textField
JTextField tf = box.ref;
tf.setBorder(BorderFactory.createLineBorder(Color.gray));
panel.add(tf);
//Setup text field listener
coordinateListener listener = new coordinateListener(tf, this);
tf.getDocument().addDocumentListener(listener);
tf.addActionListener(listener);
//add to layout
editorPanels.add(panel);
}
//rows, cols, hgap, vgap
JPanel waypointOptions = new JPanel(new GridLayout(2,2,5,5));
waypointOptions.setOpaque(false);
waypointOptions.add(theme.makeButton(newWaypoint));
waypointOptions.add(theme.makeButton(interpretLocationAction));
waypointOptions.add(theme.makeButton(saveWaypoints));
waypointOptions.add(theme.makeButton(loadWaypoints));
add(config);
add(Box.createRigidArea(space));
add(tileButton);
add(zoom);
add(dataPanel);
add(Box.createRigidArea(space));
add(graphButton);
add(Box.createRigidArea(space));
add(logPanelButton);
add(Box.createRigidArea(space));
add(new JSeparator(SwingConstants.HORIZONTAL));
add(Box.createRigidArea(space));
add(clearWaypoints);
add(Box.createRigidArea(space));
add(selector);
add(Box.createRigidArea(space));
for(JPanel panel : editorPanels) {
add(panel);
}
add(Box.createRigidArea(space));
add(waypointOptions);
add(Box.createRigidArea(space));
add(reTarget);
add(Box.createRigidArea(space));
add(looping);
}
private double fixedToDouble(int i) {
return ((double)(i&0xffff))/((double)Serial.U16_FIXED_POINT);
}
private int doubleToFixed(double i) {
return (int)(i*Serial.U16_FIXED_POINT);
}
public void interpretLocationEntry() {
try {
int selectedWaypoint = waypoints.getSelected();
if(selectedWaypoint < 0) // rover or home location selected
return;
Double newLatitude = Double.parseDouble(latitude.getText());
Double newLongitude = Double.parseDouble(longitude.getText());
Double tmpAltitude = Double.parseDouble(altitude.getText());
int newAltitude = doubleToFixed(tmpAltitude);
Point.Double newPosition = new Point.Double(newLongitude, newLatitude);
if((newAltitude&0xffff) == newAltitude) {
waypoints.set(new Dot(newPosition, (short)newAltitude), selectedWaypoint);
//set to display reconverted value
altitude.setText(fixedToDouble(newAltitude)+"");
} else {
Dot newloc = waypoints.get(selectedWaypoint).dot();
newloc.setLocation(newPosition);
waypoints.set(newloc, selectedWaypoint);
}
} catch (NumberFormatException e) {}
}
private Action logPanelAction = new AbstractAction() {
LogViewer lv;
Logger log;
{
lv = new LogViewer();
log = Logger.getLogger("d");
log.addHandler(lv.getHandler());
putValue(Action.NAME, "Event Log");
}
public void actionPerformed(ActionEvent e) {
lv.setVisible(true);
}
};
private Action zoomInAction = new AbstractAction() {
{
String text = "+";
putValue(Action.NAME, text);
putValue(Action.SHORT_DESCRIPTION, text);
}
public void actionPerformed(ActionEvent e) {
//Do nothing, input handled by zoomInMouseAdapter
}
};
private MouseAdapter zoomInMouseAdapter = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent me) {
map.zoomIn(new Point(map.getWidth() / 2, map.getHeight() / 2));
if(zoomTimer == null) {
zoomTimer = new javax.swing.Timer(250, zoomInTimerAction);
zoomTimer.start();
}
}
@Override
public void mouseReleased(MouseEvent me) {
if(zoomTimer != null) {
zoomTimer.stop();
zoomTimer = null;
}
}
};
private Action zoomInTimerAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
map.zoomIn(new Point(map.getWidth() / 2, map.getHeight() / 2));
}
};
private Action zoomOutAction = new AbstractAction() {
{
String text = "-";
putValue(Action.NAME, text);
putValue(Action.SHORT_DESCRIPTION, text);
}
public void actionPerformed(ActionEvent e) {
//Do nothing, input handled by zoomOutMouseAdapter
}
};
private MouseAdapter zoomOutMouseAdapter = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent me) {
map.zoomOut(new Point(map.getWidth() / 2, map.getHeight() / 2));
if(zoomTimer == null) {
zoomTimer = new javax.swing.Timer(250, zoomOutTimerAction);
zoomTimer.start();
}
}
@Override
public void mouseReleased(MouseEvent me) {
if(zoomTimer != null) {
zoomTimer.stop();
zoomTimer = null;
}
}
};
private Action zoomOutTimerAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
map.zoomOut(new Point(map.getWidth() / 2, map.getHeight() / 2));
}
};
private Action zoomFullAction = new AbstractAction() {
{
String text = "Full";
putValue(Action.NAME, text);
putValue(Action.SHORT_DESCRIPTION, text);
}
public void actionPerformed(ActionEvent e) {
map.zoomFull(new Point(map.getWidth() / 2, map.getHeight() / 2));
}
};
private Action nextTileServer;
private Action toggleLooping = new AbstractAction() {
{
String text = "Looping On";
putValue(Action.NAME, text);
putValue(Action.SHORT_DESCRIPTION, text);
}
public void actionPerformed(ActionEvent e) {
waypoints.setLooped(!waypoints.getLooped());
putValue(Action.NAME,
(waypoints.getLooped())? "Looping Off" : "Looping On");
}
};
private Action previousWaypoint = new AbstractAction() {
{
String text = "<";
putValue(Action.NAME, text);
putValue(Action.SHORT_DESCRIPTION, text);
}
public void actionPerformed(ActionEvent e) {
waypoints.setSelected(waypoints.getSelected()-1);
updateDisplay();
map.repaint();
}
};
private Action nextWaypoint = new AbstractAction() {
{
String text = ">";
putValue(Action.NAME, text);
putValue(Action.SHORT_DESCRIPTION, text);
}
public void actionPerformed(ActionEvent e) {
waypoints.setSelected(waypoints.getSelected()+1);
updateDisplay();
map.repaint();
}
};
private Action saveWaypoints = new AbstractAction() {
{
String text = "Save";
putValue(Action.NAME, text);
putValue(Action.SHORT_DESCRIPTION, text);
}
public void actionPerformed(ActionEvent e) {
try {
xml.writeXML(context);
} catch (XMLStreamException ex) {
System.err.println(ex.getMessage());
}
}
};
private Action loadWaypoints = new AbstractAction() {
{
String text = "Load";
putValue(Action.NAME, text);
putValue(Action.SHORT_DESCRIPTION, text);
}
public void actionPerformed(ActionEvent e) {
try {
xml.readXML(context);
} catch (XMLStreamException ex) {
System.err.println(ex.getMessage());
}
}
};
private Action interpretLocationAction = new AbstractAction() {
{
String text = "Enter";
putValue(Action.NAME, text);
}
public void actionPerformed(ActionEvent e) {
interpretLocationEntry();
}
};
private Action reTargetRover = new AbstractAction() {
{
String text = "Set Target";
putValue(Action.NAME, text);
}
public void actionPerformed(ActionEvent e) {
waypoints.setTarget(waypoints.getSelected());
}
};
private Action newWaypoint = new AbstractAction() {
{
String text = "New";
putValue(Action.NAME, text);
}
public void actionPerformed(ActionEvent e) {
int selectedWaypoint = waypoints.getSelected();
waypoints.add(
new Dot(waypoints.get(selectedWaypoint).dot()), selectedWaypoint);
}
};
private Action clearWaypointsAction = new AbstractAction() {
{
String text = "Clear Waypoints";
putValue(Action.NAME, text);
}
public void actionPerformed(ActionEvent e) {
// label the clear event as coming from the rover
// so we don't send waypoint update messages
// for every individual waypoint
// Instead we send an explicit clear message to the rover afterwards
waypoints.clear(WaypointListener.Source.REMOTE);
if (context.sender != null) {
context.sender.sendWaypointList();
}
}
};
private Action openDataPanel = new AbstractAction() {
{
String text = "Telemetry";
putValue(Action.NAME, text);
}
public void actionPerformed(ActionEvent e) {
final DataWindow window = new DataWindow(context);
}
};
private Action openConfigWindow = new AbstractAction() {
{
String text = "Configuration";
putValue(Action.NAME, text);
}
public void actionPerformed(ActionEvent e) {
final SystemConfigWindow window = new SystemConfigWindow(context);
}
};
private Action buildGraph = new AbstractAction() {
{
String text = "Graph";
putValue(Action.NAME, text);
}
public void actionPerformed(ActionEvent e) {
Graph graph = new Graph(context.getTelemetryDataSources(), false);
graph.setPreferredSize(new Dimension(500, 300));
JFrame gFrame = new JFrame("Telemetry Graph");
gFrame.add(graph);
gFrame.pack();
gFrame.setVisible(true);
}
};
} |
package jmetest.effects;
import java.util.logging.Level;
import com.jme.app.SimpleGame;
import com.jme.effects.Tint;
import com.jme.image.Texture;
import com.jme.input.FirstPersonController;
import com.jme.input.InputController;
import com.jme.input.KeyBindingManager;
import com.jme.input.KeyInput;
import com.jme.math.Vector3f;
import com.jme.renderer.Camera;
import com.jme.renderer.ColorRGBA;
import com.jme.scene.Box;
import com.jme.scene.Node;
import com.jme.scene.Text;
import com.jme.scene.TriMesh;
import com.jme.scene.state.AlphaState;
import com.jme.scene.state.TextureState;
import com.jme.scene.state.ZBufferState;
import com.jme.system.DisplaySystem;
import com.jme.system.JmeException;
import com.jme.util.LoggingSystem;
import com.jme.util.TextureManager;
import com.jme.util.Timer;
/**
* <code>TestTint</code>
*
* @author Ahmed
* @version $Id: TestTint.java,v 1.3 2004-03-03 17:38:10 darkprophet Exp $
*/
public class TestTint extends SimpleGame {
private Camera cam;
private Node tintNode, scene;
private InputController input;
private Timer timer;
private Tint tint;
private TriMesh box;
private float alpha;
private Text instructions;
protected void update(float interpolation) {
timer.update();
input.update(timer.getTimePerFrame() * 35);
if (KeyBindingManager
.getKeyBindingManager()
.isValidCommand("Alpha+")) {
alpha += 0.01f;
tint.getTintColor().a = alpha;
} else if (
KeyBindingManager.getKeyBindingManager().isValidCommand(
"Alpha-")) {
alpha -= 0.01f;
tint.getTintColor().a = alpha;
}
scene.updateWorldData(timer.getTimePerFrame() * 10);
tintNode.updateWorldData(timer.getTimePerFrame() * 10);
}
protected void render(float interpolation) {
display.getRenderer().clearBuffers();
display.getRenderer().draw(scene);
display.getRenderer().draw(tintNode);
}
protected void initSystem() {
try {
display = DisplaySystem.getDisplaySystem(properties.getRenderer());
display.createWindow(
properties.getWidth(),
properties.getHeight(),
properties.getDepth(),
properties.getFreq(),
properties.getFullscreen());
display.setTitle("Tint Test");
cam =
display.getRenderer().getCamera(
properties.getWidth(),
properties.getHeight());
} catch (JmeException e) {
e.printStackTrace();
System.exit(1);
}
display.getRenderer().setBackgroundColor(new ColorRGBA(0, 0, 0, 0));
cam.setFrustum(1f, 1000f, -0.55f, 0.55f, 0.4125f, -0.4125f);
Vector3f loc = new Vector3f(0, 0, 3);
Vector3f left = new Vector3f(-1, 0, 0);
Vector3f up = new Vector3f(0, 1, 0);
Vector3f dir = new Vector3f(0, 0, -1);
cam.setFrame(loc, left, up, dir);
display.getRenderer().setCamera(cam);
input = new FirstPersonController(this, cam, properties.getRenderer());
timer = Timer.getTimer(properties.getRenderer());
input.getKeyBindingManager().set("Alpha+", KeyInput.KEY_PERIOD);
input.getKeyBindingManager().set("Alpha-", KeyInput.KEY_COMMA);
}
protected void initGame() {
tintNode = new Node("tintNode");
scene = new Node("scene");
alpha = 0.8f;
AlphaState as1 = display.getRenderer().getAlphaState();
as1.setBlendEnabled(true);
as1.setSrcFunction(AlphaState.SB_SRC_ALPHA);
as1.setDstFunction(AlphaState.DB_ONE);
as1.setTestEnabled(true);
as1.setTestFunction(AlphaState.TF_GREATER);
as1.setEnabled(true);
TextureState ts1 = display.getRenderer().getTextureState();
ts1.setEnabled(true);
ts1.setTexture(
TextureManager.loadTexture(
TestTint.class.getClassLoader().getResource(
"jmetest/data/images/Monkey.jpg"),
Texture.MM_LINEAR,
Texture.FM_LINEAR,
true));
TextureState font = display.getRenderer().getTextureState();
font.setEnabled(true);
font.setTexture(
TextureManager.loadTexture(
TestTint.class.getClassLoader().getResource(
"jmetest/data/font/font.png"),
Texture.MM_LINEAR,
Texture.FM_LINEAR,
true));
ZBufferState zEnabled = display.getRenderer().getZBufferState();
zEnabled.setEnabled(true);
Vector3f min = new Vector3f(-0.1f, -0.1f, -0.1f);
Vector3f max = new Vector3f(0.1f, 0.1f, 0.1f);
box = new Box("Box", min.mult(5), max.mult(5));
box.setRenderState(ts1);
box.setLocalTranslation(new Vector3f(0, 0, 0));
tint = new Tint("tint", new ColorRGBA(1, 0, 0, alpha));
tint.setRenderState(as1);
instructions =
new Text("Instructions", "WASD to move, < and > to change alpha");
instructions.setRenderState(font);
instructions.setRenderState(as1);
scene.setRenderState(zEnabled);
scene.attachChild(box);
scene.attachChild(instructions);
tintNode.attachChild(tint);
}
protected void reinit() {
}
protected void cleanup() {
}
public static void main(String[] args) {
LoggingSystem.getLogger().setLevel(Level.ALL);
TestTint app = new TestTint();
app.setDialogBehaviour(SimpleGame.ALWAYS_SHOW_PROPS_DIALOG);
app.start();
}
} |
package pl.rafalmag.ev3.clock;
import java.util.concurrent.TimeUnit;
import lejos.hardware.Button;
import lejos.hardware.Sound;
import lejos.hardware.lcd.LCD;
import lejos.hardware.motor.EV3LargeRegulatedMotor;
import lejos.hardware.motor.EV3MediumRegulatedMotor;
import lejos.hardware.port.MotorPort;
import lejos.internal.ev3.EV3LCDManager;
import lejos.internal.ev3.EV3LCDManager.LCDLayer;
import lejos.robotics.MirrorMotor;
import lejos.utility.TextMenu;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.rafalmag.ev3.RuntimeInterruptedException;
import pl.rafalmag.ev3.Time;
import pl.rafalmag.systemtime.SystemTime;
@SuppressWarnings("restriction")
public class MainWithMenu {
private static final Logger log = LoggerFactory
.getLogger(MainWithMenu.class);
public static void main(String[] args) {
log.info("Initializing...");
LCD.clear();
disableOtherLogLayers();
LCD.clear();
Button.setKeyClickVolume(1);
SystemTime.initSysTime();
ClockProperties clockProperties = ClockProperties.getInstance();
AnalogClock clock = new AnalogClock(clockProperties, new TickPeriod(5,
TimeUnit.SECONDS), new Time(0, 20),
MirrorMotor
.invertMotor(new EV3MediumRegulatedMotor(MotorPort.A)),
MirrorMotor
.invertMotor(new EV3LargeRegulatedMotor(MotorPort.B)));
MainWithMenu mainWithMenu = new MainWithMenu(clock);
log.info("Ready");
Sound.beep();
mainWithMenu.start();
}
private static void disableOtherLogLayers() {
for (LCDLayer layer : EV3LCDManager.getLocalLCDManager().getLayers()) {
if (!layer.getName().equalsIgnoreCase("LCD")) {
layer.setVisible(false);
}
}
}
private final AnalogClock clock;
public MainWithMenu(AnalogClock clock) {
this.clock = clock;
}
public void start() {
addRunningLeds();
addShutdownHook();
clockSettingMenu();
LCD.clear();
mainMenuLoop();
LCD.clear();
stopApp();
}
private void addRunningLeds() {
clock.getClockRunning().addObserver(new ClockRunningObserver() {
@Override
public void update(ClockRunning clockRunning, Boolean running) {
if (running) {
Button.LEDPattern(1); // green
} else {
Button.LEDPattern(0); // blank
}
}
});
}
private void addShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
stopApp();
}
}, "Shutdown hook"));
}
public void clockSettingMenu() {
Time time = clock.getTime();
LCD.drawString("Clock setting", 0, 0);
TextMenu textMenu = new TextMenu(ClockSettingMenu.getNames(), 2);
int lastSelected = 0;
while (true) {
textMenu.setTitle(time.toString());
// blocking here
lastSelected = textMenu.select(lastSelected);
if (lastSelected < 0) { // esc
clock.setTime(time);
return;
}
ClockSettingMenu clockSettingMenu = ClockSettingMenu.values()[lastSelected];
switch (clockSettingMenu) {
case HOUR_MINUS:
time = time.minusHour();
break;
case HOUR_PLUS:
time = time.plusHour();
break;
case MINUTE_MINUS:
time = time.minusMinute();
break;
case MINUTE_PLUS:
time = time.plusMinute();
break;
case OK:
clock.setTime(time);
return;
default:
throw new IllegalStateException("Not supported enum value = "
+ clockSettingMenu);
}
}
}
public void mainMenuLoop() {
LCD.drawString("Clock setting", 0, 0);
TextMenu textMenu = new TextMenu(MainMenu.getNames(), 2);
int lastSelected = 0;
while (true) {
textMenu.setTitle(clock.getTime().toString());
// blocking here
lastSelected = textMenu.select(lastSelected);
if (lastSelected < 0) { // esc
return;
}
MainMenu mainMenu = MainMenu.values()[lastSelected];
switch (mainMenu) {
case AUTO:
clock.autoSet(SystemTime.getDate());
break;
case BACKWARD:
clock.fastBackward();
waitTillEnterIsDown();
clock.stop();
break;
case FORWARD:
clock.fastForward();
waitTillEnterIsDown();
clock.stop();
break;
case TOGGLE_RUN:
clock.toggleStart();
// TODO submenu with digital time ?
break;
case HAND_SETTINGS:
LCD.clear();
clockSettingMenu();
LCD.clear();
break;
default:
throw new IllegalStateException("Not supported enum value = "
+ mainMenu);
}
}
}
private void waitTillEnterIsDown() {
while (Button.ENTER.isDown()) {
try {
Thread.sleep(10); // 10 ms
} catch (InterruptedException e) {
throw new RuntimeInterruptedException(e);
}
}
}
private void stopApp() {
clock.stop();
Button.LEDPattern(0);
LCD.clear();
LCD.drawString("Bye!", 0, 5);
log.info("bye");
}
} |
package tk.wurst_client.features.mods;
import net.minecraft.entity.Entity;
import tk.wurst_client.events.listeners.UpdateListener;
import tk.wurst_client.features.Feature;
import tk.wurst_client.settings.CheckboxSetting;
import tk.wurst_client.settings.SliderSetting;
import tk.wurst_client.settings.SliderSetting.ValueDisplay;
import tk.wurst_client.utils.EntityUtils;
import tk.wurst_client.utils.EntityUtils.TargetSettings;
import tk.wurst_client.utils.PlayerUtils;
import tk.wurst_client.utils.RotationUtils;
@Mod.Info(
description = "Slower Killaura that bypasses any AntiCheat plugins.\n"
+ "Not required on normal NoCheat+ servers!",
name = "KillauraLegit",
tags = "LegitAura, killaura legit, kill aura legit, legit aura",
help = "Mods/KillauraLegit")
@Mod.Bypasses
public class KillauraLegitMod extends Mod implements UpdateListener
{
public CheckboxSetting useKillaura =
new CheckboxSetting("Use Killaura settings", true)
{
@Override
public void update()
{
if(isChecked())
{
KillauraMod killaura = wurst.mods.killauraMod;
useCooldown.lock(killaura.useCooldown.isChecked());
speed.lockToValue(killaura.speed.getValue());
range.lockToValue(killaura.range.getValue());
fov.lockToValue(killaura.fov.getValue());
}else
{
useCooldown.unlock();
speed.unlock();
range.unlock();
fov.unlock();
}
}
};
public CheckboxSetting useCooldown =
new CheckboxSetting("Use Attack Cooldown as Speed", true)
{
@Override
public void update()
{
speed.setDisabled(isChecked());
}
};
public SliderSetting speed =
new SliderSetting("Speed", 12, 0.1, 12, 0.1, ValueDisplay.DECIMAL);
public SliderSetting range =
new SliderSetting("Range", 4.25, 1, 4.25, 0.05, ValueDisplay.DECIMAL);
public SliderSetting fov =
new SliderSetting("FOV", 360, 30, 360, 10, ValueDisplay.DEGREES);
private TargetSettings targetSettings = new TargetSettings()
{
@Override
public float getRange()
{
return range.getValueF();
}
@Override
public float getFOV()
{
return fov.getValueF();
}
};
@Override
public void initSettings()
{
settings.add(useKillaura);
settings.add(useCooldown);
settings.add(speed);
settings.add(range);
settings.add(fov);
}
@Override
public Feature[] getSeeAlso()
{
return new Feature[]{wurst.special.targetSpf, wurst.mods.killauraMod,
wurst.mods.multiAuraMod, wurst.mods.clickAuraMod,
wurst.mods.triggerBotMod};
}
@Override
public void onEnable()
{
// disable other killauras
wurst.mods.killauraMod.setEnabled(false);
wurst.mods.multiAuraMod.setEnabled(false);
wurst.mods.clickAuraMod.setEnabled(false);
wurst.mods.tpAuraMod.setEnabled(false);
wurst.mods.triggerBotMod.setEnabled(false);
wurst.events.add(UpdateListener.class, this);
}
@Override
public void onDisable()
{
wurst.events.remove(UpdateListener.class, this);
}
@Override
public void onUpdate()
{
// update timer
updateMS();
// check timer / cooldown
if(useCooldown.isChecked() ? mc.player.getCooledAttackStrength(0F) < 1F
: !hasTimePassedS(speed.getValueF()))
return;
// set entity
Entity entity = EntityUtils.getBestEntityToAttack(targetSettings);
// check if entity was found
if(entity == null)
return;
// face entity
if(!RotationUtils.faceEntityClient(entity))
return;
// Criticals
if(wurst.mods.criticalsMod.isActive() && mc.player.onGround)
mc.player.jump();
// attack entity
mc.playerController.attackEntity(mc.player, entity);
PlayerUtils.swingArmClient();
// reset timer
updateLastMS();
}
} |
package verification.platu.stategraph;
import java.io.*;
import java.util.*;
import lpn.parser.LhpnFile;
import lpn.parser.Transition;
import verification.platu.common.PlatuObj;
import verification.platu.lpn.DualHashMap;
import verification.platu.lpn.LPN;
import verification.platu.lpn.LpnTranList;
import verification.platu.lpn.VarSet;
import verification.timed_state_exploration.zone.TimedState;
/**
* State
* @author Administrator
*/
public class State extends PlatuObj {
public static int[] counts = new int[15];
protected int[] marking;
protected int[] vector;
protected boolean[] tranVector; // indicator vector to record whether each transition is enabled or not.
private int hashVal = 0;
private LhpnFile lpn = null;
private int index;
private boolean localEnabledOnly;
protected boolean failure = false;
// The TimingState that extends this state with a zone. Null if untimed.
//protected TimedState timeExtension;
// A list of all the TimedStates that are time extensions of this state.
private ArrayList<TimedState> timeExtensions;
@Override
public String toString() {
// String ret=Arrays.toString(marking)+""+
// Arrays.toString(vector);
// return "["+ret.replace("[", "{").replace("]", "}")+"]";
return this.print();
}
public State(final LhpnFile lpn, int[] new_marking, int[] new_vector, boolean[] new_isTranEnabled) {
this.lpn = lpn;
this.marking = new_marking;
this.vector = new_vector;
this.tranVector = new_isTranEnabled;
if (marking == null || vector == null || tranVector == null) {
new NullPointerException().printStackTrace();
}
//Arrays.sort(this.marking);
this.index = 0;
localEnabledOnly = false;
counts[0]++;
}
public State(State other) {
if (other == null) {
new NullPointerException().printStackTrace();
}
this.lpn = other.lpn;
this.marking = new int[other.marking.length];
System.arraycopy(other.marking, 0, this.marking, 0, other.marking.length);
this.vector = new int[other.vector.length];
System.arraycopy(other.vector, 0, this.vector, 0, other.vector.length);
this.tranVector = new boolean[other.tranVector.length];
System.arraycopy(other.tranVector, 0, this.tranVector, 0, other.tranVector.length);
// this.hashVal = other.hashVal;
this.hashVal = 0;
this.index = other.index;
this.localEnabledOnly = other.localEnabledOnly;
counts[0]++;
}
// TODO: (temp) Two Unused constructors, State() and State(Object otherState)
// public State() {
// this.marking = new int[0];
// this.vector = new int[0];//EMPTY_VECTOR.clone();
// this.hashVal = 0;
// this.index = 0;
// localEnabledOnly = false;
// counts[0]++;
//static PrintStream out = System.out;
// public State(Object otherState) {
// State other = (State) otherState;
// if (other == null) {
// new NullPointerException().printStackTrace();
// this.lpnModel = other.lpnModel;
// this.marking = new int[other.marking.length];
// System.arraycopy(other.marking, 0, this.marking, 0, other.marking.length);
// // this.vector = other.getVector().clone();
// this.vector = new int[other.vector.length];
// System.arraycopy(other.vector, 0, this.vector, 0, other.vector.length);
// this.hashVal = other.hashVal;
// this.index = other.index;
// this.localEnabledOnly = other.localEnabledOnly;
// counts[0]++;
public void setLpn(final LhpnFile thisLpn) {
this.lpn = thisLpn;
}
public LhpnFile getLpn() {
return this.lpn;
}
public void setLabel(String lbl) {
}
public String getLabel() {
return null;
}
/**
* This method returns the boolean array representing the status (enabled/disabled) of each transition in an LPN.
* @return
*/
public boolean[] getTranVector() {
return tranVector;
}
public void setIndex(int newIndex) {
this.index = newIndex;
}
public int getIndex() {
return this.index;
}
public boolean hasNonLocalEnabled() {
return this.localEnabledOnly;
}
public void hasNonLocalEnabled(boolean nonLocalEnabled) {
this.localEnabledOnly = nonLocalEnabled;
}
public boolean isFailure() {
return false;// getType() != getType().NORMAL || getType() !=
// getType().TERMINAL;
}
public static long tSum = 0;
@Override
public State clone() {
counts[6]++;
State s = new State(this);
return s;
}
public String print() {
DualHashMap<String, Integer> VarIndexMap = this.lpn.getVarIndexMap();
String message = "Marking: [";
for (int i : marking) {
message += i + ",";
}
message += "]\n" + "Vector: [";
for (int i = 0; i < vector.length; i++) {
message += VarIndexMap.getKey(i) + "=>" + vector[i]+", ";
}
message += "]\n" + "Transition Vector: [";
for (int i = 0; i < tranVector.length; i++) {
message += tranVector[i] + ",";
}
message += "]\n";
return message;
}
@Override
public int hashCode() {
if(hashVal == 0){
final int prime = 31;
int result = 1;
result = prime * result + ((lpn == null) ? 0 : lpn.getLabel().hashCode());
result = prime * result + Arrays.hashCode(marking);
result = prime * result + Arrays.hashCode(vector);
result = prime * result + Arrays.hashCode(tranVector);
hashVal = result;
}
return hashVal;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
State other = (State) obj;
if (lpn == null) {
if (other.lpn != null)
return false;
}
else if (!lpn.equals(other.lpn))
return false;
if (!Arrays.equals(marking, other.marking))
return false;
if (!Arrays.equals(vector, other.vector))
return false;
if (!Arrays.equals(tranVector, other.tranVector))
return false;
return true;
}
public void print(DualHashMap<String, Integer> VarIndexMap) {
System.out.print("Marking: [");
for (int i : marking) {
System.out.print(i + ",");
}
System.out.println("]");
System.out.print("Vector: [");
for (int i = 0; i < vector.length; i++) {
System.out.print(VarIndexMap.getKey(i) + "=>" + vector[i]+", ");
}
System.out.println("]");
System.out.print("Transition vector: [");
for (boolean bool : tranVector) {
System.out.print(bool + ",");
}
System.out.println("]");
}
/**
* @return the marking
*/
public int[] getMarking() {
return marking;
}
public void setMarking(int[] newMarking) {
marking = newMarking;
}
/**
* @return the vector
*/
public int[] getVector() {
// new Exception("StateVector getVector(): "+s).printStackTrace();
return vector;
}
public HashMap<String, Integer> getOutVector(VarSet outputs, DualHashMap<String, Integer> VarIndexMap) {
HashMap<String, Integer> outVec = new HashMap<String, Integer>();
for(int i = 0; i < vector.length; i++) {
String var = VarIndexMap.getKey(i);
if(outputs.contains(var) == true)
outVec.put(var, vector[i]);
}
return outVec;
}
public State getLocalState() {
//VarSet lpnOutputs = this.lpnModel.getOutputs();
//VarSet lpnInternals = this.lpnModel.getInternals();
Set<String> lpnOutputs = this.lpn.getAllOutputs().keySet();
Set<String> lpnInternals = this.lpn.getAllInternals().keySet();
DualHashMap<String,Integer> varIndexMap = this.lpn.getVarIndexMap();
int[] outVec = new int[this.vector.length];
/*
* Create a copy of the vector of mState such that the values of inputs are set to 0
* and the values for outputs/internal variables remain the same.
*/
for(int i = 0; i < this.vector.length; i++) {
String curVar = varIndexMap.getKey(i);
if(lpnOutputs.contains(curVar) ==true || lpnInternals.contains(curVar)==true)
outVec[i] = this.vector[i];
else
outVec[i] = 0;
}
// TODO: (??) Need to create outTranVector as well?
return new State(this.lpn, this.marking, outVec, this.tranVector);
}
/**
* @return the enabledSet
*/
public int[] getEnabledSet() {
return null;// enabledSet;
}
public LpnTranList getEnabledTransitions() {
LpnTranList enabledTrans = new LpnTranList();
for (int i=0; i<tranVector.length; i++) {
if (tranVector[i]) {
enabledTrans.add(this.lpn.getTransition(i));
}
}
return enabledTrans;
}
public String getEnabledSetString() {
String ret = "";
// for (int i : enabledSet) {
// ret += i + ", ";
return ret;
}
/**
* Return a new state if the newVector leads to a new state from this state; otherwise return null.
* @param newVector
* @param VarIndexMap
* @return
*/
public State update(StateGraph SG,HashMap<String, Integer> newVector, DualHashMap<String, Integer> VarIndexMap) {
int[] newStateVector = new int[this.vector.length];
boolean newState = false;
for(int index = 0; index < vector.length; index++) {
String var = VarIndexMap.getKey(index);
int this_val = this.vector[index];
Integer newVal = newVector.get(var);
if(newVal != null) {
if(this_val != newVal) {
newState = true;
newStateVector[index] = newVal;
}
else
newStateVector[index] = this.vector[index];
}
else
newStateVector[index] = this.vector[index];
}
boolean[] newEnabledTranVector = SG.updateEnabledTranVector(this.getTranVector(), this.marking, newStateVector, null);
if(newState == true)
return new State(this.lpn, this.marking, newStateVector, newEnabledTranVector);
return null;
}
/**
* Return a new state if the newVector leads to a new state from this state; otherwise return null.
* States considered here include a vector indicating enabled/disabled state of each transition.
* @param newVector
* @param VarIndexMap
* @return
*/
public State update(HashMap<String, Integer> newVector, DualHashMap<String, Integer> VarIndexMap,
boolean[] newTranVector) {
int[] newStateVector = new int[this.vector.length];
boolean newState = false;
for(int index = 0; index < vector.length; index++) {
String var = VarIndexMap.getKey(index);
int this_val = this.vector[index];
Integer newVal = newVector.get(var);
if(newVal != null) {
if(this_val != newVal) {
newState = true;
newStateVector[index] = newVal;
}
else
newStateVector[index] = this.vector[index];
}
else
newStateVector[index] = this.vector[index];
}
if (!this.tranVector.equals(newTranVector))
newState = true;
if(newState == true)
return new State(this.lpn, this.marking, newStateVector, newTranVector);
return null;
}
static public void printUsageStats() {
System.out.printf("%-20s %11s\n", "State", counts[0]);
System.out.printf("\t%-20s %11s\n", "State", counts[10]);
// System.out.printf("\t%-20s %11s\n", "State", counts[11]);
// System.out.printf("\t%-20s %11s\n", "merge", counts[1]);
System.out.printf("\t%-20s %11s\n", "update", counts[2]);
// System.out.printf("\t%-20s %11s\n", "compose", counts[3]);
System.out.printf("\t%-20s %11s\n", "equals", counts[4]);
// System.out.printf("\t%-20s %11s\n", "conjunction", counts[5]);
System.out.printf("\t%-20s %11s\n", "clone", counts[6]);
System.out.printf("\t%-20s %11s\n", "hashCode", counts[7]);
// System.out.printf("\t%-20s %11s\n", "resembles", counts[8]);
// System.out.printf("\t%-20s %11s\n", "digest", counts[9]);
}
//TODO: (original) try database serialization
public File serialize(String filename) throws FileNotFoundException,
IOException {
File f = new File(filename);
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(f));
os.writeObject(this);
os.close();
return f;
}
public static State deserialize(String filename)
throws FileNotFoundException, IOException, ClassNotFoundException {
File f = new File(filename);
ObjectInputStream os = new ObjectInputStream(new FileInputStream(f));
State zone = (State) os.readObject();
os.close();
return zone;
}
public static State deserialize(File f) throws FileNotFoundException,
IOException, ClassNotFoundException {
ObjectInputStream os = new ObjectInputStream(new FileInputStream(f));
State zone = (State) os.readObject();
os.close();
return zone;
}
public boolean failure(){
return this.failure;
}
public void setFailure(){
this.failure = true;
}
public void print(LhpnFile lpn) {
System.out.print("Marking: [");
// for (int i : marking) {
// System.out.print(i + ",");
for (int i=0; i < marking.length; i++) {
System.out.print(lpn.getPlaceList().clone()[i] + "=" + marking[i] + ", ");
}
System.out.println("]");
System.out.print("Vector: [");
for (int i = 0; i < vector.length; i++) {
System.out.print(lpn.getVarIndexMap().getKey(i) + "=>" + vector[i]+", ");
}
System.out.println("]");
System.out.print("Transition vector: [");
for (boolean bool : tranVector) {
System.out.print(bool + ",");
}
System.out.println("]");
}
/**
* Getter for the TimingState that extends this state.
* @return
* The TimingState that extends this state if it has been set. Null, otherwise.
*/
public ArrayList<TimedState> getTimeExtension(){
return timeExtensions;
}
/**
* Setter for the TimingState that extends this state.
* @param s
* The TimingState that extends this state.
*/
public void setTimeExtension(ArrayList<TimedState> s){
timeExtensions = s;
}
public void addTimeExtension(TimedState s){
if(timeExtensions == null){
timeExtensions = new ArrayList<TimedState>();
}
timeExtensions.add(s);
}
} |
package hex.tree;
import sun.misc.Unsafe;
import water.*;
import water.fvec.Frame;
import water.fvec.Vec;
import water.nbhm.UtilUnsafe;
import water.util.ArrayUtils;
import water.util.AtomicUtils;
import water.util.Log;
import water.util.RandomUtils;
import java.util.Arrays;
import java.util.Random;
/** A Histogram, computed in parallel over a Vec.
*
* <p>A {@code DHistogram} bins every value added to it, and computes a the
* vec min and max (for use in the next split), and response mean and variance
* for each bin. {@code DHistogram}s are initialized with a min, max and
* number-of- elements to be added (all of which are generally available from
* a Vec). Bins run from min to max in uniform sizes. If the {@code
* DHistogram} can determine that fewer bins are needed (e.g. boolean columns
* run from 0 to 1, but only ever take on 2 values, so only 2 bins are
* needed), then fewer bins are used.
*
* <p>{@code DHistogram} are shared per-node, and atomically updated. There's
* an {@code add} call to help cross-node reductions. The data is stored in
* primitive arrays, so it can be sent over the wire.
*
* <p>If we are successively splitting rows (e.g. in a decision tree), then a
* fresh {@code DHistogram} for each split will dynamically re-bin the data.
* Each successive split will logarithmically divide the data. At the first
* split, outliers will end up in their own bins - but perhaps some central
* bins may be very full. At the next split(s) - if they happen at all -
* the full bins will get split, and again until (with a log number of splits)
* each bin holds roughly the same amount of data. This 'UniformAdaptive' binning
* resolves a lot of problems with picking the proper bin count or limits -
* generally a few more tree levels will equal any fancy but fixed-size binning strategy.
*
* <p>Support for histogram split points based on quantiles (or random points) is
* available as well, via {@code _histoType}.
*
*/
public final class DHistogram extends Iced {
public final transient String _name; // Column name (for debugging)
public final double _minSplitImprovement;
public final byte _isInt; // 0: float col, 1: int col, 2: categorical & int col
public char _nbin; // Bin count (excluding NA bucket)
public double _step; // Linear interpolation step per bin
public final double _min, _maxEx; // Conservative Min/Max over whole collection. _maxEx is Exclusive.
protected double [] _vals;
public double w(int i){ return _vals[3*i+0];}
public double wY(int i){ return _vals[3*i+1];}
public double wYY(int i){return _vals[3*i+2];}
public void addWAtomic(int i, double wDelta) { // used by AutoML
AtomicUtils.DoubleArray.add(_vals, 3*i+0, wDelta);
}
public void addNasAtomic(double y, double wy, double wyy) {
AtomicUtils.DoubleArray.add(_vals,3*_nbin+0,y);
AtomicUtils.DoubleArray.add(_vals,3*_nbin+1,wy);
AtomicUtils.DoubleArray.add(_vals,3*_nbin+2,wyy);
}
public void addNasPlain(double... ds) {
_vals[3*_nbin+0] += ds[0];
_vals[3*_nbin+1] += ds[1];
_vals[3*_nbin+2] += ds[2];
}
public double wNA() { return _vals[3*_nbin+0]; }
public double wYNA() { return _vals[3*_nbin+1]; }
public double wYYNA() { return _vals[3*_nbin+2]; }
// Atomically updated double min/max
protected double _min2, _maxIn; // Min/Max, shared, atomically updated. _maxIn is Inclusive.
private static final Unsafe _unsafe = UtilUnsafe.getUnsafe();
static private final long _min2Offset;
static private final long _max2Offset;
static {
try {
_min2Offset = _unsafe.objectFieldOffset(DHistogram.class.getDeclaredField("_min2"));
_max2Offset = _unsafe.objectFieldOffset(DHistogram.class.getDeclaredField("_maxIn"));
} catch( Exception e ) {
throw H2O.fail();
}
}
public SharedTreeModel.SharedTreeParameters.HistogramType _histoType; //whether ot use random split points
public transient double _splitPts[]; // split points between _min and _maxEx (either random or based on quantiles)
public final long _seed;
public transient boolean _hasQuantiles;
public Key _globalQuantilesKey; //key under which original top-level quantiles are stored;
/**
* Split direction for missing values.
*
* Warning: If you change this enum, make sure to synchronize them with `hex.genmodel.algos.tree.NaSplitDir` in
* package `h2o-genmodel`.
*/
public enum NASplitDir {
//never saw NAs in training
None(0), //initial state - should not be present in a trained model
// saw NAs in training
NAvsREST(1), //split off non-NA (left) vs NA (right)
NALeft(2), //NA goes left
NARight(3), //NA goes right
// never NAs in training, but have a way to deal with them in scoring
Left(4), //test time NA should go left
Right(5); //test time NA should go right
private int value;
NASplitDir(int v) { this.value = v; }
public int value() { return value; }
}
static class HistoQuantiles extends Keyed<HistoQuantiles> {
public HistoQuantiles(Key<HistoQuantiles> key, double[] splitPts) {
super(key);
this.splitPts = splitPts;
}
double[/*nbins*/] splitPts;
}
public static int[] activeColumns(DHistogram[] hist) {
int[] cols = new int[hist.length];
int len=0;
for( int i=0; i<hist.length; i++ ) {
if (hist[i]==null) continue;
assert hist[i]._min < hist[i]._maxEx && hist[i].nbins() > 1 : "broken histo range "+ hist[i];
cols[len++] = i; // Gather active column
}
// cols = Arrays.copyOfRange(cols, len, hist.length);
return cols;
}
public void setMin( double min ) {
long imin = Double.doubleToRawLongBits(min);
double old = _min2;
while( min < old && !_unsafe.compareAndSwapLong(this, _min2Offset, Double.doubleToRawLongBits(old), imin ) )
old = _min2;
}
// Find Inclusive _max2
public void setMaxIn( double max ) {
long imax = Double.doubleToRawLongBits(max);
double old = _maxIn;
while( max > old && !_unsafe.compareAndSwapLong(this, _max2Offset, Double.doubleToRawLongBits(old), imax ) )
old = _maxIn;
}
static class StepOutOfRangeException extends RuntimeException {
public StepOutOfRangeException(double step, int xbins, double maxEx, double min) {
super("step=" + step + ", xbins = " + xbins + ", maxEx = " + maxEx + ", min = " + min);
}
}
public DHistogram(String name, final int nbins, int nbins_cats, byte isInt, double min, double maxEx,
double minSplitImprovement, SharedTreeModel.SharedTreeParameters.HistogramType histogramType, long seed, Key globalQuantilesKey) {
assert nbins > 1;
assert nbins_cats > 1;
assert maxEx > min : "Caller ensures "+maxEx+">"+min+", since if max==min== the column "+name+" is all constants";
_isInt = isInt;
_name = name;
_min=min;
_maxEx=maxEx; // Set Exclusive max
_min2 = Double.MAX_VALUE; // Set min/max to outer bounds
_maxIn= -Double.MAX_VALUE;
_minSplitImprovement = minSplitImprovement;
_histoType = histogramType;
_seed = seed;
while (_histoType == SharedTreeModel.SharedTreeParameters.HistogramType.RoundRobin) {
SharedTreeModel.SharedTreeParameters.HistogramType[] h = SharedTreeModel.SharedTreeParameters.HistogramType.values();
_histoType = h[(int)Math.abs(seed++ % h.length)];
}
if (_histoType== SharedTreeModel.SharedTreeParameters.HistogramType.AUTO)
_histoType= SharedTreeModel.SharedTreeParameters.HistogramType.UniformAdaptive;
assert(_histoType!= SharedTreeModel.SharedTreeParameters.HistogramType.RoundRobin);
_globalQuantilesKey = globalQuantilesKey;
// See if we can show there are fewer unique elements than nbins.
// Common for e.g. boolean columns, or near leaves.
int xbins = isInt == 2 ? nbins_cats : nbins;
if (isInt > 0 && maxEx - min <= xbins) {
assert ((long) min) == min : "Overflow for integer/categorical histogram: minimum value cannot be cast to long without loss: (long)" + min + " != " + min + "!"; // No overflow
xbins = (char) ((long) maxEx - (long) min); // Shrink bins
_step = 1.0f; // Fixed stepsize
} else {
_step = xbins / (maxEx - min); // Step size for linear interpolation, using mul instead of div
if(_step <= 0 || Double.isInfinite(_step) || Double.isNaN(_step))
throw new StepOutOfRangeException(_step, xbins, maxEx, min);
}
_nbin = (char) xbins;
assert(_nbin>0);
assert(_vals ==null);
// Log.info("Histogram: " + this);
// Do not allocate the big arrays here; wait for scoreCols to pick which cols will be used.
}
// Interpolate d to find bin
public int bin( double col_data ) {
if(Double.isNaN(col_data)) return _nbin; // NA bucket
if (Double.isInfinite(col_data)) // Put infinity to most left/right bin
if (col_data<0) return 0;
else return _nbin-1;
assert _min <= col_data && col_data < _maxEx : "Coldata " + col_data + " out of range " + this;
// When the model is exposed to new test data, we could have data that is
// out of range of any bin - however this binning call only happens during
// model-building.
int idx1;
double pos = _hasQuantiles ? col_data : ((col_data - _min) * _step);
if (_splitPts != null) {
idx1 = Arrays.binarySearch(_splitPts, pos);
if (idx1 < 0) idx1 = -idx1 - 2;
} else {
idx1 = (int) pos;
}
if (idx1 == _nbin) idx1--; // Roundoff error allows idx1 to hit upper bound, so truncate
assert 0 <= idx1 && idx1 < _nbin : idx1 + " " + _nbin;
return idx1;
}
public double binAt( int b ) {
if (_hasQuantiles) return _splitPts[b];
return _min + (_splitPts == null ? b : _splitPts[b]) / _step;
}
public int nbins() { return _nbin; }
public double bins(int b) { return w(b); }
// Big allocation of arrays
public void init() { init(null);}
public void init(double [] vals) {
assert _vals == null;
if (_histoType==SharedTreeModel.SharedTreeParameters.HistogramType.Random) {
// every node makes the same split points
Random rng = RandomUtils.getRNG((Double.doubleToRawLongBits(((_step+0.324)*_min+8.3425)+89.342*_maxEx) + 0xDECAF*_nbin + 0xC0FFEE*_isInt + _seed));
assert(_nbin>1);
_splitPts = new double[_nbin];
_splitPts[0] = 0;
_splitPts[_nbin - 1] = _nbin-1;
for (int i = 1; i < _nbin-1; ++i)
_splitPts[i] = rng.nextFloat() * (_nbin-1);
Arrays.sort(_splitPts);
}
else if (_histoType== SharedTreeModel.SharedTreeParameters.HistogramType.QuantilesGlobal) {
assert (_splitPts == null);
if (_globalQuantilesKey != null) {
HistoQuantiles hq = DKV.getGet(_globalQuantilesKey);
if (hq != null) {
_splitPts = ((HistoQuantiles) DKV.getGet(_globalQuantilesKey)).splitPts;
if (_splitPts!=null) {
// Log.info("Obtaining global splitPoints: " + Arrays.toString(_splitPts));
_splitPts = ArrayUtils.limitToRange(_splitPts, _min, _maxEx);
if (_splitPts.length > 1 && _splitPts.length < _nbin)
_splitPts = ArrayUtils.padUniformly(_splitPts, _nbin);
if (_splitPts.length <= 1) {
_splitPts = null; //abort, fall back to uniform binning
_histoType = SharedTreeModel.SharedTreeParameters.HistogramType.UniformAdaptive;
}
else {
_hasQuantiles=true;
_nbin = (char)_splitPts.length;
// Log.info("Refined splitPoints: " + Arrays.toString(_splitPts));
}
}
}
}
}
else assert(_histoType== SharedTreeModel.SharedTreeParameters.HistogramType.UniformAdaptive);
//otherwise AUTO/UniformAdaptive
assert(_nbin>0);
_vals = vals == null?MemoryManager.malloc8d(3*_nbin+3):vals;
}
// Add one row to a bin found via simple linear interpolation.
// Compute bin min/max.
// Compute response mean & variance.
void incr( double col_data, double y, double w ) {
if (Double.isNaN(col_data)) {
addNasAtomic(w,w*y,w*y*y);
return;
}
assert Double.isInfinite(col_data) || (_min <= col_data && col_data < _maxEx) : "col_data "+col_data+" out of range "+this;
int b = bin(col_data); // Compute bin# via linear interpolation
water.util.AtomicUtils.DoubleArray.add(_vals,3*b,w); // Bump count in bin
// Track actual lower/upper bound per-bin
if (!Double.isInfinite(col_data)) {
setMin(col_data);
setMaxIn(col_data);
}
if( y != 0 && w != 0) incr0(b,y,w);
}
// Merge two equal histograms together. Done in a F/J reduce, so no
// synchronization needed.
public void add( DHistogram dsh ) {
assert (_vals == null || dsh._vals == null) || (_isInt == dsh._isInt && _nbin == dsh._nbin && _step == dsh._step &&
_min == dsh._min && _maxEx == dsh._maxEx);
if( dsh._vals == null ) return;
if(_vals == null)
init(dsh._vals);
else
ArrayUtils.add(_vals,dsh._vals);
if (_min2 > dsh._min2) _min2 = dsh._min2;
if (_maxIn < dsh._maxIn) _maxIn = dsh._maxIn;
}
// Inclusive min & max
public double find_min () { return _min2 ; }
public double find_maxIn() { return _maxIn; }
// Exclusive max
public double find_maxEx() { return find_maxEx(_maxIn,_isInt); }
public static double find_maxEx(double maxIn, int isInt ) {
double ulp = Math.ulp(maxIn);
if( isInt > 0 && 1 > ulp ) ulp = 1;
double res = maxIn+ulp;
return Double.isInfinite(res) ? maxIn : res;
}
// The initial histogram bins are setup from the Vec rollups.
public static DHistogram[] initialHist(Frame fr, int ncols, int nbins, DHistogram hs[], long seed, SharedTreeModel.SharedTreeParameters parms, Key[] globalQuantilesKey) {
Vec vecs[] = fr.vecs();
for( int c=0; c<ncols; c++ ) {
Vec v = vecs[c];
final double minIn = v.isCategorical() ? 0 : Math.max(v.min(),-Double.MAX_VALUE); // inclusive vector min
final double maxIn = v.isCategorical() ? v.domain().length-1 : Math.min(v.max(), Double.MAX_VALUE); // inclusive vector max
final double maxEx = v.isCategorical() ? v.domain().length : find_maxEx(maxIn,v.isInt()?1:0); // smallest exclusive max
final long vlen = v.length();
try {
hs[c] = v.naCnt() == vlen || v.min() == v.max() ?
null : make(fr._names[c], nbins, (byte) (v.isCategorical() ? 2 : (v.isInt() ? 1 : 0)), minIn, maxEx, seed, parms, globalQuantilesKey[c]);
} catch(StepOutOfRangeException e) {
hs[c] = null;
Log.warn("Column " + fr._names[c] + " with min = " + v.min() + ", max = " + v.max() + " has step out of range (" + e.getMessage() + ") and is ignored.");
}
assert (hs[c] == null || vlen > 0);
}
return hs;
}
public static DHistogram make(String name, final int nbins, byte isInt, double min, double maxEx, long seed, SharedTreeModel.SharedTreeParameters parms, Key globalQuantilesKey) {
return new DHistogram(name,nbins, parms._nbins_cats, isInt, min, maxEx, parms._min_split_improvement, parms._histogram_type, seed, globalQuantilesKey);
}
// Pretty-print a histogram
@Override public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(_name).append(":").append(_min).append("-").append(_maxEx).append(" step=" + (1 / _step) + " nbins=" + nbins() + " isInt=" + _isInt);
if( _vals != null ) {
for(int b = 0; b< _nbin; b++ ) {
sb.append(String.format("\ncnt=%f, [%f - %f], mean/var=", w(b),_min+b/_step,_min+(b+1)/_step));
sb.append(String.format("%6.2f/%6.2f,", mean(b), var(b)));
}
sb.append('\n');
}
return sb.toString();
}
double mean(int b) {
double n = w(b);
return n>0 ? wY(b)/n : 0;
}
/**
* compute the sample variance within a given bin
* @param b bin id
* @return sample variance (>= 0)
*/
public double var (int b) {
double n = w(b);
if( n<=1 ) return 0;
return Math.max(0, (wYY(b) - wY(b)* wY(b)/n)/(n-1)); //not strictly consistent with what is done elsewhere (use n instead of n-1 to get there)
}
// Add one row to a bin found via simple linear interpolation.
// Compute response mean & variance.
// Done racily instead F/J map calls, so atomic
public void incr0( int b, double y, double w ) {
AtomicUtils.DoubleArray.add(_vals,3*b+1,(float)(w*y)); //See 'HistogramTest' JUnit for float-casting rationalization
AtomicUtils.DoubleArray.add(_vals,3*b+2,(float)(w*y*y));
}
// Same, except square done by caller
public void incr1( int b, double y, double yy) {
AtomicUtils.DoubleArray.add(_vals,3*b+1,(float)y); //See 'HistogramTest' JUnit for float-casting rationalization
AtomicUtils.DoubleArray.add(_vals,3*b+2,(float)yy);
}
/**
* Update counts in appropriate bins. Not thread safe, assumed to have private copy.
* @param ws observation weights
* @param cs column data
* @param ys response
* @param rows rows sorted by leaf assignemnt
* @param hi upper bound on index into rows array to be processed by this call (exclusive)
* @param lo lower bound on index into rows array to be processed by this call (inclusive)
*/
public void updateHisto(double[] ws, double[] cs, double[] ys, int [] rows, int hi, int lo){
// Gather all the data for this set of rows, for 1 column and 1 split/NID
// Gather min/max, wY and sum-squares.
for(int r = lo; r< hi; ++r) {
int k = rows[r];
double weight = ws[k];
if (weight == 0) continue;
double col_data = cs[k];
if (col_data < _min2) _min2 = col_data;
if (col_data > _maxIn) _maxIn = col_data;
double y = ys[k];
assert (!Double.isNaN(y));
double wy = weight * y;
double wyy = wy * y;
int b = bin(col_data);
_vals[3*b + 0] += weight;
_vals[3*b + 1] += wy;
_vals[3*b + 2] += wyy;
}
}
/**
* Cast bin values *except for sums of weights and Na-bucket counters to floats to drop least significant bits.
* Improves reproducibility (drop bits most affected by floating point error).
*/
public void reducePrecision(){
if(_vals == null) return;
for(int i = 0; i < _vals.length -3 /* do not reduce precision of NAs */; i+=3) {
_vals[i+1] = (float)_vals[i+1];
_vals[i+2] = (float)_vals[i+2];
}
}
public void updateSharedHistosAndReset(ScoreBuildHistogram.LocalHisto lh, double[] ws, double[] cs, double[] ys, int [] rows, int hi, int lo) {
double minmax[] = new double[]{_min2,_maxIn};
// Gather all the data for this set of rows, for 1 column and 1 split/NID
// Gather min/max, wY and sum-squares.
for(int r = lo; r< hi; ++r) {
int k = rows[r];
double weight = ws[k];
if (weight == 0) continue;
double col_data = cs[k];
if (col_data < minmax[0]) minmax[0] = col_data;
if (col_data > minmax[1]) minmax[1] = col_data;
double y = ys[k];
assert(!Double.isNaN(y));
double wy = weight * y;
double wyy = wy * y;
if (Double.isNaN(col_data)) {
//separate bucket for NA - atomically added to the shared histo
addNasAtomic(weight,wy,wyy);
} else {
// increment local per-thread histograms
int b = bin(col_data);
lh.wAdd(b,weight);
lh.wYAdd(b,wy);
lh.wYYAdd(b,wyy);
}
}
// Atomically update histograms
setMin(minmax[0]); // Track actual lower/upper bound per-bin
setMaxIn(minmax[1]);
final int len = _nbin;
for( int b=0; b<len; b++ ) {
if (lh.w(b) != 0) {
AtomicUtils.DoubleArray.add(_vals, 3*b+0, lh.w(b));
lh.wClear(b);
}
if (lh.wY(b) != 0) {
AtomicUtils.DoubleArray.add(_vals, 3*b+1, (float) lh.wY(b));
lh.wYClear(b);
}
if (lh.wYY(b) != 0) {
AtomicUtils.DoubleArray.add(_vals, 3*b+2,(float)lh.wYY(b));
lh.wYYClear(b);
}
}
}
} |
package com.mitsugaru.karmicjail.command;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.mitsugaru.karmicjail.KarmicJail;
import com.mitsugaru.karmicjail.database.DBHandler;
import com.mitsugaru.karmicjail.database.Table;
import com.mitsugaru.karmicjail.jail.JailStatus;
import com.mitsugaru.karmicjail.jail.PrisonerInfo;
import com.mitsugaru.karmicjail.config.RootConfig;
import com.mitsugaru.karmicjail.inventory.JailInventoryHolder;
import com.mitsugaru.karmicjail.permissions.PermCheck;
import com.mitsugaru.karmicjail.permissions.PermissionNode;
import com.mitsugaru.karmicjail.services.CommandHandler;
import com.mitsugaru.karmicjail.services.JailCommand;
public class Commander extends CommandHandler {
private final Map<String, Integer> page = new HashMap<String, Integer>();
private final Map<String, PrisonerInfo> cache = new HashMap<String, PrisonerInfo>();
private final Map<String, JailInventoryHolder> inventoryHolders = new HashMap<String, JailInventoryHolder>();
public Commander(KarmicJail plugin) {
super(plugin, "kj");
// Register commands
JailPlayerCommand jail = new JailPlayerCommand();
registerCommand("jail", jail);
registerCommand("j", jail);
registerCommand("unjail", new UnjailCommand());
registerCommand("setjail", new SetJailCommand());
registerCommand("setunjail", new SetUnjailCommand());
HelpCommand help = new HelpCommand();
registerCommand("help", help);
registerCommand("?", help);
VersionCommand version = new VersionCommand();
registerCommand("version", version);
registerCommand("ver", version);
StatusCommand status = new StatusCommand();
registerCommand("status", status);
registerCommand("check", status);
registerCommand("reload", new ReloadCommand());
registerCommand("list", new ListCommand());
registerCommand("prev", new PrevCommand());
registerCommand("next", new NextCommand());
registerCommand("mute", new MuteCommand());
registerCommand("time", new TimeCommand());
registerCommand("reason", new ReasonCommand());
registerCommand("last", new LastCommand());
registerCommand("inv", new InventoryCommand());
registerCommand("warp", new WarpCommand());
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
RootConfig config = plugin.getModuleForClass(RootConfig.class);
long dTime = 0;
if(config.debugTime) {
dTime = System.nanoTime();
}
boolean value = super.onCommand(sender, command, label, args);
if(config.debugTime) {
dTime = System.nanoTime() - dTime;
sender.sendMessage("[Debug]" + KarmicJail.TAG + "Process time: " + dTime);
}
return value;
}
public void showHelp(CommandSender sender) {
PermCheck perm = plugin.getModuleForClass(PermCheck.class);
sender.sendMessage(ChatColor.BLUE + "=====" + ChatColor.GREEN + "KarmicJail" + ChatColor.BLUE + "=====");
if(perm.has(sender, PermissionNode.JAIL)) {
sender.sendMessage(ChatColor.GREEN + "/kj jail " + ChatColor.AQUA + "<player> " + ChatColor.LIGHT_PURPLE + "[player2]... [time] [reason]"
+ ChatColor.YELLOW + " : Jails player(s)");
sender.sendMessage(ChatColor.YELLOW + "Note - Names auto-complete if player is online.");
sender.sendMessage(ChatColor.GREEN + "/kj time" + ChatColor.AQUA + " <player> <time>" + ChatColor.YELLOW
+ " : View and set time for jailed player.");
sender.sendMessage(ChatColor.GREEN + "/kj reason" + ChatColor.AQUA + " <player> " + ChatColor.LIGHT_PURPLE + "[reason]" + ChatColor.YELLOW
+ " : Sets jail reason for player.");
}
if(perm.has(sender, PermissionNode.UNJAIL)) {
sender.sendMessage(ChatColor.GREEN + "/kj unjail" + ChatColor.AQUA + " <player>" + ChatColor.YELLOW + " : Unjail player");
}
if(perm.has(sender, PermissionNode.MUTE)) {
sender.sendMessage(ChatColor.GREEN + "/kj mute" + ChatColor.AQUA + " <player>" + ChatColor.YELLOW + " : Toggle mute for a player.");
}
if(perm.has(sender, PermissionNode.LIST)) {
sender.sendMessage(ChatColor.GREEN + "/kj list" + ChatColor.LIGHT_PURPLE + " [page]" + ChatColor.YELLOW + " : List jailed players.");
sender.sendMessage(ChatColor.GREEN + "/kj prev" + ChatColor.YELLOW + " : Previous page. Alias: /jprev");
sender.sendMessage(ChatColor.GREEN + "/kj next" + ChatColor.YELLOW + " : Next page. Alias: /jnext");
}
if(perm.has(sender, PermissionNode.HISTORY_VIEW)) {
sender.sendMessage(ChatColor.GREEN + "/kj history" + ChatColor.LIGHT_PURPLE + " [args]" + ChatColor.YELLOW + " : Jail history command.");
}
if(perm.has(sender, PermissionNode.INVENTORY_VIEW)) {
sender.sendMessage(ChatColor.GREEN + "/kj inv" + ChatColor.AQUA + " <player>" + ChatColor.YELLOW + " : Open inventory of jailed player.");
}
if(perm.has(sender, PermissionNode.WARP_LAST)) {
sender.sendMessage(ChatColor.GREEN + "/kj last" + ChatColor.AQUA + " <player>" + ChatColor.YELLOW
+ " : Warp to last known postion of player");
}
if(perm.has(sender, PermissionNode.SETJAIL)) {
sender.sendMessage(ChatColor.GREEN + "/kj setjail" + ChatColor.LIGHT_PURPLE + " [x] [y] [z] [world]" + ChatColor.YELLOW
+ " : Set jail teleport to current pos or given pos");
sender.sendMessage(ChatColor.GREEN + "/kj setunjail" + ChatColor.LIGHT_PURPLE + " [x] [y] [z] [world]" + ChatColor.YELLOW
+ " : Set unjail teleport to current pos or given pos");
}
if(perm.has(sender, PermissionNode.JAILSTATUS)) {
sender.sendMessage(ChatColor.GREEN + "/kj status" + ChatColor.LIGHT_PURPLE + " [player]" + ChatColor.YELLOW + " : Get jail status.");
}
sender.sendMessage(ChatColor.GREEN + "/kj version" + ChatColor.YELLOW + " : Plugin version and config info. Alias: /jversion");
}
/**
* Lists the players in jail
*
* @param sender
* of command
* @param Page
* adjustment
*/
public void listJailed(CommandSender sender, int pageAdjust) {
RootConfig config = plugin.getModuleForClass(RootConfig.class);
DBHandler database = plugin.getModuleForClass(DBHandler.class);
// Update cache of jailed players
ResultSet rs = null;
try {
// TODO order by date
rs = database.query("SELECT * FROM " + Table.JAILED.getName() + " WHERE status='" + JailStatus.JAILED + "' OR status='"
+ JailStatus.PENDINGJAIL + "';");
if(rs.next()) {
do {
String name = rs.getString("playername");
String jailer = rs.getString("jailer");
if(rs.wasNull()) {
jailer = "NOBODY";
}
String date = rs.getString("date");
if(rs.wasNull()) {
date = "NO DATE";
}
String reason = rs.getString("reason");
if(rs.wasNull()) {
reason = "";
}
long time = rs.getLong("time");
if(rs.wasNull()) {
time = 0;
}
int muteInt = rs.getInt("muted");
if(rs.wasNull()) {
muteInt = 0;
}
boolean muted = false;
if(muteInt == 1) {
muted = true;
}
cache.put(name, new PrisonerInfo(name, jailer, date, reason, time, muted));
// Update the time if necessary
if(KarmicJail.getJailThreads().containsKey(name)) {
cache.get(name).updateTime(KarmicJail.getJailThreads().get(name).remainingTime());
}
} while(rs.next());
}
} catch(SQLException e) {
plugin.getLogger().log(Level.SEVERE, KarmicJail.TAG + " SQL Exception", e);
e.printStackTrace();
} finally {
database.cleanup(rs, null);
}
if(cache.isEmpty()) {
sender.sendMessage(ChatColor.RED + KarmicJail.TAG + " No jailed players");
return;
}
if(!page.containsKey(sender.getName())) {
page.put(sender.getName(), 0);
} else {
if(pageAdjust != 0) {
int adj = page.get(sender.getName()).intValue() + pageAdjust;
page.put(sender.getName(), adj);
}
}
PrisonerInfo[] array = cache.values().toArray(new PrisonerInfo[0]);
// Caluclate amount of pages
int num = array.length / 8;
double rem = (double) array.length % (double) config.limit;
if(rem != 0) {
num++;
}
if(page.get(sender.getName()).intValue() < 0) {
// They tried to use /ks prev when they're on page 0
sender.sendMessage(ChatColor.YELLOW + KarmicJail.TAG + " Page does not exist");
// reset their current page back to 0
page.put(sender.getName(), 0);
} else if((page.get(sender.getName()).intValue()) * config.limit > array.length) {
// They tried to use /ks next at the end of the list
sender.sendMessage(ChatColor.YELLOW + KarmicJail.TAG + " Page does not exist");
// Revert to last page
page.put(sender.getName(), num - 1);
}
// Header with amount of pages
sender.sendMessage(ChatColor.BLUE + "===" + ChatColor.GRAY + "Jailed" + ChatColor.BLUE + "===" + ChatColor.GRAY + "Page: "
+ ((page.get(sender.getName()).intValue()) + 1) + ChatColor.BLUE + " of " + ChatColor.GRAY + num + ChatColor.BLUE + "===");
// list
for(int i = ((page.get(sender.getName()).intValue()) * config.limit); i < ((page.get(sender.getName()).intValue()) * config.limit)
+ config.limit; i++) {
// Don't try to pull something beyond the bounds
if(i < array.length) {
StringBuilder sb = new StringBuilder();
Player player = plugin.getServer().getPlayer(array[i].name);
// Grab player and colorize name if they're online or not
if(player == null) {
sb.append(ChatColor.RED + array[i].name + ChatColor.GRAY + " - ");
} else {
sb.append(ChatColor.GREEN + array[i].name + ChatColor.GRAY + " - ");
}
// Grab date
try {
sb.append(ChatColor.GOLD + array[i].date.substring(0, 10) + ChatColor.GRAY + " - ");
} catch(StringIndexOutOfBoundsException e) {
// Incorrect format stored, so just give the date as is
sb.append(ChatColor.GOLD + array[i].date + ChatColor.GRAY + " - ");
}
// Give jailer name
sb.append(ChatColor.AQUA + array[i].jailer);
// Grab time if applicable
if(array[i].time > 0) {
double temp = Math.floor(((double) array[i].time / (double) KarmicJail.minutesToTicks) + 0.5f);
sb.append(ChatColor.GRAY + " - " + ChatColor.BLUE + "" + plugin.prettifyMinutes((int) temp));
}
// Grab reason if there was one given
if(!array[i].reason.equals("")) {
sb.append(ChatColor.GRAY + " - " + ChatColor.GRAY + ChatColor.translateAlternateColorCodes('&', array[i].reason));
}
// Grab if muted
if(array[i].mute) {
sb.append(ChatColor.GRAY + " - " + ChatColor.DARK_RED + "MUTED");
}
sender.sendMessage(sb.toString());
} else {
break;
}
}
}
public Map<String, JailInventoryHolder> getInventoryHolders() {
return inventoryHolders;
}
public Map<String, Integer> getPage() {
return page;
}
public Map<String, PrisonerInfo> getCache() {
return cache;
}
@Override
public boolean noArgs(CommandSender sender, Command command, String label) {
showHelp(sender);
return true;
}
@Override
public boolean unknownCommand(CommandSender sender, Command command, String label, String[] args) {
sender.sendMessage(ChatColor.YELLOW + KarmicJail.TAG + " Invalid command '" + args[0] + "', use /kj help.");
return true;
}
private class HelpCommand implements JailCommand {
@Override
public boolean execute(KarmicJail plugin, CommandSender sender, Command command, String label, String[] args) {
showHelp(sender);
return true;
}
}
} |
package jp.toastkid.gui.jfx.wiki;
import java.awt.Desktop;
import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.MessageFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.eclipse.collections.impl.factory.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXCheckBox;
import com.jfoenix.controls.JFXDatePicker;
import com.jfoenix.controls.JFXSnackbar;
import com.jfoenix.controls.JFXTextArea;
import com.sun.javafx.scene.control.skin.ContextMenuContent;
import com.sun.javafx.scene.control.skin.ContextMenuContent.MenuItemContainer;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.DoubleProperty;
import javafx.collections.ObservableList;
import javafx.concurrent.Worker;
import javafx.concurrent.Worker.State;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.print.PageLayout;
import javafx.print.PageOrientation;
import javafx.print.Paper;
import javafx.print.Printer;
import javafx.print.PrinterJob;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.MenuItem;
import javafx.scene.control.MultipleSelectionModel;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.Slider;
import javafx.scene.control.SplitPane;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebHistory;
import javafx.scene.web.WebView;
import javafx.stage.PopupWindow;
import javafx.stage.Stage;
import javafx.stage.Window;
import jp.toastkid.gui.jfx.common.Style;
import jp.toastkid.gui.jfx.common.control.AutoCompleteTextField;
import jp.toastkid.gui.jfx.dialog.AlertDialog;
import jp.toastkid.gui.jfx.dialog.ProgressDialog;
import jp.toastkid.gui.jfx.wiki.chart.ChartPane;
import jp.toastkid.gui.jfx.wiki.control.ArticleListCell;
import jp.toastkid.gui.jfx.wiki.dialog.ConfigDialog;
import jp.toastkid.gui.jfx.wiki.jobs.FileWatcherJob;
import jp.toastkid.gui.jfx.wiki.models.Article;
import jp.toastkid.gui.jfx.wiki.models.Article.Extension;
import jp.toastkid.gui.jfx.wiki.models.Config;
import jp.toastkid.gui.jfx.wiki.models.Defines;
import jp.toastkid.gui.jfx.wiki.models.Resources;
import jp.toastkid.gui.jfx.wiki.rss.RssFeeder;
import jp.toastkid.gui.jfx.wiki.search.FileSearcher;
import jp.toastkid.gui.jfx.wiki.search.SearchResult;
import jp.toastkid.gui.jfx.wordcloud.FxWordCloud;
import jp.toastkid.gui.jfx.wordcloud.JFXMasonryPane2;
import jp.toastkid.libs.WebServiceHelper;
import jp.toastkid.libs.archiver.ZipArchiver;
import jp.toastkid.libs.utils.AobunUtils;
import jp.toastkid.libs.utils.CalendarUtil;
import jp.toastkid.libs.utils.CollectionUtil;
import jp.toastkid.libs.utils.FileUtil;
import jp.toastkid.libs.utils.HtmlUtil;
import jp.toastkid.libs.utils.MathUtil;
import jp.toastkid.libs.utils.RuntimeUtil;
import jp.toastkid.libs.utils.Strings;
import jp.toastkid.libs.wiki.Wiki2Markdown;
import reactor.core.publisher.Mono;
/**
* JavaFX WikiClient's Controller.
*
* @author Toast kid
*
*/
public final class Controller implements Initializable {
/** Logger. */
private static final Logger LOGGER = LoggerFactory.getLogger(Controller.class);
/** default divider's position. */
private static final double DEFAULT_DIVIDER_POSITION = 0.2;
/** WebView's highliting. */
private static final String WINDOW_FIND_DOWN
= "window.find(\"{0}\", false, false, true, false, true, false)";
/** WebView's highliting. */
private static final String WINDOW_FIND_UP
= "window.find(\"{0}\", false, true, true, false, true, false)";
private static final int FOCUS_MARGIN = 10;
/** searcher appear keyboard shortcut. */
private static final KeyCodeCombination APPEAR_SEARCHER
= new KeyCodeCombination(KeyCode.F, KeyCombination.CONTROL_DOWN);
/** scripter appear keyboard shortcut. */
private static final KeyCodeCombination APPEAR_SCRIPTER
= new KeyCodeCombination(KeyCode.K, KeyCombination.CONTROL_DOWN);
/** run script keyboard shortcut. */
private static final KeyCodeCombination RUN_SCRIPT
= new KeyCodeCombination(KeyCode.ENTER, KeyCombination.CONTROL_DOWN);
/** Zoom increment keyboard shortcut. */
private static final KeyCodeCombination ZOOM_INCREMENT
= new KeyCodeCombination(KeyCode.SEMICOLON, KeyCombination.CONTROL_DOWN);
/** Zoom decrement keyboard shortcut. */
private static final KeyCodeCombination ZOOM_DECREMENT
= new KeyCodeCombination(KeyCode.MINUS, KeyCombination.CONTROL_DOWN);
/** Show left pane. */
private static final KeyCodeCombination SHOW_LEFT_PANE
= new KeyCodeCombination(KeyCode.RIGHT, KeyCombination.CONTROL_DOWN);
/** Hide left pane. */
private static final KeyCodeCombination HIDE_LEFT_PANE
= new KeyCodeCombination(KeyCode.LEFT, KeyCombination.CONTROL_DOWN);
/** select tab. */
private static final KeyCodeCombination FIRST_TAB
= new KeyCodeCombination(KeyCode.DIGIT1, KeyCombination.CONTROL_DOWN);
/** select tab. */
private static final KeyCodeCombination SECOND_TAB
= new KeyCodeCombination(KeyCode.DIGIT2, KeyCombination.CONTROL_DOWN);
/** select tab. */
private static final KeyCodeCombination THIRD_TAB
= new KeyCodeCombination(KeyCode.DIGIT3, KeyCombination.CONTROL_DOWN);
/** select tab. */
private static final KeyCodeCombination FOURTH_TAB
= new KeyCodeCombination(KeyCode.DIGIT4, KeyCombination.CONTROL_DOWN);
/** select tab. */
private static final KeyCodeCombination FIFTH_TAB
= new KeyCodeCombination(KeyCode.DIGIT5, KeyCombination.CONTROL_DOWN);
/** select tab. */
private static final KeyCodeCombination SIXTH_TAB
= new KeyCodeCombination(KeyCode.DIGIT6, KeyCombination.CONTROL_DOWN);
/** select tab. */
private static final KeyCodeCombination SEVENTH_TAB
= new KeyCodeCombination(KeyCode.DIGIT7, KeyCombination.CONTROL_DOWN);
/** select tab. */
private static final KeyCodeCombination EIGHTH_TAB
= new KeyCodeCombination(KeyCode.DIGIT8, KeyCombination.CONTROL_DOWN);
/** select tab. */
private static final KeyCodeCombination NINTH_TAB
= new KeyCodeCombination(KeyCode.DIGIT9, KeyCombination.CONTROL_DOWN);
/** header. */
@FXML
public HBox header;
/** footer. */
@FXML
public HBox footer;
/** URL . */
@FXML
public TextField urlText;
@FXML
public TabPane leftTabs;
/** (WebView). */
@FXML
public TabPane tabPane;
@FXML
public ListView<Article> articleList;
@FXML
public ListView<Article> historyList;
@FXML
public Label status;
@SuppressWarnings("rawtypes")
@FXML
public ComboBox searchKind;
/** Web . */
@FXML
public TextField webQuery;
@SuppressWarnings("rawtypes")
@FXML
public ComboBox graphKind;
@FXML
public ComboBox<String> month;
@FXML
public SplitPane splitter;
@FXML
public Button reload;
/** Web search button. */
@FXML
public Button webSearch;
/** Zoom Controller. */
@FXML
public Slider zoom;
/** Specify zoom rate. */
@FXML
public TextField zoomInput;
/** Stylesheet selector. */
@FXML
public ComboBox<String> style;
/** in article searcher area. */
@FXML
public HBox searcherArea;
/** in article searcher input box. */
@FXML
public TextField searcherInput;
/** calendar. */
@FXML
public DatePicker calendar;
@FXML
public VBox mainArea;
/** for desktop control. */
private static Desktop desktop;
/** functions class. */
private Functions func;
/** Stage. */
private Stage stage;
/** width. */
private double width;
/** height. */
private double height;
/** Music Player's controller. */
@FXML
private jp.toastkid.gui.jfx.wiki.music.Controller musicController;
/** NameMaker's controller. */
@FXML
private jp.toastkid.gui.jfx.wiki.name.Controller nameController;
/** Script area's controller. */
@FXML
private jp.toastkid.gui.jfx.wiki.script.Controller scriptController;
/** BMI area's controller. */
@FXML
private jp.toastkid.gui.jfx.wiki.bmi.Controller bmiController;
/** search history. */
private final TextField queryInput
= new AutoCompleteTextField(){{setPromptText("");}};
/** filter input. */
private final TextField filterInput
= new AutoCompleteTextField(){{setPromptText("");}};
/** for auto backup. */
private static final ExecutorService BACKUP = Executors.newSingleThreadExecutor();
/** file watcher. */
private static final FileWatcherJob FILE_WATCHER = new FileWatcherJob();
private FullScreen fs;
private FxWordCloud wordCloud;
@Override
public final void initialize(final URL url, final ResourceBundle bundle) {
final ProgressDialog pd = new ProgressDialog.Builder().setText("……").build();
pd.start(stage);
urlText.setText(Defines.DEFAULT_HOME);
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
pd.addProgress(1);
}
// initialize parallel task.
final int availableProcessors = Runtime.getRuntime().availableProcessors();
pd.addText("availableProcessors = " + availableProcessors);
final ExecutorService es = Executors.newFixedThreadPool(
availableProcessors + availableProcessors + availableProcessors);
es.execute(() -> {
final long start = System.currentTimeMillis();
prepareArticleList();
pd.addProgress(11);
pd.addText(Thread.currentThread().getName() + " Ended read article names. "
+ (System.currentTimeMillis() - start) + "ms");
});
es.execute(() -> {
final long start = System.currentTimeMillis();
func = new Functions();
pd.addProgress(11);
pd.addText(Thread.currentThread().getName() + " Ended initialize Functions class. "
+ (System.currentTimeMillis() - start) + "ms");
});
es.execute(() -> {
final long start = System.currentTimeMillis();
initGraphTool();
pd.addProgress(11);
pd.addText(Thread.currentThread().getName() + " Ended initialize graph tool. "
+ (System.currentTimeMillis() - start) + "ms");
});
es.execute(() -> {
final long start = System.currentTimeMillis();
Platform.runLater( () -> {
readStyleSheets();
setStylesheet();
splitter.setDividerPosition(0, DEFAULT_DIVIDER_POSITION);
});
pd.addProgress(11);
pd.addText(Thread.currentThread().getName() + " Ended initialize stylesheets. "
+ (System.currentTimeMillis() - start) + "ms");
});
// insert WebView to tabPane.
es.execute(() -> {
final long start = System.currentTimeMillis();
tabPane.getSelectionModel().selectedItemProperty().addListener(
(a, prevTab, nextTab) -> {
// (121224) URL
final Optional<WebView> opt = getCurrentWebView();
if (!opt.isPresent()) {
return;
}
final WebEngine engine = opt.get().getEngine();
final String tabUrl = engine.getLocation();
if (!StringUtils.isEmpty(tabUrl)
&& !tabUrl.startsWith("about")
&& !tabUrl.endsWith(Defines.TEMP_FILE_NAME)
){
urlText.setText(tabUrl);
return;
}
final String text = nextTab.getText();
if (StringUtils.isEmpty(text)) {
return;
}
// (130317)
final File selected = new File(
Config.get(Config.Key.ARTICLE_DIR),
Functions.toBytedString_EUC_JP(nextTab.getText()) + Article.Extension.WIKI.text()
);
if (selected.exists()){
Config.article = new Article(selected);
urlText.setText(Config.article.toInternalUrl());
focusOn();
}
}
);
wordCloud = new FxWordCloud.Builder().setNumOfWords(200).setMaxFontSize(120.0)
.setMinFontSize(8.0).build();
Platform.runLater( () -> {
openWebTab();
callHome();
});
pd.addProgress(11);
pd.addText(Thread.currentThread().getName() + " Ended initialize right tabs. "
+ (System.currentTimeMillis() - start) + "ms");
});
es.execute(() -> {
final long start = System.currentTimeMillis();
scriptController.scriptLanguage.getSelectionModel().select(0);
searcherInput.textProperty().addListener((observable, oldValue, newValue) ->
highlight(Optional.ofNullable(newValue), WINDOW_FIND_DOWN)
);
final DoubleProperty valueProperty = zoom.valueProperty();
valueProperty.addListener( (value, arg1, arg2) -> {
getCurrentWebView().ifPresent(wv -> {wv.zoomProperty().bindBidirectional(valueProperty);});
zoomInput.setText(Double.toString(valueProperty.get()));
});
pd.addProgress(11);
pd.addText(Thread.currentThread().getName() + " Ended initialize tools. "
+ (System.currentTimeMillis() - start) + "ms");
});
es.shutdown();
searchKind.getSelectionModel().select(0);
// move to top.
header.setOnMousePressed((event) -> moveToTop());
footer.setOnMousePressed((event) -> moveToBottom());
pd.addProgress(11);
reload.setGraphic( new ImageView(FileUtil.getUrl(Resources.PATH_IMG_RELOAD).toString()));
webSearch.setGraphic(new ImageView(FileUtil.getUrl(Resources.PATH_IMG_SEARCH).toString()));
//initReloadButton();
BACKUP.submit(FILE_WATCHER);
pd.addProgress(11);
pd.stop();
}
/**
* setup searcher and scripter. this method call by FXWikiClient.
*/
protected void setupExpandables() {
hideSearcher();
scriptController.hideScripter();
stage.getScene().setOnKeyPressed(e -> {
// select tab.
if (FIRST_TAB.match(e)) {
selectTab(0);
} else if (SECOND_TAB.match(e)) {
selectTab(1);
} else if (THIRD_TAB.match(e)) {
selectTab(2);
} else if (FOURTH_TAB.match(e)) {
selectTab(3);
} else if (FIFTH_TAB.match(e)) {
selectTab(4);
} else if (SIXTH_TAB.match(e)) {
selectTab(5);
} else if (SEVENTH_TAB.match(e)) {
selectTab(6);
} else if (EIGHTH_TAB.match(e)) {
selectTab(7);
} else if (NINTH_TAB.match(e)) {
selectTab(8);
}
if (APPEAR_SEARCHER.match(e)) {
if (searcherArea.visibleProperty().getValue()) {
hideSearcher();
} else {
openSearcher();
}
} else if (APPEAR_SCRIPTER.match(e)) {
if (scriptController.scripterArea.visibleProperty().getValue()) {
scriptController.hideScripter();
} else {
scriptController.openScripter();
}
} else if (ZOOM_INCREMENT.match(e)) {
zoom.increment();
} else if (ZOOM_DECREMENT.match(e)) {
zoom.decrement();
} else if (SHOW_LEFT_PANE.match(e)) {
showLeftPane();
} else if (HIDE_LEFT_PANE.match(e)) {
hideLeftPane();
}
});
scriptController.scripterInput.setOnKeyPressed((e) -> {
if (RUN_SCRIPT.match(e)) {
scriptController.runScript();
}
});
tabPane.setPrefHeight(height);
}
/**
* select specified index tab.
* @param index
*/
private void selectTab(final int index) {
if (index < 0 || tabPane.getTabs().size() < index ) {
LOGGER.info(index + " " + tabPane.getTabs().size());
return;
}
tabPane.getSelectionModel().select(index);
}
/**
* search backward.
*/
@FXML
protected void searchUp() {
highlight(Optional.ofNullable(searcherInput.getText()), WINDOW_FIND_UP);
}
/**
* search forward.
*/
@FXML
protected void searchDown() {
highlight(Optional.ofNullable(searcherInput.getText()), WINDOW_FIND_DOWN);
}
private final void highlight(
final Optional<String> word, final String script) {
word.ifPresent(keyword ->
getCurrentWebView()
.ifPresent(wv -> wv.getEngine().executeScript(MessageFormat.format(script, keyword)))
);
}
/**
* only call child method.
*/
@FXML
protected void openScripter() {
scriptController.openScripter();
}
@FXML
protected void hideSearcher() {
searcherArea.visibleProperty().setValue(false);
searcherArea.setManaged(false);
}
/**
* hide article search box area.
*/
private void openSearcher() {
searcherArea.setManaged(true);
searcherArea.visibleProperty().setValue(true);
searcherInput.requestFocus();
}
/**
* read stylesheets.
*/
private void readStyleSheets() {
style.getItems().addAll(Style.findFileNamesFromDir());
}
/**
* set stylesheet name in combobox.
*/
private void setStylesheet() {
final String stylesheet = Config.get(Config.Key.STYLESHEET);
style.getSelectionModel().select(StringUtils.isEmpty(stylesheet)
? 0 : style.getItems().indexOf(stylesheet));
}
@FXML
private final void setZoom() {
try {
final double ratio = Double.parseDouble(zoomInput.getText());
zoom.setValue(ratio);
} catch (final Exception e) {
LOGGER.error("Error", e);
}
}
@FXML
private final void callDefaultZoom() {
zoom.setValue(1.0);;
}
private final void moveToTop() {
getCurrentWebView().ifPresent(wv ->
wv.getEngine().executeScript(findScrollTop(wv.getEngine().getLocation()))
);
}
/**
* find scroll script.
* @param url
* @return
*/
private String findScrollTop(final String url) {
return url.endsWith(Defines.TEMP_FILE_NAME)
? "$('html,body').animate({ scrollTop: 0 }, 'fast');"
: "window.scrollTo(0, 0);";
}
private final void moveToBottom() {
getCurrentWebView().ifPresent(wv ->
wv.getEngine().executeScript(findScrollBottom(wv.getEngine().getLocation()))
);
}
/**
* find scroll script.
* @param url
* @return
*/
private String findScrollBottom(final String url) {
return url.endsWith(Defines.TEMP_FILE_NAME)
? "$('html,body').animate({ scrollTop: document.body.scrollHeight }, 'fast');"
: "window.scrollTo(0, document.body.scrollHeight);";
}
@FXML
public final void callGallery() {
func.generateGallery();
loadUrl(Functions.findInstallDir() + Defines.TEMP_FILE_NAME);
}
@FXML
public final void callCalendar() {
calendar.show();
final LocalDate value = calendar.getValue();
if (value == null) {
return;
}
loadDiary(value);
}
/**
* load diary specified LocalDate.
* @param date
*/
private void loadDiary(final LocalDate date) {
try {
final String prefix = "" + date.toString();
final Optional<Article> opt = articleList.getItems().stream()
.filter(item -> item.title.startsWith(prefix))
.findFirst();
if (!opt.isPresent()) {
new JFXSnackbar(mainArea).show(prefix + "'s diary is not exist.", 4000L);
return;
}
opt.ifPresent(article -> loadUrl(article.toInternalUrl()));
} catch (final Exception e) {
System.err.println("no such element" + e.getMessage());
}
}
private final void initGraphTool() {
@SuppressWarnings("unused")
final ObservableList<String> items = month.<String>getItems();
items.addAll(ChartPane.getMonthsList());
graphKind.getSelectionModel().select(0);
month.getSelectionModel().select(items.size() - 1);
}
@FXML
public final void callConvertAobun() {
final String absolutePath = Config.article.file.getAbsolutePath();
AobunUtils.docToTxt(absolutePath);
AlertDialog.showMessage(getParent(), "",
Strings.join("", System.lineSeparator(), absolutePath));
}
/**
* ePub .
*/
@FXML
public final void callConvertEpub() {
final RadioButton vertically = new RadioButton("vertically");
final RadioButton horizontally = new RadioButton("horizontally");
final ToggleGroup radios = new ToggleGroup() {{
getToggles().addAll(vertically, horizontally);
vertically.setSelected(true);
}};
new AlertDialog.Builder().setParent(getParent())
.setTitle("ePub").setMessage("OK ePub ")
.addControl(vertically, horizontally)
.setOnPositive("OK", () -> {
final ProgressDialog pd = new ProgressDialog.Builder()
.setScene(this.getParent().getScene())
.setText("ePub ……").build();
pd.start(stage);
func.toEpub(vertically.isSelected());
pd.stop();
}).build().show();
}
/**
* Json ePub .
*/
@FXML
public final void callGenerateEpubs() {
new AlertDialog.Builder().setParent(getParent())
.setTitle("ePub").setMessage("OK ePub ")
.setOnPositive("OK", () -> {
final ProgressDialog pd = new ProgressDialog.Builder()
.setScene(this.getParent().getScene())
.setText("ePub ……").build();
pd.start(stage);
func.runEpubGenerator();
pd.stop();
}).build().show();
}
/**
* call simple backup.
*/
@FXML
public final void callSimpleBachup() {
final DatePicker datePicker = new JFXDatePicker();
datePicker.show();
datePicker.setShowWeekNumbers(true);
new AlertDialog.Builder().setParent(getParent()).addControl(datePicker)
.setTitle("")
.setMessage("")
.setOnPositive("Backup", () -> {
final LocalDate value = datePicker.getValue();
if (value == null) {
return;
}
final long epochDay = CalendarUtil.zoneDateTime2long(
value.atStartOfDay().atZone(ZoneId.systemDefault()));
func.simpleBackup(Config.get(Config.Key.ARTICLE_DIR), epochDay);
}).build().show();
}
/**
* HTML .
*/
@FXML
public final void callHtmlSource() {
final Mono<String> source = Mono.<String>create(emitter -> {
getCurrentWebView().ifPresent(wv -> {
emitter.complete(wv.getEngine()
.executeScript(
"document.getElementsByTagName('html')[0].innerHTML;"
)
.toString()
.replace("<", "<")
.replace(">", ">")
);
});
});
final Mono<WebView> browser = Mono.<WebView>create(emitter -> {
final String title = tabPane.getSelectionModel().getSelectedItem().getText();
openWebTab(title.concat("'s HTML Source"));
getCurrentWebView().ifPresent(wv -> emitter.complete(wv));
});
source.and(browser).subscribe(tuple ->
tuple.t2.getEngine().loadContent(tuple.t1.replace("\n", "<br/>"))
);
}
/**
* HTML.
*/
@FXML
private final void callApplicationState() {
final Map<String, String> map = ApplicationState.getConfigMap();
final StringBuilder bld = new StringBuilder();
final String lineSeparator = System.lineSeparator();
map.forEach((key, value) ->
bld.append(key).append("\t").append(value).append(lineSeparator)
);
AlertDialog.showMessage(getParent(), "", bld.toString());
}
@FXML
private final void callBackUp(final ActionEvent event) {
final Window parent = getParent();
new AlertDialog.Builder().setParent(parent)
.setTitle("")
.setMessage("")
.setOnPositive("OK", () -> {
final ProgressDialog pd = new ProgressDialog.Builder()
.setScene(this.getParent().getScene())
.setText("……").build();
final long start = System.currentTimeMillis();
String sArchivePath = Config.get(Config.Key.ARTICLE_DIR);
try {
new ZipArchiver().doDirectory(sArchivePath);
//new ZipArchiver().doDirectory(iArchivePath);
} catch (final IOException e) {
LOGGER.error("Error", e);;
}
final long end = System.currentTimeMillis() - start;
pd.stop();
sArchivePath = sArchivePath.substring(0, sArchivePath.length() - 1)
.concat(ZipArchiver.EXTENSION_ZIP);
final String message = String.format("%s%s%d[ms]",
sArchivePath, System.lineSeparator(), end);
AlertDialog.showMessage(parent, "", message);
}).build().show();
}
/**
* get parent window.
* @return parent window.
*/
private Window getParent() {
return stage.getScene().getWindow();
}
@FXML
private final void setHome() {
final String currentURL = urlText.getText();
final Window parent = getParent();
if (currentURL.startsWith("/")
|| currentURL.startsWith("http:
|| currentURL.startsWith("https:
){
final String homeTitle = tabPane.getSelectionModel().getSelectedItem().getText();
new AlertDialog.Builder().setParent(parent).setTitle("")
.setMessage(homeTitle + "")
.setOnPositive("YES", () -> {
Config.store(Config.Key.HOME, currentURL);
Config.reload();
}).build().show();
return ;
}
AlertDialog.showMessage(parent, "", "");
}
/**
* .
* Wiki (HTML).
*/
@FXML
private final void reload() {
final Node node = getCurrentTab().getContent();
if (node == null) {
return;
}
if (node instanceof WebView) {
final WebEngine engine = ((WebView) node).getEngine();
final String url = engine.getLocation();
if (!url.contains(Defines.TEMP_FILE_NAME)
|| StringUtils.isEmpty(Config.article.file.getName())) {
engine.reload();
return;
}
loadUrl(Config.article.toInternalUrl(), true);
return;
}
// webView reload.
LOGGER.info(node.getClass().equals(ChartPane.class) + " " + node.getClass().getName() + " " + ToStringBuilder.reflectionToString(node));
if (node instanceof ChartPane) {
drawChart(false);
}
}
/**
* Web .
* @param event ActionEvent
*/
@FXML
private final void webSearch(final ActionEvent event) {
final String kind = searchKind.getItems()
.get(searchKind.getSelectionModel().getSelectedIndex())
.toString();
final String query = webQuery.getText();
if (StringUtils.isEmpty(query)){
return ;
}
final String url = WebServiceHelper.buildRequestUrl(query, kind);
if (StringUtils.isEmpty(url)){
return;
}
openWebTab();
loadUrl(url);
}
/**
* .
* @param event ActionEvent
*/
@FXML
private final void callConfig(final ActionEvent event) {
final String current = Config.get(Config.Key.VIEW_TEMPLATE);
new ConfigDialog(getParent()).showConfigDialog();
Config.reload();
musicController.reload();
if (!current.equals(Config.get(Config.Key.VIEW_TEMPLATE))) {
reload();
}
}
/**
* open CSS Generator.
*/
@FXML
private final void openCssGenerator() {
try {
new jp.toastkid.gui.jfx.cssgen.Main().start(this.stage);
} catch (final Exception e) {
LOGGER.error("Error", e);;
}
}
/**
* open Noodle Timer.
*/
@FXML
private final void openNoodleTimer() {
try {
new jp.toastkid.gui.jfx.noodle_timer.Main().start(this.stage);
} catch (final Exception e) {
LOGGER.error("Error", e);;
}
}
@FXML
private final void drawChart() {
drawChart(true);
}
@FXML
private final void drawChart(final boolean openNew) {
final String graphTitle = graphKind.getSelectionModel().getSelectedItem().toString();
final Pane content = ChartPane.make(graphTitle,
"" + month.getSelectionModel().getSelectedItem().toString());
if (openNew) {
final Tab tab = makeClosableTab(graphTitle);
tab.setContent(content);
openTab(tab);
return;
}
getCurrentTab().setContent(content);
}
/**
* current .
* @param tab Tab.
*/
private void openTab(final Tab tab) {
tabPane.getTabs().add(tab);
tabPane.getSelectionModel().select(tab);
}
/**
* WebView .
* @param e
*/
@FXML
private void openWebTab() {
openWebTab("");
}
/**
* WebView .
* @param title
*/
private void openWebTab(final String title) {
if (Config.article != null) {
Config.article.yOffset = 0;
}
final Tab tab = makeClosableTab("new tab");
final WebView wv = new WebView();
wv.setOnContextMenuRequested(event -> showContextMenu());
tab.setContent(wv);
final WebEngine engine = wv.getEngine();
engine.setCreatePopupHandler(
popupFeature -> {
openWebTab();
tabPane.getSelectionModel().selectLast();
return getCurrentWebView().get().getEngine();
}
);
//engine.setJavaScriptEnabled(true);
engine.setOnAlert(e -> LOGGER.info(e.getData()));
final Worker<Void> loadWorker = engine.getLoadWorker();
loadWorker.stateProperty().addListener(
(arg0, prev, next) -> {
final String url = engine.getLocation();
if (State.READY.equals(prev)) {
tab.setText("loading...");
}
if (Functions.isWikiArticleUrl(url)) {
if (State.SCHEDULED.equals(arg0.getValue())) {
loadWorker.cancel();
Platform.runLater(() -> loadUrl(url));
}
}
if (next == Worker.State.SUCCEEDED) {
tab.setText(StringUtils.isNotBlank(engine.getTitle())
? engine.getTitle() : title);
final int j = Config.article.yOffset;
if (j == 0) {
return;
}
engine.executeScript(String.format("window.scrollTo(0, %d);", j));
}
}
);
openTab(tab);
}
/**
* make closable tab.
* @param title tab's title
* @return
*/
private Tab makeClosableTab(final String title) {
final Tab tab = new Tab(title);
final Button closeButton = new JFXButton("x");
closeButton.setOnAction(e -> closeTab(tab));
tab.setGraphic(closeButton);
return tab;
}
private PopupWindow showContextMenu() {
@SuppressWarnings("deprecation")
final Iterator<Window> windows = Window.impl_getWindows();
while (windows.hasNext()) {
final Window window = windows.next();
if (!(window instanceof ContextMenu
&& window.getScene() != null && window.getScene().getRoot() != null)) {
return null;
}
final Parent root = window.getScene().getRoot();
// access to context menu content
if(root.getChildrenUnmodifiable().size() <= 0) {
return null;
}
final Node popup = root.getChildrenUnmodifiable().get(0);
if(popup.lookup(".context-menu") == null) {
return null;
}
final Node bridge = popup.lookup(".context-menu");
final ContextMenuContent cmc
= (ContextMenuContent)((Parent)bridge).getChildrenUnmodifiable().get(0);
final VBox itemsContainer = cmc.getItemsContainer();
for (final Node n: itemsContainer.getChildren()) {
final MenuItemContainer item = (MenuItemContainer) n;
item.getItem().setText(item.getItem().getText());
}
// adding new item:
final MenuItem length = new MenuItem(""){{
setOnAction(event -> callFileLength());
}};
final MenuItem fullScreen = new MenuItem("Full Screen"){{
setOnAction(event -> callTabFullScreen());
}};
final MenuItem slideShow = new MenuItem(""){{
setOnAction(event -> slideShow());
}};
final MenuItem openTab = new MenuItem(""){{
setOnAction(event -> openWebTab());
}};
final MenuItem source = new MenuItem(""){{
setOnAction(event -> callHtmlSource());
}};
final MenuItem search = new MenuItem(""){{
setOnAction(event -> openSearcher());
}};
final MenuItem moveToTop = new MenuItem(""){{
setOnAction(event -> moveToTop());
}};
final MenuItem moveToBottom = new MenuItem(""){{
setOnAction(event -> moveToBottom());
}};
final MenuItem searchAll = new MenuItem(""){{
setOnAction(event -> callSearch());
}};
final MenuItem showLeft = new MenuItem(""){{
setOnAction(event -> showLeftPane());
}};
final MenuItem hideLeft = new MenuItem(""){{
setOnAction(event -> hideLeftPane());
}};
final MenuItem wordCloud = new MenuItem("Word cloud"){{
setOnAction(event -> callWordCloud());
}};
// add new item:
cmc.getItemsContainer().getChildren().addAll(
cmc.new MenuItemContainer(length),
cmc.new MenuItemContainer(fullScreen),
cmc.new MenuItemContainer(slideShow),
cmc.new MenuItemContainer(openTab),
cmc.new MenuItemContainer(source),
cmc.new MenuItemContainer(search),
cmc.new MenuItemContainer(moveToTop),
cmc.new MenuItemContainer(moveToBottom),
cmc.new MenuItemContainer(searchAll),
cmc.new MenuItemContainer(isHideLeftPane() ? showLeft : hideLeft),
cmc.new MenuItemContainer(wordCloud)
);
return (PopupWindow)window;
}
return null;
}
private void showLeftPane() {
splitter.setDividerPosition(0, DEFAULT_DIVIDER_POSITION);
}
private void hideLeftPane() {
splitter.setDividerPosition(0, 0.0d);
}
/**
* true.
* @return true.
*/
private boolean isHideLeftPane() {
return splitter.getDividerPositions()[0] < 0.01d;
}
/**
* .1
* @param e
*/
@FXML
private final void closeTab(final ActionEvent event) {
closeTab(tabPane.getSelectionModel().getSelectedItem());
}
/**
* .
* @param tab
*/
private final void closeTab(final Tab tab) {
final ObservableList<Tab> tabs = tabPane.getTabs();
if (1 < tabs.size()) {
tabs.remove(tab);
}
}
@FXML
private final void back() {
final Optional<WebView> opt = getCurrentWebView();
opt.ifPresent(wv -> {
final WebHistory history = wv.getEngine().getHistory();
final int index = history.getCurrentIndex();
if (0 < index) {
history.go(index - 1);
}
});
}
@FXML
private final void forward() {
final Optional<WebView> opt = getCurrentWebView();
opt.ifPresent(wv -> {
final WebHistory history = wv.getEngine().getHistory();
final int index = history.getCurrentIndex();
if (index < history.getMaxSize()) {
history.go(index + 1);
}
});
}
/**
* .
* TODO
* @param event
*/
@FXML
private final void stop() {
Platform.runLater( () ->
getCurrentWebView().ifPresent(wv -> wv.getEngine().getLoadWorker().cancel()));
}
/**
* .
* @param event
*/
@FXML
private final void callFileLength() {
AlertDialog.showMessage(
getParent(),
"",
func.makeCharCountResult(
tabPane.getSelectionModel().getSelectedItem().getText(),
Config.article.file,
Defines.ARTICLE_ENCODE
)
);
}
@FXML
private final void callSearch() {
searchArticle("", "");
}
/**
* .
* @param q
* @param f
*/
private void searchArticle(final String q, final String f) {
final CheckBox isTitleOnly = new JFXCheckBox("");
final CheckBox isAnd = new JFXCheckBox("AND "){{setSelected(true);}};
new AlertDialog.Builder().setParent(getParent())
.setTitle("").setMessage("")
.addControl(queryInput, new Label(""), filterInput, isTitleOnly, isAnd)
.setOnPositive("OK", () -> {
final String query = queryInput.getText().trim();
if (StringUtils.isEmpty(query)) {
return;
}
((AutoCompleteTextField) queryInput).getEntries().add(query);
final String filter = filterInput.getText();
if (StringUtils.isNotBlank(filter)) {
((AutoCompleteTextField) filterInput).getEntries().add(filter);
}
final long start = System.currentTimeMillis();
final FileSearcher fileSearcher = new FileSearcher.Builder()
.setHomeDirPath(Config.get("articleDir"))
.setAnd(isAnd.isSelected())
.setTitleOnly(isTitleOnly.isSelected())
.setSelectName(filter)
.build();
final Map<String, SearchResult> map = fileSearcher.search(query);
if (map.isEmpty()){
AlertDialog.showMessage(
getParent(), "", "");
searchArticle(queryInput.getText(), filterInput.getText());
return;
}
final Tab tab = Functions.makeClosableTab(
String.format("%s%s", query, isAnd.isSelected() ? "AND" : "OR"),
leftTabs
);
// prepare tab's content.
final VBox box = new VBox();
leftTabs.getTabs().add(tab);
leftTabs.getSelectionModel().select(tab);
final ObservableList<Node> children = box.getChildren();
children.add(new Label(
String.format(": %d[ms]", fileSearcher.getLastSearchTime())));
children.add(new Label(String.format("%d / %d",
map.size(), fileSearcher.getLastFilenum())));
// set up ListView.
final ListView<Article> listView = new ListView<>();
initArticleList(listView);
listView.getItems().addAll(
map.entrySet().stream()
.map(entry -> new Article(new File(entry.getValue().filePath)))
.sorted()
.collect(Collectors.toList())
);
listView.setMinHeight(articleList.getHeight());
children.add(listView);
tab.setContent(box);
setStatus("" + (System.currentTimeMillis() - start) + "[ms]");
}).build().show();
}
@FXML
private final void callWordCloud() {
final Tab tab = makeClosableTab(Config.article.title + "");
final JFXMasonryPane2 pane = new JFXMasonryPane2();
final ScrollPane value = new ScrollPane(pane);
value.setFitToHeight(true);
value.setFitToWidth(true);
tab.setContent(value);
wordCloud.draw(pane, Config.article.file);
Platform.runLater(()-> value.requestLayout());
openTab(tab);
}
/**
* Markdown .
*/
@FXML
private void callConvertMd() {
final Tab tab = makeClosableTab("(MD)" + Config.article.title);
final TextArea pane = new JFXTextArea();
final double prefWidth = tabPane.getWidth();
pane.setPrefWidth(prefWidth);
pane.setPrefHeight(tabPane.getPrefHeight());
try {
pane.setText(CollectionUtil.implode(
Wiki2Markdown.convert(Files.readAllLines(Config.article.file.toPath()))
));
} catch (final IOException e) {
LOGGER.error("Error", e);;
AlertDialog.showMessage(getParent(), "IOException", e.getMessage());
return;
}
tab.setContent(new ScrollPane(pane));
openTab(tab);
}
/**
*
* TinySegmenter Java
* <HR>
* (130414) HTML <BR>
* (130406) TinySegmenter JavaScript Java<BR>
* (130401) <BR>
*/
@FXML
private final void callMorphAnalyzer() {
final long start = System.currentTimeMillis();
final Map<String, Integer> resMap = func.makeTermFrequencyMap();
openWebTab("");
func.generateHtml(HtmlUtil.getTableHtml(resMap), "");
loadDefaultFile();
setStatus("" + (System.currentTimeMillis() - start) + "[ms]");
}
/**
* call RSS Feeder
*/
@FXML
private final void callRssFeeder() {
final long start = System.currentTimeMillis();
openWebTab("RSS Feeder");
String content = RssFeeder.run();
if (StringUtils.isEmpty(content)) {
content = ".";
}
func.generateHtml(content, "RSS Feeder");
loadDefaultFile();
setStatus("" + (System.currentTimeMillis() - start) + "[ms]");
}
/**
* Load temporary HTML.
*/
private void loadDefaultFile() {
loadUrl(Functions.findInstallDir() + Defines.TEMP_FILE_NAME);
}
/**
* Call system calculator.
*/
@FXML
private final void callCalc() {
RuntimeUtil.callCalculator();
}
/**
* Call command prompt.
*/
@FXML
private final void callCmd() {
RuntimeUtil.callCmd();
}
/**
* switch Full screen mode.
*/
@FXML
private final void fullScreen() {
stage.setFullScreen(!stage.fullScreenProperty().get());
}
/**
* Show current tab to full screen.
*/
@FXML
private void callTabFullScreen() {
if (fs == null) {
fs = new FullScreen(this.width, this.height);
}
if (!StringUtils.equals(fs.getTitle(), Config.article.title)) {
fs.setTitle(Config.article.title);
fs.show(Functions.findInstallDir() + Defines.TEMP_FILE_NAME);
return;
}
fs.show();
}
/**
* show slide show.
*/
@FXML
private void slideShow() {
FileUtil.outPutStr(
Functions.bindArgs(
Resources.PATH_SLIDE,
Maps.mutable.of(
"title", Config.article.title,
"content", func.convertArticle2Slide(),
"theme", Config.get(Config.Key.SLIDE_THEME, "white")
)
),
Defines.TEMP_FILE_NAME,
Defines.ARTICLE_ENCODE
);
callTabFullScreen();
}
/**
* .
* @param event .
*/
@FXML
private final void openFolder(final ActionEvent event) {
final MenuItem source = (MenuItem) event.getSource();
final String text = source.getText();
String[] dirs;
switch (text) {
case "":
dirs = new String[]{ Functions.findInstallDir() };
break;
case "":
dirs = new String[]{ Config.get(Config.Key.ARTICLE_DIR) };
break;
case "":
dirs = new String[]{ Config.get(Config.Key.IMAGE_DIR) };
break;
case "":
dirs = Config.get(Config.Key.MUSIC_DIR).split(",");
break;
default:
dirs = new String[]{ Functions.findInstallDir() };
break;
}
for (final String dir : dirs) {
if (StringUtils.isBlank(dir)) {
continue;
}
final String openPath = dir.startsWith(FileUtil.FILE_PROTOCOL)
? dir
: FileUtil.FILE_PROTOCOL + dir;
RuntimeUtil.callExplorer(openPath);
}
}
@FXML
private final void callHome() {
loadUrl(Config.get(Config.Key.HOME));
}
private void prepareArticleList() {
initArticleList(articleList);
initArticleList(historyList);
loadArticleList();
}
/**
* ListView .
* @param listView ListView
*/
private void initArticleList(final ListView<Article> listView) {
listView.setCellFactory((lv) -> new ArticleListCell());
final MultipleSelectionModel<Article> selectionModel = listView.getSelectionModel();
selectionModel.setSelectionMode(SelectionMode.SINGLE);
selectionModel.selectedItemProperty().addListener((property, oldVal, newVal) -> {
if (property.getValue() == null) {
return;
}
loadUrl(property.getValue().toInternalUrl());
});
}
@FXML
private void loadArticleList() {
final ObservableList<Article> items = articleList.getItems();
items.removeAll();
final List<Article> readArticleNames = Functions.readArticleNames();
items.addAll(readArticleNames);
articleList.requestLayout();
focusOn();
}
/**
* ListView .
* @param items ObservableList
*/
private void focusOn() {
Platform.runLater(() -> {
final int indexOf = articleList.getItems().indexOf(Config.article);
if (indexOf != -1){
articleList.getSelectionModel().select(indexOf);
articleList.scrollTo(indexOf - FOCUS_MARGIN);
}
final int indexOfHistory = historyList.getItems().indexOf(Config.article);
if (indexOfHistory != -1){
historyList.getSelectionModel().select(indexOfHistory);
historyList.scrollTo(indexOfHistory - FOCUS_MARGIN);
}
});
}
/**
* .
* @param url URL
* @return yOffset.
*/
private void loadUrl(final String url) {
loadUrl(url, false);
}
/**
* .
* @param url URL
* @param isReload yOffset.
* @return yOffset.
*/
private void loadUrl(final String url, final boolean isReload) {
final Optional<WebView> currentWebView = getCurrentWebView();
if (!currentWebView.isPresent()) {
if (StringUtils.isNotBlank(url)) {
openWebTab();
loadUrl(url, isReload);
}
return;
}
// Web .
if (!StringUtils.isEmpty(url) && url.startsWith("http")) {
urlText.setText(url);
currentWebView.ifPresent(wv -> wv.getEngine().load(url));
return;
}
// (121229)
String fileName = Functions.findFileNameFromUrl(url);
final int lastIndexOf = fileName.lastIndexOf("
final String innerLink = lastIndexOf != -1
? HtmlUtil.tagEscape(fileName.substring(lastIndexOf)) : "";
// (140112)
if (lastIndexOf != -1) {
fileName = fileName.substring(0, lastIndexOf);
}
final File file = new File(Config.get(Config.Key.ARTICLE_DIR), fileName);
if (!fileName.endsWith(".html")
&& !FileUtil.isImageFile(fileName)
//&& (url.startsWith("file://") || url.startsWith(Defines.ARTICLE_URL_PREFIX) )
){
if (Config.article == null) {
Config.article = new Article(file);
} else {
Config.article.replace(file);
}
if (!file.exists()){
callEditor();
}
// TODO check
if (func == null) {
return;
}
// HTML
func.generateArticleFile();
urlText.setText(Config.article.toInternalUrl());
final WebEngine engine = getCurrentWebView().get().getEngine();
Platform.runLater(() -> {
final Object script = engine.executeScript("window.pageYOffset;");
final int yOffset
= script != null ? MathUtil.parseOrZero(script.toString()) : 0;
engine.load(Functions.findInstallDir() + Defines.TEMP_FILE_NAME + innerLink);
Config.article.yOffset = isReload ? yOffset : 0;
});
// deep copy .
addHistory(Config.article.clone());
focusOn();
}
}
/**
*
* @param article Article Object
*/
private final void addHistory(final Article article) {
final ObservableList<Article> items = historyList.getItems();
if (!items.contains(article)) {
items.add(0, article);
}
FILE_WATCHER.add(article.file);
historyList.requestLayout();
}
@FXML
private final void clearBackup() {
new AlertDialog.Builder().setParent(stage)
.setTitle("Clear History").setMessage("")
.setOnPositive("OK", () -> {
try {
Files.list(Paths.get("backup/")).parallel()
.forEach(p -> {
try {
Files.deleteIfExists(p);
} catch (final Exception e) {
LOGGER.error("Error", e);;
}
});
} catch (final Exception e) {
LOGGER.error("Error", e);;
}
})
.build().show();
}
@FXML
private final void clearHistory() {
new AlertDialog.Builder().setParent(stage)
.setTitle("Clear History").setMessage("")
.setOnPositive("OK", () -> {
historyList.getItems().clear();
FILE_WATCHER.clear();
})
.build().show();
}
/**
* .
* <HR>
* (130304) <BR>
*/
@FXML
private final void makeArticle() {
makeContent(Article.Extension.WIKI);
}
/**
* make new Markdown.
* .
*/
@FXML
private final void makeMarkdown() {
makeContent(Article.Extension.MD);
}
/**
* make content file.
* @param ext.
*/
private final void makeContent(final Extension ext) {
final TextField input = new TextField();
final String newArticleMessage = "";
input.setPromptText(newArticleMessage);
new AlertDialog.Builder().setParent(getParent())
.setTitle("")
.setMessage(newArticleMessage)
.addControl(input)
.build().show();
final String newFileName = input.getText();
if (!StringUtils.isEmpty(newFileName)){
Config.article = Article.find(Functions.toBytedString_EUC_JP(newFileName) + ext.text());
callEditor();
}
}
/**
*
* <HR>
* (130707) <BR>
* (130512) <BR>
*/
@FXML
private final void callCopy(final ActionEvent event) {
callRenameArticle(true);
}
/**
*
* <HR>
* (130707) <BR>
* (130512) <BR>
*/
@FXML
private final void callRename(final ActionEvent event) {
callRenameArticle(false);
}
/**
*
* <HR>
* @param isCopy
* (130707) <BR>
* (130512) <BR>
*/
private final void callRenameArticle(final boolean isCopy) {
String prefix = "";
if (isCopy) {
prefix = "Copy_";
}
final Window parent = getParent();
final String currentTitle = Config.article.title;
final TextField input = new TextField(prefix.concat(currentTitle));
final String renameMessage = "";
input.setPromptText(renameMessage);
new AlertDialog.Builder().setParent(parent)
.setTitle("").setMessage(renameMessage)
.addControl(input)
.setOnPositive("OK", () ->{
final String newTitle = input.getText();
if (StringUtils.isBlank(newTitle)) {
return;
}
final File dest = new File(
Config.get(Config.Key.ARTICLE_DIR),
Functions.toBytedString_EUC_JP(newTitle) + Config.article.extention()
);
if (dest.exists()){
AlertDialog.showMessage(parent, "", "");
}
final File file = Config.article.file;
boolean success = false;
try {
success = isCopy
? FileUtil.copyTransfer(file.getAbsolutePath(), dest.getAbsolutePath())
: file.renameTo(dest);
} catch (final IOException e) {
LOGGER.error("Error", e);;
}
final String title;
final String message;
if (success){
if (isCopy) {
title = "";
message = "" + newTitle + "";
} else {
title = "";
message = "" + newTitle + "";
}
AlertDialog.showMessage(parent, title, message);
Config.article.replace(dest);
loadUrl(Config.article.toInternalUrl());
removeHistory(new Article(file));
loadArticleList();
return;
}
if (isCopy) {
title = "";
message = "";
} else {
title = "";
message = "";
}
AlertDialog.showMessage(parent, title, message);
}).build().show();;
}
/**
*
* <HR>
* (130317) <BR>
* (130309) 1
* <BR>
* (130305) <BR>
*/
@FXML
public final void callDelete(final ActionEvent event) {
final Article article = Config.article;
final String deleteTarget = article.title;
final Window parent = getParent();
// (130317)
if (!article.file.exists()){
AlertDialog.showMessage(parent,
"", deleteTarget + " ");
return;
}
new AlertDialog.Builder().setParent(parent).setTitle("")
.setMessage(deleteTarget + " ")
.setOnPositive("OK", () -> {
article.file.delete();
AlertDialog.showMessage(parent, "", deleteTarget + " ");
// (130317)
final String homePath = Config.get(Config.Key.HOME);
loadUrl(homePath);
// (130309)
articleList.getItems().remove(deleteTarget);
removeHistory(article);
}).build().show();
}
/**
* .
* @param deleteTarget
*/
private final void removeHistory(final Article deleteTarget) {
final ObservableList<Article> items = historyList.getItems();
if (items.indexOf(deleteTarget) != -1) {
items.remove(deleteTarget);
}
}
@FXML
public final void callEditor() {
final File openTarget = Config.article.file;
if (openTarget.exists()){
openFileByEditor(openTarget);
return;
}
// (130302)
try {
openTarget.createNewFile();
Files.write(openTarget.toPath(), Functions.makeNewContent());
} catch (final IOException e) {
LOGGER.error("Error", e);;
}
loadArticleList();
openFileByEditor(openTarget);
}
/**
* open file by editor.
*
* @param openTarget
*/
public static void openFileByEditor(final File openTarget) {
if (!openTarget.exists() || desktop == null){
return;
}
try {
desktop.open(openTarget);
} catch (final IOException e) {
LOGGER.error("Error", e);;
}
}
/**
* return current tab.
* @return current tab.
*/
private final Tab getCurrentTab() {
return tabPane.getTabs().get(tabPane.getSelectionModel().getSelectedIndex());
}
/**
* WebView
* @return WebView empty
*/
private final Optional<WebView> getCurrentWebView() {
final ObservableList<Tab> tabs = tabPane.getTabs();
final Node content = tabs.get(tabPane.getSelectionModel()
.getSelectedIndex()).getContent();
return content instanceof WebView
? Optional.of((WebView) content)
: Optional.empty();
}
/**
* urlText .
*/
@FXML
public final void readUrlText(final ActionEvent event) {
loadUrl(urlText.getText());
}
/**
* PrinterJob .
*/
@FXML
public final void callPrinterJob() {
new AlertDialog.Builder().setParent(getParent())
.setTitle("PDF").setMessage("PDF")
.setOnPositive("OK", () -> {
final Optional<WebView> wv = getCurrentWebView();
if (!wv.isPresent()) {
return;
}
final Printer printer = Printer.getDefaultPrinter();
if(printer == null) {
LOGGER.warn("printe is null");
return;
} else {
LOGGER.info("print name:" + printer.getName());
}
final PageLayout pageLayout = printer.createPageLayout(
Paper.A4, PageOrientation.PORTRAIT, Printer.MarginType.DEFAULT);
// Printer
final PrinterJob job = PrinterJob.createPrinterJob(printer);
if (job == null) {
return;
}
job.getJobSettings().setJobName(Config.get(Config.Key.WIKI_TITLE));
LOGGER.info("jobName [{}]\n", job.getJobSettings().getJobName());
wv.get().getEngine().print(job);
job.endJob();
AlertDialog.showMessage(getParent(), "PDF", "PDF");
}).build().show();
}
/**
* call capture.
* @param filename
*/
@FXML
public void callCapture() {
func.capture(Long.toString(System.nanoTime()), getCurrentRectangle());
}
/**
* set stylesheet.
*/
@FXML
public void callSetOnStyle() {
final String styleName = style.getItems().get(style.getSelectionModel().getSelectedIndex())
.toString();
if (StringUtils.isEmpty(styleName)) {
return;
}
final ObservableList<String> stylesheets = stage.getScene().getStylesheets();
if (stylesheets != null) {
stylesheets.clear();
}
if ("MODENA".equals(styleName) || "CASPIAN".equals(styleName)) {
Application.setUserAgentStylesheet(styleName);
} else {
Application.setUserAgentStylesheet("MODENA");
stylesheets.add(Style.getPath(styleName));
}
Config.store(Config.Key.STYLESHEET, styleName);
}
/**
* get current window size rectangle.
* @return
*/
private Rectangle getCurrentRectangle() {
return new Rectangle(
(int) stage.getX(),
(int) stage.getY(),
(int) stage.getWidth(),
(int) stage.getHeight());
}
/**
* .
* <ol>
* <li> HTML .
* </ol>
*/
@FXML
public final void closeApplication() {
try {
if (BACKUP != null) {
BACKUP.shutdownNow();
}
} finally {
this.stage.close();
System.exit(0);
}
}
/**
* stage .
* @param stage
*/
public final void setStage(final Stage stage) {
this.stage = stage;
scriptController.setStage(this.stage);
}
/**
* .
* @param str
*/
public final void setStatus(final String str) {
status.setText(str);
}
/**
* height .
* @param height
*/
public final void setSize(final double width, final double height) {
this.width = width;
this.height = height;
}
} |
package lemming.context.inbound;
import lemming.context.BaseContext;
import org.apache.wicket.Component;
import org.apache.wicket.MarkupContainer;
import org.apache.wicket.extensions.markup.html.repeater.tree.AbstractTree;
import org.apache.wicket.extensions.markup.html.repeater.tree.ITreeProvider;
import org.apache.wicket.extensions.markup.html.repeater.tree.NestedTree;
import org.apache.wicket.extensions.markup.html.repeater.tree.content.Folder;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* A tree used to map inbound contexts to contexts.
*/
public class ContextTree extends NestedTree<BaseContext> {
/**
* Creates a tree.
*
* @param provider tree provider
*/
public ContextTree(ITreeProvider<BaseContext> provider) {
super("inboundContextTree", provider);
}
/**
* Creates a content component.
*
* @param id if of the component
* @param model model of the component
* @return The component.
*/
@Override
protected Component newContentComponent(String id, IModel<BaseContext> model) {
return new ContextFolder(id, this, model);
}
/**
* Collapses all roots.
*/
public void collapseAll() {
Iterator<? extends BaseContext> iterator = getProvider().getRoots();
while (iterator.hasNext()) {
collapse(iterator.next());
}
}
/**
* Expands all roots.
*/
public void expandAll() {
Iterator<? extends BaseContext> iterator = getProvider().getRoots();
while (iterator.hasNext()) {
expand(iterator.next());
}
}
/**
* A folder component for contexts.
*/
private class ContextFolder extends Folder<BaseContext> {
/**
* Creates a folder.
*
* @param id if of the folder
* @param tree parent tree
* @param model folder model
*/
ContextFolder(String id, AbstractTree<BaseContext> tree, IModel<BaseContext> model) {
super(id, tree, model);
}
/**
* Creates a label model.
*
* @param model folder model
* @return The label model.
*/
@Override
protected IModel<?> newLabelModel(IModel<BaseContext> model) {
BaseContext context = model.getObject();
return Model.of(String.format("<b>%d</b>: %s", context.getNumber(), context.getKeyword()));
}
/**
* Creates a label component.
*
* @param id id of the component
* @param model model of the component
* @return The component.
*/
@Override
protected Component newLabelComponent(String id, IModel<BaseContext> model) {
Component component = super.newLabelComponent(id, model);
component.setEscapeModelStrings(false);
return component;
}
/**
* Creates a link component.
*
* @param id id of the component
* @param model model of the component
* @return The component.
*/
@Override
protected MarkupContainer newLinkComponent(String id, IModel<BaseContext> model) {
MarkupContainer container = super.newLinkComponent(id, model);
container.setEscapeModelStrings(false);
return container;
}
/**
* Returns a style class for the folder.
*
* @return A style class.
*/
@Override
protected String getStyleClass() {
String styleClass = super.getStyleClass();
ITreeProvider<BaseContext> provider = ContextTree.this.getProvider();
StringBuilder stringBuilder = new StringBuilder();
if (getModelObject() instanceof InboundContext) {
return styleClass;
}
if (provider.hasChildren(getModelObject())) {
List<BaseContext> children = new ArrayList<>();
provider.getChildren(getModelObject()).forEachRemaining(children::add);
stringBuilder.append(styleClass);
if (children.size() > 1) {
return stringBuilder.append(" ").append("has-multiple-children").toString();
} else if (getModelObject().getKeyword().equals(children.get(0).getKeyword())) {
return styleClass;
} else {
return stringBuilder.append(" ").append("has-different-child").toString();
}
} else {
return stringBuilder.append(" ").append("has-no-children").toString();
}
}
}
} |
package main.java.com.bag.client;
import bftsmart.communication.client.ReplyReceiver;
import bftsmart.reconfiguration.util.RSAKeyLoader;
import bftsmart.tom.ServiceProxy;
import bftsmart.tom.core.messages.TOMMessage;
import bftsmart.tom.core.messages.TOMMessageType;
import bftsmart.tom.util.TOMUtil;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.pool.KryoFactory;
import com.esotericsoftware.kryo.pool.KryoPool;
import main.java.com.bag.operations.CreateOperation;
import main.java.com.bag.operations.DeleteOperation;
import main.java.com.bag.operations.IOperation;
import main.java.com.bag.operations.UpdateOperation;
import main.java.com.bag.util.*;
import main.java.com.bag.util.storage.NodeStorage;
import main.java.com.bag.util.storage.RelationshipStorage;
import org.jetbrains.annotations.NotNull;
import java.io.Closeable;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Class handling the client.
*/
public class TestClient extends ServiceProxy implements BAGClient, ReplyReceiver, Closeable, AutoCloseable
{
/**
* Should the transaction runNetty in secure mode?
*/
private boolean secureMode = true;
/**
* The place the local config file is. This + the cluster id will contain the concrete cluster config location.
*/
private static final String LOCAL_CONFIG_LOCATION = "local%d/config";
/**
* The place the global config files is.
*/
private static final String GLOBAL_CONFIG_LOCATION = "global/config";
/**
* Sets to log reads, updates, deletes and node creations.
*/
private ArrayList<NodeStorage> readsSetNode;
private ArrayList<RelationshipStorage> readsSetRelationship;
private ArrayList<IOperation> writeSet;
/**
* Amount of responses.
*/
private int responses = 0;
/**
* Defines if the client is currently committing.
*/
private boolean isCommitting = false;
/**
* Local timestamp of the current transaction.
*/
private long localTimestamp = -1;
/**
* The id of the local server process the client is communicating with.
*/
private int serverProcess;
/**
* Lock object to let the thread wait for a read return.
*/
private BlockingQueue<Object> readQueue = new LinkedBlockingQueue<>();
/**
* The last object in read queue.
*/
public static final Object FINISHED_READING = new Object();
/**
* Id of the local cluster.
*/
private final int localClusterId;
/**
* Checks if its the first read of the client.
*/
private boolean firstRead = true;
/**
* The proxy to use during communication with the globalCluster.
*/
private ServiceProxy globalProxy;
/**
* Create a threadsafe version of kryo.
*/
private KryoFactory factory = () ->
{
Kryo kryo = new Kryo();
kryo.register(NodeStorage.class, 100);
kryo.register(RelationshipStorage.class, 200);
kryo.register(CreateOperation.class, 250);
kryo.register(DeleteOperation.class, 300);
kryo.register(UpdateOperation.class, 350);
return kryo;
};
public TestClient(final int processId, final int serverId, final int localClusterId)
{
super(processId, localClusterId == -1 ? GLOBAL_CONFIG_LOCATION : String.format(LOCAL_CONFIG_LOCATION, localClusterId));
if(localClusterId != -1)
{
globalProxy = new ServiceProxy(100 + getProcessId(), "global/config");
}
secureMode = true;
this.serverProcess = serverId;
this.localClusterId = localClusterId;
initClient();
Log.getLogger().warn("Starting client " + processId);
}
/**
* Initiates the client maps and registers necessary operations.
*/
private void initClient()
{
readsSetNode = new ArrayList<>();
readsSetRelationship = new ArrayList<>();
writeSet = new ArrayList<>();
}
/**
* Get the blocking queue.
* @return the queue.
*/
@Override
public BlockingQueue<Object> getReadQueue()
{
return readQueue;
}
/**
* write requests. (Only reach database on commit)
*/
@Override
public void write(final Object identifier, final Object value)
{
if(identifier == null && value == null)
{
Log.getLogger().warn("Unsupported write operation");
return;
}
//Must be a create request.
if(identifier == null)
{
handleCreateRequest(value);
return;
}
//Must be a delete request.
if(value == null)
{
handleDeleteRequest(identifier);
return;
}
handleUpdateRequest(identifier, value);
}
/**
* Fills the updateSet in the case of an update request.
* @param identifier the value to write to.
* @param value what should be written.
*/
private void handleUpdateRequest(Object identifier, Object value)
{
//todo edit create request if equal.
if(identifier instanceof NodeStorage && value instanceof NodeStorage)
{
writeSet.add(new UpdateOperation<>((NodeStorage) identifier,(NodeStorage) value));
}
else if(identifier instanceof RelationshipStorage && value instanceof RelationshipStorage)
{
writeSet.add(new UpdateOperation<>((RelationshipStorage) identifier,(RelationshipStorage) value));
}
else
{
Log.getLogger().warn("Unsupported update operation can't update a node with a relationship or vice versa");
}
}
/**
* Fills the createSet in the case of a create request.
* @param value object to fill in the createSet.
*/
private void handleCreateRequest(Object value)
{
if(value instanceof NodeStorage)
{
writeSet.add(new CreateOperation<>((NodeStorage) value));
}
else if(value instanceof RelationshipStorage)
{
readsSetNode.add(((RelationshipStorage) value).getStartNode());
readsSetNode.add(((RelationshipStorage) value).getEndNode());
writeSet.add(new CreateOperation<>((RelationshipStorage) value));
}
}
/**
* Fills the deleteSet in the case of a delete requests and deletes the node also from the create set and updateSet.
* @param identifier the object to delete.
*/
private void handleDeleteRequest(Object identifier)
{
if(identifier instanceof NodeStorage)
{
writeSet.add(new DeleteOperation<>((NodeStorage) identifier));
}
else if(identifier instanceof RelationshipStorage)
{
writeSet.add(new DeleteOperation<>((RelationshipStorage) identifier));
}
}
/**
* ReadRequests.(Directly read database) send the request to the db.
* @param identifiers list of objects which should be read, may be NodeStorage or RelationshipStorage
*/
@Override
public void read(final Object...identifiers)
{
long timeStampToSend = firstRead ? -1 : localTimestamp;
for(final Object identifier: identifiers)
{
if (identifier instanceof NodeStorage)
{
//this sends the message straight to server 0 not to the others.
sendMessageToTargets(this.serialize(Constants.READ_MESSAGE, timeStampToSend, identifier), 0, new int[] {serverProcess}, TOMMessageType.UNORDERED_REQUEST);
}
else if (identifier instanceof RelationshipStorage)
{
sendMessageToTargets(this.serialize(Constants.RELATIONSHIP_READ_MESSAGE, timeStampToSend, identifier), 0, new int[] {serverProcess}, TOMMessageType.UNORDERED_REQUEST);
}
else
{
Log.getLogger().warn("Unsupported identifier: " + identifier.toString());
}
}
firstRead = false;
}
/**
* Receiving read requests replies here
* @param reply the received message.
*/
@Override
public void replyReceived(final TOMMessage reply)
{
final KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
final Kryo kryo = pool.borrow();
Log.getLogger().info("reply");
if(reply.getReqType() == TOMMessageType.UNORDERED_REQUEST)
{
final Input input = new Input(reply.getContent());
switch(kryo.readObject(input, String.class))
{
case Constants.READ_MESSAGE:
processReadReturn(input);
break;
case Constants.GET_PRIMARY:
case Constants.COMMIT_RESPONSE:
processCommitReturn(reply.getContent());
break;
default:
Log.getLogger().info("Unexpected message type!");
break;
}
input.close();
}
else if(reply.getReqType() == TOMMessageType.REPLY || reply.getReqType() == TOMMessageType.ORDERED_REQUEST)
{
Log.getLogger().info("Commit return" + reply.getReqType().name());
processCommitReturn(reply.getContent());
}
else
{
Log.getLogger().info("Receiving other type of request." + reply.getReqType().name());
}
pool.release(kryo);
super.replyReceived(reply);
}
/**
* Processes the return of a read request. Filling the readsets.
* @param input the received bytes in an input..
*/
private void processReadReturn(final Input input)
{
if(input == null)
{
Log.getLogger().warn("TimeOut, Didn't receive an answer from the server!");
return;
}
Log.getLogger().info("Process read return!");
final KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
final Kryo kryo = pool.borrow();
final String result = kryo.readObject(input, String.class);
this.localTimestamp = kryo.readObject(input, Long.class);
if(Constants.ABORT.equals(result))
{
input.close();
pool.release(kryo);
resetSets();
readQueue.add(FINISHED_READING);
return;
}
final List nodes = kryo.readObject(input, ArrayList.class);
final List relationships = kryo.readObject(input, ArrayList.class);
if(nodes != null && !nodes.isEmpty() && nodes.get(0) instanceof NodeStorage)
{
for (final NodeStorage storage : (ArrayList<NodeStorage>) nodes)
{
final NodeStorage tempStorage = new NodeStorage(storage.getId(), storage.getProperties());
try
{
tempStorage.addProperty("hash", HashCreator.sha1FromNode(storage));
}
catch (NoSuchAlgorithmException e)
{
Log.getLogger().warn("Couldn't add hash for node", e);
}
readsSetNode.add(tempStorage);
}
}
if(relationships != null && !relationships.isEmpty() && relationships.get(0) instanceof RelationshipStorage)
{
for (final RelationshipStorage storage : (ArrayList<RelationshipStorage>)relationships)
{
final RelationshipStorage tempStorage = new RelationshipStorage(storage.getId(), storage.getProperties(), storage.getStartNode(), storage.getEndNode());
try
{
tempStorage.addProperty("hash", HashCreator.sha1FromRelationship(storage));
}
catch (NoSuchAlgorithmException e)
{
Log.getLogger().warn("Couldn't add hash for relationship", e);
}
readsSetRelationship.add(tempStorage);
}
}
readQueue.add(FINISHED_READING);
input.close();
pool.release(kryo);
}
private void processCommitReturn(final byte[] result)
{
final KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
final Kryo kryo = pool.borrow();
if(result == null)
{
Log.getLogger().warn("Server returned null, something went incredibly wrong there");
return;
}
final Input input = new Input(result);
final String type = kryo.readObject(input, String.class);
if(!Constants.COMMIT_RESPONSE.equals(type))
{
Log.getLogger().warn("Incorrect response to commit message");
input.close();
return;
}
final String decision = kryo.readObject(input, String.class);
localTimestamp = kryo.readObject(input, Long.class);
Log.getLogger().info("Processing commit return: " + localTimestamp);
if(Constants.COMMIT.equals(decision))
{
Log.getLogger().info("Transaction succesfully committed");
}
else
{
Log.getLogger().info("Transaction commit denied - transaction being aborted");
}
Log.getLogger().info("Reset after commit");
resetSets();
input.close();
pool.release(kryo);
}
/**
* Commit reaches the server, if secure commit send to all, else only send to one
*/
@Override
public void commit()
{
firstRead = true;
final boolean readOnly = isReadOnly();
Log.getLogger().info("Starting commit");
if (readOnly && !secureMode)
{
//verifyReadSet();
Log.getLogger().warn(String.format("Read only unsecure Transaction with local transaction id: %d successfully committed", localTimestamp));
firstRead = true;
resetSets();
return;
}
Log.getLogger().info("Starting commit process for: " + this.localTimestamp);
final byte[] bytes = serializeAll();
if (readOnly)
{
final KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
final Kryo kryo = pool.borrow();
Log.getLogger().warn(getProcessId() + " Commit with snapshotId: " + this.localTimestamp);
final byte[] answer;
if(localClusterId == -1)
{
//List of all view processes
/*final int[] currentViewProcesses = this.getViewManager().getCurrentViewProcesses();
//The servers we will actually contact
final int[] servers = new int[3];
//final int spare = servers[new Random().nextInt(currentViewProcesses.length)];
int i = 0;
for(final int processI : currentViewProcesses)
{
if(i < servers.length)
{
servers[i] = processI;
i++;
}
}
isCommitting = true;
Log.getLogger().info("Sending to: " + Arrays.toString(servers));
//sendMessageToTargets(bytes, 0, servers, TOMMessageType.UNORDERED_REQUEST);*/
answer = invokeUnordered(bytes);
}
else
{
answer = globalProxy.invokeUnordered(bytes);
}
Log.getLogger().info(getProcessId() + "Committed with snapshotId " + this.localTimestamp);
final Input input = new Input(answer);
final String messageType = kryo.readObject(input, String.class);
if (!Constants.COMMIT_RESPONSE.equals(messageType))
{
Log.getLogger().warn("Incorrect response type to client from server!" + getProcessId());
resetSets();
firstRead = true;
return;
}
final boolean commit = Constants.COMMIT.equals(kryo.readObject(input, String.class));
if (commit)
{
localTimestamp = kryo.readObject(input, Long.class);
resetSets();
firstRead = true;
Log.getLogger().info(String.format("Transaction with local transaction id: %d successfully committed", localTimestamp));
return;
}
return;
}
if (localClusterId == -1)
{
Log.getLogger().info("Distribute commit with snapshotId: " + this.localTimestamp);
this.invokeOrdered(bytes);
}
else
{
Log.getLogger().info("Commit with snapshotId directly to global cluster. TimestampId: " + this.localTimestamp);
Log.getLogger().info("WriteSet: " + writeSet.size() + " readSetNode: " + readsSetNode.size() + " readSetRs: " + readsSetRelationship.size());
processCommitReturn(globalProxy.invokeOrdered(bytes));
}
}
/**
* Method verifies readSet signatures.
*/
private void verifyReadSet()
{
final KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
final Kryo kryo = pool.borrow();
for(final NodeStorage storage: readsSetNode)
{
for(final Map.Entry<String, Object> entry: storage.getProperties().entrySet())
{
if(!entry.getKey().contains("signature"))
{
continue;
}
final int key = Integer.parseInt(entry.getKey().replace("signature",""));
Log.getLogger().warn("Verifying the keys of the nodes");
final RSAKeyLoader rsaLoader = new RSAKeyLoader(key, GLOBAL_CONFIG_LOCATION, false);
try
{
if (!TOMUtil.verifySignature(rsaLoader.loadPublicKey(), storage.getBytes(), ((String) entry.getValue()).getBytes("UTF-8")))
{
Log.getLogger().warn("Signature of server: " + key + " doesn't match");
}
else
{
Log.getLogger().info("Signature matches of server: " + entry.getKey());
}
}
catch (final Exception e)
{
Log.getLogger().error("Unable to load public key on client", e);
}
}
}
Log.getLogger().warn("Verifying the keys of the relationships");
for(final RelationshipStorage storage: readsSetRelationship)
{
for(final Map.Entry<String, Object> entry: storage.getProperties().entrySet())
{
if(!entry.getKey().contains("signature"))
{
continue;
}
final int key = Integer.parseInt(entry.getKey().replace("signature",""));
Log.getLogger().warn("Verifying the keys of the nodes");
final RSAKeyLoader rsaLoader = new RSAKeyLoader(key, GLOBAL_CONFIG_LOCATION, false);
try
{
if (!TOMUtil.verifySignature(rsaLoader.loadPublicKey(), storage.getBytes(), ((String) entry.getValue()).getBytes("UTF-8")))
{
Log.getLogger().warn("Signature of server: " + key + " doesn't match");
}
else
{
Log.getLogger().info("Signature matches of server: " + entry.getKey());
}
}
catch (final Exception e)
{
Log.getLogger().error("Unable to load public key on client", e);
}
}
}
pool.release(kryo);
}
/**
* Serializes the data and returns it in byte format.
* @return the data in byte format.
*/
private byte[] serialize(@NotNull String request)
{
KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
Kryo kryo = pool.borrow();
Output output = new Output(0, 256);
kryo.writeObject(output, request);
byte[] bytes = output.getBuffer();
output.close();
pool.release(kryo);
return bytes;
}
/**
* Serializes the data and returns it in byte format.
* @return the data in byte format.
*/
private byte[] serialize(@NotNull String reason, long localTimestamp, final Object...args)
{
final KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
final Kryo kryo = pool.borrow();
final Output output = new Output(0, 100024);
kryo.writeObject(output, reason);
kryo.writeObject(output, localTimestamp);
for(final Object identifier: args)
{
if(identifier instanceof NodeStorage || identifier instanceof RelationshipStorage)
{
kryo.writeObject(output, identifier);
}
}
byte[] bytes = output.getBuffer();
output.close();
pool.release(kryo);
return bytes;
}
/**
* Serializes all sets and returns it in byte format.
* @return the data in byte format.
*/
private byte[] serializeAll()
{
final KryoPool pool = new KryoPool.Builder(factory).softReferences().build();
final Kryo kryo = pool.borrow();
final Output output = new Output(0, 400024);
kryo.writeObject(output, Constants.COMMIT_MESSAGE);
//Write the timeStamp to the server
kryo.writeObject(output, localTimestamp);
//Write the readSet.
kryo.writeObject(output, readsSetNode);
kryo.writeObject(output, readsSetRelationship);
//Write the writeSet.
kryo.writeObject(output, writeSet);
byte[] bytes = output.getBuffer();
output.close();
pool.release(kryo);
return bytes;
}
/**
* Resets all the read and write sets.
*/
private void resetSets()
{
readsSetNode = new ArrayList<>();
readsSetRelationship = new ArrayList<>();
writeSet = new ArrayList<>();
isCommitting = false;
responses = 0;
final Random random = new Random();
int randomNumber = random.nextInt(1000);
if(randomNumber <= 650)
{
serverProcess = 0;
return;
}
serverProcess = 1;
}
/**
* Checks if the transaction has made any changes to the update sets.
* @return true if not.
*/
private boolean isReadOnly()
{
return writeSet.isEmpty();
}
@Override
public boolean isCommitting()
{
return isCommitting;
}
/**
* Get the primary of the cluster.
* @param kryo the kryo instance.
* @return the primary id.
*/
private int getPrimary(final Kryo kryo)
{
byte[] response = invoke(serialize(Constants.GET_PRIMARY), TOMMessageType.UNORDERED_REQUEST);
if(response == null)
{
Log.getLogger().warn("Server returned null, something went incredibly wrong there");
return -1;
}
final Input input = new Input(response);
kryo.readObject(input, String.class);
final int primaryId = kryo.readObject(input, Integer.class);
Log.getLogger().info("Received id: " + primaryId);
input.close();
return primaryId;
}
} |
package mpei.bkm.protegeplugin.menu;
import mpei.bkm.converters.UnconvertableException;
import mpei.bkm.converters.text2scheme.Text2SchemeContainerConverter;
import mpei.bkm.model.lss.Attribute;
import mpei.bkm.model.lss.datatypespecification.datatypes.*;
import mpei.bkm.model.lss.objectspecification.concept.BKMClass;
import mpei.bkm.model.lss.objectspecification.concept.BinaryLink;
import mpei.bkm.model.lss.objectspecification.concept.Concept;
import mpei.bkm.model.lss.objectspecification.concepttypes.BKMClassType;
import mpei.bkm.model.lss.objectspecification.concepttypes.ConceptType;
import mpei.bkm.model.lss.objectspecification.concepttypes.StarConceptType;
import mpei.bkm.model.lss.objectspecification.concepttypes.UnionConceptType;
import mpei.bkm.model.lss.objectspecification.intervalrestrictions.AtomRestriction;
import mpei.bkm.model.lss.objectspecification.intervalrestrictions.number.*;
import mpei.bkm.parsing.structurescheme.SchemeContainer;
import org.protege.editor.core.ui.util.UIUtil;
import org.protege.editor.owl.OWLEditorKit;
import org.protege.editor.owl.model.event.EventType;
import org.protege.editor.owl.ui.action.ProtegeOWLAction;
import org.semanticweb.owlapi.model.*;
import uk.ac.manchester.cs.owl.owlapi.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class BKMMenu extends ProtegeOWLAction {
private static final long serialVersionUID = 2452385628012488946L;
private OWLEditorKit editorKit;
public void initialise() throws Exception {
editorKit = getOWLEditorKit();
}
public void dispose() throws Exception {
}
static Map<PrimitiveDataType.PRIMITIVEDATATYPE,IRI> bkmPrimitiveMap = new HashMap<PrimitiveDataType.PRIMITIVEDATATYPE, IRI>();
static {
bkmPrimitiveMap.put(PrimitiveDataType.PRIMITIVEDATATYPE.String,IRI.create("http://www.w3.org/2001/XMLSchema#string"));
bkmPrimitiveMap.put(PrimitiveDataType.PRIMITIVEDATATYPE.Integer,IRI.create("http://www.w3.org/2001/XMLSchema#integer"));
bkmPrimitiveMap.put(PrimitiveDataType.PRIMITIVEDATATYPE.Boolean,IRI.create("http://www.w3.org/2001/XMLSchema#boolean"));
bkmPrimitiveMap.put(PrimitiveDataType.PRIMITIVEDATATYPE.Number,IRI.create("http://www.w3.org/2001/XMLSchema#float"));
bkmPrimitiveMap.put(PrimitiveDataType.PRIMITIVEDATATYPE.Char,IRI.create("http://www.w3.org/2001/XMLSchema#string"));
}
public void loadIntoOntology(OWLOntology owlOntology, SchemeContainer schemeContainer) {
List<OWLClass> owlClassList = new ArrayList<OWLClass>();
List<OWLAxiom> owlAxioms = new ArrayList<OWLAxiom>();
Map<OWLObjectProperty,String> classRangesToAdd = new HashMap<OWLObjectProperty, String>();
Map<OWLObjectProperty,List<String>> unionClasses = new HashMap<OWLObjectProperty, List<String>>();
Map<String, OWLClass> nameClassMapping = new HashMap<String, OWLClass>();
Map<OWLClass, List> exactRestrictions = new HashMap<OWLClass,List>();
Set<List> linkIntervalRestrictions = new HashSet<List>();
for (Concept concept : schemeContainer.getScheme().getConceptSet()) {
OWLClass owlClass = new OWLClassImpl(IRI.create("#" + concept.getName()));
nameClassMapping.put(concept.getName(), owlClass);
owlAxioms.add(new OWLDeclarationAxiomImpl(
owlClass,Collections.EMPTY_SET
));
owlClassList.add(owlClass);
exactRestrictions.put(owlClass, new ArrayList());
if (concept instanceof BinaryLink) {
BinaryLink link = (BinaryLink)concept;
String leftName = link.getLeft().getConceptAttribute().getName();
OWLObjectProperty left = new OWLObjectPropertyImpl(
IRI.create("#" + link.getName() + "_" + leftName)
);
linkIntervalRestrictions.add(Arrays.asList(owlClass, left, link.getRestriction().getLeft(), leftName));
owlAxioms.add(new OWLDeclarationAxiomImpl(left,Collections.EMPTY_SET));
String rightName = link.getRight().getConceptAttribute().getName();
OWLObjectProperty right = new OWLObjectPropertyImpl(
IRI.create("#" + link.getName() + "_" + rightName)
);
owlAxioms.add(new OWLDeclarationAxiomImpl(right, Collections.EMPTY_SET));
owlAxioms.add(new OWLObjectPropertyDomainAxiomImpl(
left,
owlClass,
Collections.EMPTY_SET));
owlAxioms.add(new OWLObjectPropertyDomainAxiomImpl(
right,
owlClass,
Collections.EMPTY_SET));
linkIntervalRestrictions.add(Arrays.asList(owlClass, right, link.getRestriction().getRight(), rightName));
}
for (Attribute attribute : concept.getAttributes()) {
if (attribute.getType() instanceof DataType) {
OWLDataProperty owlProperty = new OWLDataPropertyImpl(
IRI.create("#" + concept.getName() + "_" + attribute.getName())
);
owlAxioms.add(new OWLDeclarationAxiomImpl(
owlProperty,Collections.EMPTY_SET
));
owlAxioms.add(new OWLDataPropertyDomainAxiomImpl(
owlProperty,
owlClass,
Collections.EMPTY_SET));
if (attribute.getType() instanceof PrimitiveDataType) {
PrimitiveDataType.PRIMITIVEDATATYPE t = ((PrimitiveDataType) attribute.getType()).getType();
OWLDatatype type = new OWLDatatypeImpl(bkmPrimitiveMap.get(t));
owlAxioms.add(new OWLDataPropertyRangeAxiomImpl(
owlProperty,
type,
Collections.EMPTY_SET));
exactRestrictions.get(owlClass).addAll(Arrays.asList(owlProperty, type));
}
if (attribute.getType() instanceof StarDataType &&
((StarDataType) attribute.getType()).getType() instanceof PrimitiveDataType) {
PrimitiveDataType.PRIMITIVEDATATYPE t = ((PrimitiveDataType)((StarDataType) attribute.getType()).getType()).getType();
OWLDatatype type = new OWLDatatypeImpl(bkmPrimitiveMap.get(t));
owlAxioms.add(new OWLDataPropertyRangeAxiomImpl(
owlProperty,
type,
Collections.EMPTY_SET));
}
if (attribute.getType() instanceof EnumType) {
Set<OWLLiteral> enums = new HashSet<OWLLiteral>();
OWLDatatype stringType = new OWLDatatypeImpl(bkmPrimitiveMap.get(PrimitiveDataType.PRIMITIVEDATATYPE.String));
for (String value : ((EnumType) attribute.getType()).getValues()) {
enums.add(new OWLLiteralImpl(value,null,stringType));
}
owlAxioms.add(new OWLDataPropertyRangeAxiomImpl(
owlProperty,
new OWLDataOneOfImpl(enums),
Collections.EMPTY_SET));
}
if (attribute.getType() instanceof UnionDataType) {
DataType leftDataType = ((UnionDataType) attribute.getType()).getLeft();
DataType rightDataType = ((UnionDataType) attribute.getType()).getRight();
if (leftDataType instanceof PrimitiveDataType && rightDataType instanceof PrimitiveDataType) {
PrimitiveDataType.PRIMITIVEDATATYPE left = ((PrimitiveDataType) leftDataType).getType();
PrimitiveDataType.PRIMITIVEDATATYPE right = ((PrimitiveDataType) rightDataType).getType();
OWLDataUnionOf owlDataUnionOf = new OWLDataUnionOfImpl(
new HashSet<OWLDataRange>(Arrays.asList(
new OWLDatatypeImpl(bkmPrimitiveMap.get(left)),
new OWLDatatypeImpl(bkmPrimitiveMap.get(right)))
));
owlAxioms.add(new OWLDataPropertyRangeAxiomImpl(
owlProperty,
owlDataUnionOf,
Collections.EMPTY_SET));
}
}
}
if (attribute.getType() instanceof ConceptType) {
OWLObjectProperty owlProperty = new OWLObjectPropertyImpl(
IRI.create("#" + concept.getName() + "_" + attribute.getName())
);
owlAxioms.add(new OWLDeclarationAxiomImpl(
owlProperty, Collections.EMPTY_SET
));
owlAxioms.add(new OWLObjectPropertyDomainAxiomImpl(
owlProperty,
owlClass,
Collections.EMPTY_SET));
if (attribute.getType() instanceof BKMClassType) {
classRangesToAdd.put(owlProperty, ((BKMClassType) attribute.getType()).getBKMClass().getName());
exactRestrictions.get(owlClass).addAll(Arrays.asList(owlProperty, ((BKMClassType) attribute.getType()).getBKMClass().getName()));
}
if (attribute.getType() instanceof StarConceptType &&
((StarConceptType)attribute.getType()).getType() instanceof BKMClassType) {
classRangesToAdd.put(owlProperty, ((BKMClassType) ((StarConceptType) attribute.getType()).getType()).getBKMClass().getName());
}
if (attribute.getType() instanceof UnionConceptType) {
ConceptType leftConceptType = ((UnionConceptType) attribute.getType()).getLeft();
ConceptType rightConceptType = ((UnionConceptType) attribute.getType()).getRight();
if (leftConceptType instanceof BKMClassType && rightConceptType instanceof BKMClassType) {
unionClasses.put(owlProperty, Arrays.asList(
((BKMClassType) leftConceptType).getBKMClass().getName(),
((BKMClassType) rightConceptType).getBKMClass().getName())
);
}
}
}
}
}
owlAxioms.add(new OWLDisjointClassesAxiomImpl(new HashSet<OWLClassExpression>(owlClassList),Collections.EMPTY_SET));
for (BKMClass bkmClass : schemeContainer.getCollections().allDeclaredBKMClasses) {
OWLClass subOwlClass = nameClassMapping.get(bkmClass);
if (bkmClass.getIsa() != null) {
OWLClass superOwlClass = nameClassMapping.get(bkmClass.getIsa().getName());
owlAxioms.add(new OWLSubClassOfAxiomImpl(subOwlClass,superOwlClass,Collections.EMPTY_SET));
}
}
for (Map.Entry<OWLObjectProperty, String> e : classRangesToAdd.entrySet()) {
OWLClass owlClass = nameClassMapping.get(e.getValue());
if (owlClass != null && owlClass.getIRI().getFragment().equals(e.getValue())) {
owlAxioms.add(new OWLObjectPropertyRangeAxiomImpl(
e.getKey(),
owlClass,
Collections.EMPTY_SET));
}
}
E: for(Map.Entry<OWLClass,List> e: exactRestrictions.entrySet()) {
if (e.getValue().size() < 2) {
continue;
}
Set<OWLClassExpression> equiProps = new HashSet<OWLClassExpression>();
equiProps.add(e.getKey());
Set<OWLClassExpression> propertyCardinalities = new HashSet<OWLClassExpression>();
for (int i = 0; i <= (e.getValue()).size() / 2; i+=2) {
// i: property
// i + 1:class name
if (e.getValue().get(i+1) instanceof String) {
OWLObjectProperty ope = (OWLObjectProperty) e.getValue().get(i);
OWLClass owlClass = nameClassMapping.get(e.getValue().get(i+1));
if (owlClass == null) {
continue E;
}
propertyCardinalities.add(new OWLObjectExactCardinalityImpl(ope, 1, owlClass));
}
else {
OWLDataProperty ope = (OWLDataProperty) e.getValue().get(i);
OWLDatatype type = (OWLDatatype) e.getValue().get(i + 1);
propertyCardinalities.add(new OWLDataExactCardinalityImpl(ope, 1, type));
}
}
equiProps.add(new OWLObjectIntersectionOfImpl(propertyCardinalities));
owlAxioms.add(new OWLEquivalentClassesAxiomImpl(equiProps, Collections.EMPTY_SET));
}
for(List e: linkIntervalRestrictions) {
if (e.size() < 4)
continue;
// 0: owl class (BKM link)
// 1: property
// 2: BKM Interval restriction
// 3: class name
Set<OWLClassExpression> equiProps = new HashSet<OWLClassExpression>();
equiProps.add((OWLClassExpression) e.get(0));
Set<OWLClassExpression> propertyCardinalities = new HashSet<OWLClassExpression>();
OWLObjectProperty ope = (OWLObjectProperty) e.get(1);
OWLClass owlClass = nameClassMapping.get(e.get(3));
if (owlClass == null)
continue;
AtomRestriction atomRestriction = (AtomRestriction) e.get(2);
Integer min = null, max = null;
if (atomRestriction instanceof IntervalAtomRestriction) {
min = ((IntervalAtomRestriction)atomRestriction).getFrom();
max = ((IntervalAtomRestriction)atomRestriction).getTo();
}
else if (atomRestriction instanceof GTAtomRestriction) {
min = ((GTAtomRestriction)atomRestriction).getValue() + 1;
}
else if (atomRestriction instanceof GEAtomRestriction) {
min = ((GEAtomRestriction)atomRestriction).getValue();
}
else if (atomRestriction instanceof LTAtomRestriction) {
max = ((LTAtomRestriction)atomRestriction).getValue() - 1;
}
else if (atomRestriction instanceof LEAtomRestriction) {
max = ((LEAtomRestriction)atomRestriction).getValue();
}
else if (atomRestriction instanceof EQAtomRestriction) {
Integer exact = ((EQAtomRestriction)atomRestriction).getValue();
propertyCardinalities.add(new OWLObjectExactCardinalityImpl(ope, exact, owlClass));
}
if (min != null) {
propertyCardinalities.add(new OWLObjectMinCardinalityImpl(ope, min, owlClass));
}
if (max != null) {
propertyCardinalities.add(new OWLObjectMaxCardinalityImpl(ope, max, owlClass));
}
if (propertyCardinalities.size() > 0) {
equiProps.addAll(propertyCardinalities);
owlAxioms.add(new OWLEquivalentClassesAxiomImpl(equiProps, Collections.EMPTY_SET));
}
}
U: for (Map.Entry<OWLObjectProperty, List<String>> e : unionClasses.entrySet()) {
Set<OWLClass> unionOfOWLClasses = new HashSet<OWLClass>();
for (String bkmClassName : e.getValue()) {
OWLClass owlClass = nameClassMapping.get(bkmClassName);
if (owlClass == null)
continue U;
unionOfOWLClasses.add(owlClass);
}
OWLObjectUnionOf owlObjectUnionOf = new OWLObjectUnionOfImpl(unionOfOWLClasses);
owlAxioms.add(new OWLObjectPropertyRangeAxiomImpl(
(OWLObjectPropertyExpression) e.getKey(),
owlObjectUnionOf,
Collections.EMPTY_SET
));
}
for (OWLAxiom owlAxiom : owlAxioms) {
getOWLModelManager().applyChange(new AddAxiom(owlOntology,owlAxiom));
}
getOWLModelManager().fireEvent(EventType.ONTOLOGY_CREATED);
getOWLModelManager().fireEvent(EventType.ACTIVE_ONTOLOGY_CHANGED);
}
public void actionPerformed(ActionEvent arg0) {
try {
//getOWLModelManager().setLoadErrorHandler();
File file = UIUtil.openFile(new JDialog(), "Open BKM file", "Open BKM file", new HashSet<String>(Arrays.asList("bkm")));
if (file != null) {
try {
translateBKMFile(file);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
}
}
private void translateBKMFile(File file) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(file));
String line;
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null) {
sb.append(line);
}
Text2SchemeContainerConverter converter = new Text2SchemeContainerConverter();
SchemeContainer schemeContainer = converter.convert(sb.toString());
String errors = null;
String incompleteness = null;
if (converter.getErrors().size() > 0) {
errors = "Found errors:\n" + String.join("\n", converter.getErrors());
}
if (converter.getIncompleteness().size() > 0) {
incompleteness = "Found incompleteness:\n" + String.join("\n", converter.getIncompleteness());
}
if (errors != null || incompleteness != null) {
if (errors == null) {
errors = incompleteness;
}
else if (incompleteness != null) {
errors += incompleteness;
}
errors += "\nTry to convert to OWL anyway?";
String[] options = {"Yes", "No"};
int continueAnswer = JOptionPane.showOptionDialog(new JDialog(), errors, "Errors and incompleteness",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE,
null,
options,
options[1]
);
if (continueAnswer == JOptionPane.NO_OPTION) {
return;
}
}
IRI filiIRI = IRI.create(("http:
System.getProperty("user.name") + "/" +
schemeContainer.getScheme().getName()).replace(" ", "_"));
OWLOntologyID bkm2OWLOntologyID = new OWLOntologyID(filiIRI);
for (OWLOntology owlOntology : getOWLModelManager().getOntologies()) {
if (bkm2OWLOntologyID.equals(owlOntology.getOntologyID())) {
getOWLModelManager().removeOntology(owlOntology);
}
}
OWLOntology owlOntology = getOWLModelManager().createNewOntology(
bkm2OWLOntologyID,
filiIRI.toURI());
loadIntoOntology(owlOntology, schemeContainer);
} catch (IOException e) {
JOptionPane.showMessageDialog(new JDialog(), e.getMessage(), "Error when reading BKM file.", JOptionPane.ERROR_MESSAGE);
} catch (UnconvertableException e) {
JOptionPane.showMessageDialog(new JDialog(), e.getMessage(), "Error when translating BKM file.", JOptionPane.ERROR_MESSAGE);
} catch (OWLOntologyCreationException e) {
JOptionPane.showMessageDialog(new JDialog(), e.getMessage(), "Error when creating OWL ontology from BKM file.", JOptionPane.ERROR_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(new JDialog(), "Unknown error when reading BKM file.", "Error when reading BKM file.", JOptionPane.ERROR_MESSAGE);
}
/*
final OWLOntology currentOntology = getOWLModelManager().getActiveOntology();
final OWLWorkspace editorWindow = editorKit.getOWLWorkspace();
JDialog cellfieDialog = WorkspacePanel.createDialog(currentOntology, workbookPath, editorKit, dialogManager);
cellfieDialog.setLocationRelativeTo(editorWindow);
cellfieDialog.setVisible(true);
*/
}
} |
package net.gtaun.wl.gamemode;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import net.gtaun.shoebill.common.AbstractShoebillContext;
import net.gtaun.shoebill.common.dialog.AbstractDialog;
import net.gtaun.shoebill.constant.PlayerKey;
import net.gtaun.shoebill.constant.WeaponModel;
import net.gtaun.shoebill.data.Color;
import net.gtaun.shoebill.data.Vector3D;
import net.gtaun.shoebill.event.player.PlayerCommandEvent;
import net.gtaun.shoebill.event.player.PlayerConnectEvent;
import net.gtaun.shoebill.event.player.PlayerDeathEvent;
import net.gtaun.shoebill.event.player.PlayerDisconnectEvent;
import net.gtaun.shoebill.event.player.PlayerKeyStateChangeEvent;
import net.gtaun.shoebill.event.player.PlayerRequestClassEvent;
import net.gtaun.shoebill.event.player.PlayerSpawnEvent;
import net.gtaun.shoebill.object.Player;
import net.gtaun.shoebill.object.PlayerKeyState;
import net.gtaun.shoebill.service.Service;
import net.gtaun.util.event.EventManager;
import net.gtaun.util.event.HandlerPriority;
import net.gtaun.wl.common.dialog.WlListDialog;
import net.gtaun.wl.gamemode.event.GameListDialogExtendEvent;
import net.gtaun.wl.gamemode.event.MainMenuDialogExtendEvent;
import net.gtaun.wl.lang.LanguageService;
import org.apache.commons.lang3.math.NumberUtils;
public class PlayerHandler extends AbstractShoebillContext
{
private static final Vector3D[] RANDOM_SPAWN_POS =
{
new Vector3D(1958.3783f, 1343.1572f, 15.3746f),
new Vector3D(2199.6531f, 1393.3678f, 10.8203f),
new Vector3D(2483.5977f, 1222.0825f, 10.8203f),
new Vector3D(2637.2712f, 1129.2743f, 11.1797f),
new Vector3D(2000.0106f, 1521.1111f, 17.0625f),
new Vector3D(2024.8190f, 1917.9425f, 12.3386f),
new Vector3D(2261.9048f, 2035.9547f, 10.8203f),
new Vector3D(2262.0986f, 2398.6572f, 10.8203f),
new Vector3D(2244.2566f, 2523.7280f, 10.8203f),
new Vector3D(2335.3228f, 2786.4478f, 10.8203f),
new Vector3D(2150.0186f, 2734.2297f, 11.1763f),
new Vector3D(2158.0811f, 2797.5488f, 10.8203f),
new Vector3D(1969.8301f, 2722.8564f, 10.8203f),
new Vector3D(1652.0555f, 2709.4072f, 10.8265f),
new Vector3D(1564.0052f, 2756.9463f, 10.8203f),
new Vector3D(1271.5452f, 2554.0227f, 10.8203f),
new Vector3D(1441.5894f, 2567.9099f, 10.8203f),
new Vector3D(1480.6473f, 2213.5718f, 11.0234f),
new Vector3D(1400.5906f, 2225.6960f, 11.0234f),
new Vector3D(1598.8419f, 2221.5676f, 11.0625f),
new Vector3D(1318.7759f, 1251.3580f, 10.8203f),
new Vector3D(1558.0731f, 1007.8292f, 10.8125f),
new Vector3D(-857.0551f, 1536.6832f, 22.5870f), // Out of Town Spawns
new Vector3D(817.3494f, 856.5039f, 12.7891f),
new Vector3D(116.9315f, 1110.1823f, 13.6094f),
new Vector3D(-18.8529f, 1176.0159f, 19.5634f),
new Vector3D(-315.0575f, 1774.0636f, 43.6406f),
new Vector3D(1705.2347f, 1025.6808f, 10.8203f)
};
private Random random;
public PlayerHandler(EventManager rootEventManager)
{
super(rootEventManager);
random = new Random();
init();
}
@Override
protected void onInit()
{
eventManagerNode.registerHandler(PlayerConnectEvent.class, (e) ->
{
Player player = e.getPlayer();
Color color = new Color(random.nextInt() << 8 | 0xFF);
while (color.getY()<128) color = new Color(random.nextInt() << 8 | 0xFF);
player.setColor(color);
player.sendGameText(5000, 5, "Welcome to ~r~The New WL-World~w~!!");
player.sendDeathMessage(null, WeaponModel.CONNECT);
LanguageService langService = Service.get(LanguageService.class);
langService.showLanguageSelectionDialog(player, (p, l) ->
{
player.sendMessage(Color.PURPLE, "");
});
});
eventManagerNode.registerHandler(PlayerDisconnectEvent.class, (e) ->
{
Player player = e.getPlayer();
player.sendDeathMessage(null, WeaponModel.DISCONNECT);
});
eventManagerNode.registerHandler(PlayerSpawnEvent.class, (e) ->
{
Player player = e.getPlayer();
player.toggleClock(false);
player.setTime(12, 0);
player.setWeather(0);
setRandomLocation(player);
});
eventManagerNode.registerHandler(PlayerDeathEvent.class, (e) ->
{
Player player = e.getPlayer();
Player killer = e.getKiller();
player.sendDeathMessage(killer, e.getReason());
});
eventManagerNode.registerHandler(PlayerRequestClassEvent.class, (e) ->
{
Player player = e.getPlayer();
setupForClassSelection(player);
});
eventManagerNode.registerHandler(PlayerKeyStateChangeEvent.class, HandlerPriority.HIGHEST, (e) ->
{
Player player = e.getPlayer();
PlayerKeyState keyState = player.getKeyState();
if (keyState.isAccurateKeyPressed(PlayerKey.NO))
{
showMainMenuDialog(player, null);
}
else if (keyState.isAccurateKeyPressed(PlayerKey.YES))
{
showGameListDialog(player, null);
}
});
eventManagerNode.registerHandler(PlayerCommandEvent.class, (e) ->
{
Player player = e.getPlayer();
String command = e.getCommand();
String[] splits = command.split(" ", 2);
String operation = splits[0].toLowerCase();
Queue<String> args = new LinkedList<>();
if (splits.length > 1)
{
String[] argsArray = splits[1].split(" ");
args.addAll(Arrays.asList(argsArray));
}
switch (operation)
{
case "/pos":
player.sendMessage(Color.WHITE, player.getLocation().toString());
break;
case "/tppos":
if (args.size() < 3)
{
player.sendMessage(Color.WHITE, "Usage: /tppos [x] [y] [z]");
e.setProcessed();
return;
}
float x = NumberUtils.toFloat(args.poll());
float y = NumberUtils.toFloat(args.poll());
float z = NumberUtils.toFloat(args.poll());
player.setLocation(x, y, z);
e.setProcessed();
return;
case "/world":
if (args.size() < 1)
{
player.sendMessage(Color.WHITE, "Usage: /world [id]");
e.setProcessed();
return;
}
int worldId = NumberUtils.toInt(args.poll());
player.setWorld(worldId);
e.setProcessed();
return;
case "/interior":
if (args.size() < 1)
{
player.sendMessage(Color.WHITE, "Usage: /interior [id]");
e.setProcessed();
return;
}
int interior = NumberUtils.toInt(args.poll());
player.setInterior(interior);
e.setProcessed();
return;
case "/kill":
player.setHealth(0.0f);
e.setProcessed();
return;
case "/codepage":
if (args.size() < 1)
{
player.sendMessage(Color.WHITE, "Usage: /codepage [val]");
e.setProcessed();
return;
}
int codepage = NumberUtils.toInt(args.poll());
player.setCodepage(codepage);
e.setProcessed();
return;
}
});
eventManagerNode.registerHandler(PlayerCommandEvent.class, HandlerPriority.BOTTOM, (e) ->
{
Player player = e.getPlayer();
player.sendMessage(Color.RED, "");
e.setProcessed();
});
}
@Override
protected void onDestroy()
{
}
public void showMainMenuDialog(Player player, AbstractDialog parentDialog)
{
if (parentDialog == null) player.playSound(1083);
WlListDialog mainDialog = WlListDialog.create(player, rootEventManager)
.caption(": ")
.build();
MainMenuDialogExtendEvent dialogExtendEvent = new MainMenuDialogExtendEvent(player, eventManagerNode, mainDialog);
eventManagerNode.dispatchEvent(dialogExtendEvent);
mainDialog.show();
}
public void showGameListDialog(Player player, AbstractDialog parentDialog)
{
if (parentDialog == null) player.playSound(1083);
WlListDialog mainDialog = WlListDialog.create(player, rootEventManager)
.caption(": ")
.build();
GameListDialogExtendEvent dialogShowEvent = new GameListDialogExtendEvent(player, eventManagerNode, mainDialog);
eventManagerNode.dispatchEvent(dialogShowEvent);
mainDialog.show();
}
private void setRandomLocation(Player player)
{
int rand = random.nextInt(RANDOM_SPAWN_POS.length);
player.setLocation(RANDOM_SPAWN_POS[rand]);
player.setInterior(0);
}
private void setupForClassSelection(Player player)
{
player.setInterior(14);
player.setLocation(258.4893f, -41.4008f, 1002.0234f);
player.setAngle(270.0f);
player.setCameraPosition(256.0815f, -43.0475f, 1004.0234f);
player.setCameraLookAt(258.4893f, -41.4008f, 1002.0234f);
}
} |
package net.malisis.core.block;
import java.util.List;
import net.malisis.core.MalisisCore;
import net.malisis.core.MalisisRegistry;
import net.malisis.core.renderer.MalisisRenderer;
import net.malisis.core.renderer.icon.metaprovider.IBlockMetaIconProvider;
import net.malisis.core.renderer.icon.provider.DefaultIconProvider;
import net.malisis.core.renderer.icon.provider.IBlockIconProvider;
import net.malisis.core.util.AABBUtils;
import net.malisis.core.util.RaytraceBlock;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.item.ItemBlock;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.BlockPos;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
/**
* @author Ordinastie
*
*/
public class MalisisBlock extends Block implements IBoundingBox, IBlockMetaIconProvider
{
protected String name;
protected AxisAlignedBB boundingBox;
protected IBlockIconProvider iconProvider;
protected MalisisBlock(Material material)
{
super(material);
}
public Block setName(String name)
{
this.name = name;
super.setUnlocalizedName(name);
return this;
}
@Override
public Block setUnlocalizedName(String name)
{
this.name = name;
super.setUnlocalizedName(name);
return this;
}
public String getName()
{
return name;
}
public void setTextureName(String textureName)
{
if (StringUtils.isEmpty(textureName))
return;
setBlockIconProvider(new DefaultIconProvider(textureName));
}
public void setBlockIconProvider(IBlockIconProvider iconProvider)
{
this.iconProvider = iconProvider;
}
@Override
public IBlockIconProvider getBlockIconProvider()
{
return iconProvider;
}
public void register()
{
register(ItemBlock.class);
}
public void register(Class<? extends ItemBlock> item)
{
GameRegistry.registerBlock(this, item, getName());
if (FMLCommonHandler.instance().getSide() == Side.CLIENT)
{
MalisisRegistry.registerIconProvider(iconProvider);
if (useDefaultRenderer())
MalisisRenderer.defaultRenderer.registerFor(this);
}
}
@Override
public AxisAlignedBB[] getBoundingBox(IBlockAccess world, BlockPos pos, BoundingBoxType type)
{
return new AxisAlignedBB[] { new AxisAlignedBB(minX, minY, minZ, maxX, maxY, maxZ) };
}
@Override
public void addCollisionBoxesToList(World world, BlockPos pos, IBlockState state, AxisAlignedBB mask, List list, Entity collidingEntity)
{
for (AxisAlignedBB aabb : AABBUtils.offset(pos, getBoundingBox(world, pos, BoundingBoxType.COLLISION)))
{
if (aabb != null && mask.intersectsWith(aabb))
list.add(aabb);
}
}
@Override
public MovingObjectPosition collisionRayTrace(World world, BlockPos pos, Vec3 src, Vec3 dest)
{
return RaytraceBlock.set(world, src, dest, pos).trace();
}
@Override
public AxisAlignedBB getSelectedBoundingBox(World world, BlockPos pos)
{
AxisAlignedBB[] aabbs = getBoundingBox(world, pos, BoundingBoxType.SELECTION);
if (ArrayUtils.isEmpty(aabbs) || aabbs[0] == null)
return AABBUtils.empty(pos);
return AABBUtils.offset(pos, aabbs)[0];
}
public boolean useDefaultRenderer()
{
return true;
}
@Override
public int getRenderType()
{
return MalisisCore.malisisRenderType;
}
} |
package net.onrc.onos.util;
import java.util.ArrayList;
import java.util.List;
import net.floodlightcontroller.core.INetMapTopologyObjects.IDeviceObject;
import net.floodlightcontroller.core.INetMapTopologyObjects.IFlowEntry;
import net.floodlightcontroller.core.INetMapTopologyObjects.IFlowPath;
import net.floodlightcontroller.core.INetMapTopologyObjects.IPortObject;
import net.floodlightcontroller.core.INetMapTopologyObjects.ISwitchObject;
import net.floodlightcontroller.core.ISwitchStorage.SwitchState;
import net.floodlightcontroller.util.FlowEntryId;
import net.floodlightcontroller.util.FlowId;
import com.thinkaurelius.titan.core.TitanGraph;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.frames.FramedGraph;
import com.tinkerpop.frames.structures.FramedVertexIterable;
import com.tinkerpop.gremlin.java.GremlinPipeline;
public class GraphDBOperation implements IDBOperation {
private GraphDBConnection conn;
public GraphDBOperation(GraphDBConnection dbConnection) {
this.conn = dbConnection;
}
@Override
public ISwitchObject newSwitch(String dpid) {
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
ISwitchObject obj = fg.addVertex(null,ISwitchObject.class);
if (obj != null) {
obj.setType("switch");
obj.setDPID(dpid);
}
return obj;
}
@Override
public ISwitchObject searchSwitch(String dpid) {
// TODO Auto-generated method stub
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
return (fg != null && fg.getVertices("dpid",dpid).iterator().hasNext()) ?
fg.getVertices("dpid",dpid,ISwitchObject.class).iterator().next() : null;
}
@Override
public ISwitchObject searchActiveSwitch(String dpid) {
ISwitchObject sw = searchSwitch(dpid);
if ((sw != null) &&
sw.getState().equals(SwitchState.ACTIVE.toString())) {
return sw;
}
return null;
}
@Override
public Iterable<ISwitchObject> getAllSwitches() {
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
Iterable<ISwitchObject> switches = fg.getVertices("type","switch",ISwitchObject.class);
return switches;
}
@Override
public Iterable<ISwitchObject> getActiveSwitches() {
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
Iterable<ISwitchObject> switches = fg.getVertices("type","switch",ISwitchObject.class);
List<ISwitchObject> activeSwitches = new ArrayList<ISwitchObject>();
for (ISwitchObject sw: switches) {
if(sw.getState().equals(SwitchState.ACTIVE.toString())) {
activeSwitches.add(sw);
}
}
return activeSwitches;
}
@Override
public Iterable<ISwitchObject> getInactiveSwitches() {
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
Iterable<ISwitchObject> switches = fg.getVertices("type","switch",ISwitchObject.class);
List<ISwitchObject> inactiveSwitches = new ArrayList<ISwitchObject>();
for (ISwitchObject sw: switches) {
if(sw.getState().equals(SwitchState.INACTIVE.toString())) {
inactiveSwitches.add(sw);
}
}
return inactiveSwitches;
}
@Override
public Iterable<IFlowEntry> getAllSwitchNotUpdatedFlowEntries() {
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
//TODO: Should use an enum for flow_switch_state
return fg.getVertices("switch_state", "FE_SWITCH_NOT_UPDATED", IFlowEntry.class);
}
@Override
public void removeSwitch(ISwitchObject sw) {
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
fg.removeVertex(sw.asVertex());
}
@Override
public IPortObject newPort(Short portNumber) {
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
IPortObject obj = fg.addVertex(null,IPortObject.class);
if (obj != null) {
obj.setType("port");
obj.setNumber(portNumber);
}
return obj;
}
@Override
public IPortObject searchPort(String dpid, short number) {
ISwitchObject sw = searchSwitch(dpid);
if (sw != null) {
IPortObject port = null;
// Requires Frames 2.3.0
try {
port = sw.getPort(number);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return port;
}
// if (sw != null) {
// GremlinPipeline<Vertex, IPortObject> pipe = new GremlinPipeline<Vertex, IPortObject>();
// pipe.start(sw.asVertex());
// pipe.out("on").has("number", number);
// FramedVertexIterable<IPortObject> r = new FramedVertexIterable<IPortObject>(conn.getFramedGraph(), (Iterable) pipe, IPortObject.class);
// return r != null && r.iterator().hasNext() ? r.iterator().next() : null;
return null;
}
@Override
public void removePort(IPortObject port) {
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
// EventGraph<TitanGraph> eg = conn.getEventGraph();
if (fg != null) fg.removeVertex(port.asVertex());
}
@Override
public IDeviceObject newDevice() {
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
IDeviceObject obj = fg.addVertex(null,IDeviceObject.class);
if (obj != null) obj.setType("device");
return obj;
}
@Override
public IDeviceObject searchDevice(String macAddr) {
// TODO Auto-generated method stub
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
return (fg != null && fg.getVertices("dl_address",macAddr).iterator().hasNext()) ? fg.getVertices("dl_address",macAddr,
IDeviceObject.class).iterator().next() : null;
}
@Override
public Iterable<IDeviceObject> getDevices() {
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
return fg != null ? fg.getVertices("type","device",IDeviceObject.class) : null;
}
@Override
public void removeDevice(IDeviceObject dev) {
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
if (fg != null) fg.removeVertex(dev.asVertex());
}
@Override
public IFlowPath newFlowPath() {
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
IFlowPath flowPath = fg.addVertex(null, IFlowPath.class);
if (flowPath != null) flowPath.setType("flow");
return flowPath;
}
@Override
public IFlowPath searchFlowPath(FlowId flowId) {
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
return fg.getVertices("flow_id", flowId.toString()).iterator().hasNext() ?
fg.getVertices("flow_id", flowId.toString(),
IFlowPath.class).iterator().next() : null;
}
@Override
public IFlowPath getFlowPathByFlowEntry(IFlowEntry flowEntry) {
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
GremlinPipeline<Vertex, IFlowPath> pipe = new GremlinPipeline<Vertex, IFlowPath>();
pipe.start(flowEntry.asVertex());
pipe.out("flow");
FramedVertexIterable<IFlowPath> r = new FramedVertexIterable(conn.getFramedGraph(), (Iterable) pipe, IFlowPath.class);
return r.iterator().hasNext() ? r.iterator().next() : null;
}
@Override
public Iterable<IFlowPath> getAllFlowPaths() {
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
Iterable<IFlowPath> flowPaths = fg.getVertices("type", "flow", IFlowPath.class);
List<IFlowPath> nonNullFlows = new ArrayList<IFlowPath>();
for (IFlowPath fp: flowPaths) {
if (fp.getFlowId() != null) {
nonNullFlows.add(fp);
}
}
return nonNullFlows;
}
@Override
public void removeFlowPath(IFlowPath flowPath) {
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
fg.removeVertex(flowPath.asVertex());
}
@Override
public IFlowEntry newFlowEntry() {
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
IFlowEntry flowEntry = fg.addVertex(null, IFlowEntry.class);
if (flowEntry != null) flowEntry.setType("flow_entry");
return flowEntry;
}
@Override
public IFlowEntry searchFlowEntry(FlowEntryId flowEntryId) {
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
return fg.getVertices("flow_entry_id", flowEntryId.toString()).iterator().hasNext() ?
fg.getVertices("flow_entry_id", flowEntryId.toString(),
IFlowEntry.class).iterator().next() : null;
}
@Override
public Iterable<IFlowEntry> getAllFlowEntries() {
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
return fg.getVertices("type", "flow_entry", IFlowEntry.class);
}
@Override
public void removeFlowEntry(IFlowEntry flowEntry) {
FramedGraph<TitanGraph> fg = conn.getFramedGraph();
fg.removeVertex(flowEntry.asVertex());
}
} |
package net.sf.jabref.bst;
import java.util.Optional;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class BibtexCaseChanger {
private static final Log LOGGER = LogFactory.getLog(BibtexCaseChanger.class);
// stores whether the char before the current char was a colon
private boolean prevColon = true;
// global variable to store the current brace level
private int braceLevel;
public enum FORMAT_MODE {
// First character and character after a ":" as upper case - everything else in lower case. Obey {}.
TITLE_LOWERS('t'),
// All characters lower case - Obey {}
ALL_LOWERS('l'),
// all characters upper case - Obey {}
ALL_UPPERS('u');
// the following would have to be done if the functionality of CaseChangers would be included here
// However, we decided against it and will probably do the other way round: https://github.com/JabRef/jabref/pull/215#issuecomment-146981624
// Each word should start with a capital letter
//EACH_FIRST_UPPERS('f'),
// Converts all words to upper case, but converts articles, prepositions, and conjunctions to lower case
// Capitalizes first and last word
// Does not change words starting with "{"
// DIFFERENCE to old CaseChangers.TITLE: last word is NOT capitalized in all cases
//TITLE_UPPERS('T');
public char asChar() {
return asChar;
}
private final char asChar;
FORMAT_MODE(char asChar) {
this.asChar = asChar;
}
public static FORMAT_MODE getFormatModeForBSTFormat(final char bstFormat) {
for (FORMAT_MODE mode : FORMAT_MODE.values()) {
if (mode.asChar == bstFormat) {
return mode;
}
}
throw new IllegalArgumentException();
}
}
private BibtexCaseChanger() {
}
/**
* Changes case of the given string s
*
* @param s the string to handle
* @param format the format
* @return
*/
public static String changeCase(String s, FORMAT_MODE format) {
return (new BibtexCaseChanger()).doChangeCase(s, format);
}
private String doChangeCase(String s, FORMAT_MODE format) {
char[] c = s.toCharArray();
StringBuffer sb = new StringBuffer();
int i = 0;
int n = s.length();
while (i < n) {
if (c[i] == '{') {
braceLevel++;
if ((braceLevel != 1) || ((i + 4) > n) || (c[i + 1] != '\\')) {
prevColon = false;
sb.append(c[i]);
i++;
continue;
}
if ((format == FORMAT_MODE.TITLE_LOWERS) && ((i == 0) || (prevColon && Character.isWhitespace(c[i - 1])))) {
assert(c[i] == '{');
sb.append('{');
i++;
prevColon = false;
continue;
}
i = convertSpecialChar(sb, c, i, format);
continue;
}
if (c[i] == '}') {
sb.append(c[i]);
i++;
if (braceLevel == 0) {
LOGGER.warn("Too many closing braces in string: " + s);
} else {
braceLevel
}
prevColon = false;
continue;
}
if (braceLevel == 0) {
i = convertCharIfBraceLevelIsZero(c, i, sb, format);
continue;
}
sb.append(c[i]);
i++;
}
if (braceLevel > 0) {
LOGGER.warn("No enough closing braces in string: " + s);
}
return sb.toString();
}
/**
* We're dealing with a special character (usually either an undotted `\i'
* or `\j', or an accent like one in Table~3.1 of the \LaTeX\ manual, or a
* foreign character like one in Table~3.2) if the first character after the
* |left_brace| is a |backslash|; the special character ends with the
* matching |right_brace|. How we handle what's in between depends on the
* special character. In general, this code will do reasonably well if there
* is other stuff, too, between braces, but it doesn't try to do anything
* special with |colon|s.
*
* @param c
* @param i the current position. It points to the opening brace
* @param format
* @return
*/
private int convertSpecialChar(StringBuffer sb, char[] c, int i, FORMAT_MODE format) {
assert(c[i] == '{');
sb.append(c[i]);
i++; // skip over open brace
while ((i < c.length) && (braceLevel > 0)) {
sb.append(c[i]);
i++;
// skip over the |backslash|
Optional<String> s = BibtexCaseChanger.findSpecialChar(c, i);
if (s.isPresent()) {
i = convertAccented(c, i, s.get(), sb, format);
}
while ((i < c.length) && (braceLevel > 0) && (c[i] != '\\')) {
if (c[i] == '}') {
braceLevel
} else if (c[i] == '{') {
braceLevel++;
}
i = convertNonControl(c, i, sb, format);
}
}
return i;
}
/**
* Convert the given string according to the format character (title, lower,
* up) and append the result to the stringBuffer, return the updated
* position.
*
* @param c
* @param pos
* @param s
* @param sb
* @param format
* @return the new position
*/
private int convertAccented(char[] c, int pos, String s, StringBuffer sb, FORMAT_MODE format) {
pos += s.length();
switch (format) {
case TITLE_LOWERS:
case ALL_LOWERS:
if ("L O OE AE AA".contains(s)) {
sb.append(s.toLowerCase());
} else {
sb.append(s);
}
break;
case ALL_UPPERS:
if ("l o oe ae aa".contains(s)) {
sb.append(s.toUpperCase());
} else if ("i j ss".contains(s)) {
sb.deleteCharAt(sb.length() - 1); // Kill backslash
sb.append(s.toUpperCase());
while ((pos < c.length) && Character.isWhitespace(c[pos])) {
pos++;
}
} else {
sb.append(s);
}
break;
}
return pos;
}
private int convertNonControl(char[] c, int pos, StringBuffer sb, FORMAT_MODE format) {
switch (format) {
case TITLE_LOWERS:
case ALL_LOWERS:
sb.append(Character.toLowerCase(c[pos]));
pos++;
break;
case ALL_UPPERS:
sb.append(Character.toUpperCase(c[pos]));
pos++;
break;
}
return pos;
}
private int convertCharIfBraceLevelIsZero(char[] c, int i, StringBuffer sb, FORMAT_MODE format) {
switch (format) {
case TITLE_LOWERS:
if (i == 0) {
sb.append(c[i]);
} else if (prevColon && Character.isWhitespace(c[i - 1])) {
sb.append(c[i]);
} else {
sb.append(Character.toLowerCase(c[i]));
}
if (c[i] == ':') {
prevColon = true;
} else if (!Character.isWhitespace(c[i])) {
prevColon = false;
}
break;
case ALL_LOWERS:
sb.append(Character.toLowerCase(c[i]));
break;
case ALL_UPPERS:
sb.append(Character.toUpperCase(c[i]));
}
i++;
return i;
}
/**
* Determine whether there starts a special char at pos (e.g., oe, AE). Return it as string.
* If nothing found, return null
*
* Also used by BibtexPurify
*
* @param c the current "String"
* @param pos the position
* @return the special LaTeX character or null
*/
static Optional<String> findSpecialChar(char[] c, int pos) {
if ((pos + 1) < c.length) {
if ((c[pos] == 'o') && (c[pos + 1] == 'e')) {
return Optional.of("oe");
}
if ((c[pos] == 'O') && (c[pos + 1] == 'E')) {
return Optional.of("OE");
}
if ((c[pos] == 'a') && (c[pos + 1] == 'e')) {
return Optional.of("ae");
}
if ((c[pos] == 'A') && (c[pos + 1] == 'E')) {
return Optional.of("AE");
}
if ((c[pos] == 's') && (c[pos + 1] == 's')) {
return Optional.of("ss");
}
if ((c[pos] == 'A') && (c[pos + 1] == 'A')) {
return Optional.of("AA");
}
if ((c[pos] == 'a') && (c[pos + 1] == 'a')) {
return Optional.of("aa");
}
}
if ("ijoOlL".indexOf(c[pos]) >= 0) {
return Optional.of(String.valueOf(c[pos]));
}
return Optional.empty();
}
} |
package no.cantara.cs.health;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.URL;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Properties;
@Path(HealthResource.HEALTH_PATH)
public class HealthResource {
public static final String HEALTH_PATH = "/health";
private static final Logger log = LoggerFactory.getLogger(HealthResource.class);
private final static String MAVEN_ARTIFACT_ID = "configservice";
@GET
@Produces("application/json")
public Response healthCheck() {
String json = "{" +
"\"service\":\"" + MAVEN_ARTIFACT_ID
+ "\",\"timestamp\":\"" + Instant.now().toString()
+ "\",\"runningSince\":\"" + getRunningSince()
+ "\",\"version\":\"" + getVersion()
+ "\"}";
return Response.ok(json).build();
}
private String getRunningSince() {
long uptimeInMillis = ManagementFactory.getRuntimeMXBean().getUptime();
return Instant.now().minus(uptimeInMillis, ChronoUnit.MILLIS).toString();
}
private String getVersion() {
Properties mavenProperties = new Properties();
String resourcePath = "/META-INF/maven/no.cantara.jau/configservice/pom.properties";
URL mavenVersionResource = this.getClass().getResource(resourcePath);
if (mavenVersionResource != null) {
try {
mavenProperties.load(mavenVersionResource.openStream());
return mavenProperties.getProperty("version", "missing version info in " + resourcePath);
} catch (IOException e) {
log.warn("Problem reading version resource from classpath: ", e);
}
}
return "(DEV VERSION)";
}
} |
package org.animotron.statement.operator;
import org.animotron.io.Pipe;
import org.animotron.manipulator.OnQuestion;
import org.animotron.manipulator.PFlow;
import org.animotron.manipulator.QCAVector;
/**
* Operation 'AN'. Direct reference to 'the' instance.
*
* @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a>
* @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a>
*/
public class AN extends Operator implements Reference, Evaluable, Shift {
public static final AN _ = new AN();
private static boolean debug = false;
private AN() { super("an"); }
@Override
public OnQuestion onCalcQuestion() {
return question;
}
private OnQuestion question = new OnQuestion() {
@Override
public void act(final PFlow pf) {
byte[] hash = pf.getOpHash();
if (debug) System.out.println("AN "+Thread.currentThread());
//System.out.println("AN "+pf.getVector());
//pf.sendAnswer(new QCAVector(op,op));
if (!Utils.results(pf, hash)) {
Pipe pipe = getREFs(pf, pf.getVector());
QCAVector r;
while ((r = pipe.take()) != null) {
pf.sendAnswer(r);
}
}
}
};
public static Pipe getREFs(final PFlow pf, final QCAVector vector) {
return Utils.getByREF(pf, vector);
}
} |
package com.cv4j.core.binary;
import com.cv4j.core.datamodel.ByteProcessor;
public class Threshold {
/** binary image */
public static int THRESH_BINARY = 0;
/** invert binary image */
public static int THRESH_BINARY_INV = 1;
/** it is not reasonable method to convert binary image */
public static int THRESH_MEANS = 1;
/** it is popular binary method in OPENCV and MATLAB */
public static int THRESH_OTSU = 2;
/** histogram statistic threshold method*/
public static int THRESH_TRIANGLE = 3;
/**based on 1D mean shift, CV4J custom binary method, sometimes it is very slow...*/
public static int THRESH_MEANSHIFT = 4;
/**
*
* @param gray - gray image data, ByteProcessor type
* @param type - binary segmentation method, int
*/
public void process(ByteProcessor gray, int type) {
process(gray, type, THRESH_BINARY, 0);
}
/**
*
* @param gray - gray image data, ByteProcessor type
* @param type - binary segmentation method, int
* @param thresh - threshold value you are going to use it if type = 0;
*/
public void process(ByteProcessor gray, int type, int method, int thresh) {
int tvalue = thresh;
if(type == THRESH_MEANS) {
tvalue = getMeanThreshold(gray);
}
else if(type == THRESH_OTSU) {
tvalue = getOTSUThreshold(gray);
}
else if(type == THRESH_TRIANGLE) {
tvalue = getTriangleThreshold(gray);
}
else if(type == THRESH_MEANSHIFT) {
tvalue = shift(gray);
}
byte[] data = gray.getGray();
int c = 0;
for(int i=0; i<data.length; i++) {
c = data[i]&0xff;
if(c <= tvalue) {
data[i] = (method == THRESH_BINARY_INV)?(byte)255 : (byte)0;
} else {
data[i] = (method == THRESH_BINARY_INV)?(byte)0 : (byte)255;
}
}
}
private int getMeanThreshold(ByteProcessor gray) {
byte[] data = gray.getGray();
int sum = 0;
for(int i=0; i<data.length; i++) {
sum += data[i]&0xff;
}
return sum / data.length;
}
private int getOTSUThreshold(ByteProcessor gray) {
int[] histogram = new int[256];
byte[] data = gray.getGray();
int c = 0;
for(int i=0; i<data.length; i++) {
c = data[i]&0xff;
histogram[c]++;
}
// - OTSU
double total = data.length;
double[] variances = new double[256];
for(int i=0; i<variances.length; i++)
{
double bw = 0;
double bmeans = 0;
double bvariance = 0;
double count = 0;
for(int t=0; t<i; t++)
{
count += histogram[t];
bmeans += histogram[t] * t;
}
bw = count / total;
bmeans = (count == 0) ? 0 :(bmeans / count);
for(int t=0; t<i; t++)
{
bvariance += (Math.pow((t-bmeans),2) * histogram[t]);
}
bvariance = (count == 0) ? 0 : (bvariance / count);
double fw = 0;
double fmeans = 0;
double fvariance = 0;
count = 0;
for(int t=i; t<histogram.length; t++)
{
count += histogram[t];
fmeans += histogram[t] * t;
}
fw = count / total;
fmeans = (count == 0) ? 0 : (fmeans / count);
for(int t=i; t<histogram.length; t++)
{
fvariance += (Math.pow((t-fmeans),2) * histogram[t]);
}
fvariance = (count == 0) ? 0 : (fvariance / count);
variances[i] = bw * bvariance + fw * fvariance;
}
// find the minimum within class variance
double min = variances[0];
int threshold = 0;
for(int m=1; m<variances.length; m++)
{
if(min > variances[m]){
threshold = m;
min = variances[m];
}
}
System.out.println("final threshold value : " + threshold);
return threshold;
}
private int getTriangleThreshold(ByteProcessor gray) {
int[] histogram = new int[256];
byte[] data = gray.getGray();
int c = 0;
for(int i=0; i<data.length; i++) {
c = data[i]&0xff;
histogram[c]++;
}
int left_bound = 0, right_bound = 0, max_ind = 0, max = 0;
int temp;
boolean isflipped = false;
int i=0, j=0;
int N = 256;
for( i = 0; i < N; i++ )
{
if( histogram[i] > 0 )
{
left_bound = i;
break;
}
}
if( left_bound > 0 )
left_bound
for( i = N-1; i > 0; i
{
if( histogram[i] > 0 )
{
right_bound = i;
break;
}
}
if( right_bound < N-1 )
right_bound++;
// Hmax
for( i = 0; i < N; i++ )
{
if( histogram[i] > max)
{
max = histogram[i];
max_ind = i;
}
}
if( max_ind-left_bound < right_bound-max_ind)
{
isflipped = true;
i = 0;
j = N-1;
while( i < j )
{
temp = histogram[i]; histogram[i] = histogram[j]; histogram[j] = temp;
i++; j
}
left_bound = N-1-right_bound;
max_ind = N-1-max_ind;
}
double thresh = left_bound;
double a, b, dist = 0, tempdist;
a = max; b = left_bound-max_ind;
for( i = left_bound+1; i <= max_ind; i++ )
{
tempdist = a*i + b*histogram[i];
if( tempdist > dist)
{
dist = tempdist;
thresh = i;
}
}
thresh
// T,255-T
if( isflipped )
thresh = N-1-thresh;
return (int)thresh;
}
private int shift(ByteProcessor gray) {
// find threshold
int t = 127, nt = 0;
int m1=0, m2=0;
int sum1=0, sum2=0;
int count1=0, count2=0;
int count = 0 ;
int[] data = gray.toInt(0);
while(true) {
for(int i=0; i<data.length; i++) {
if(data[i] > t) {
sum1 += data[i];
count1++;
}
else {
sum2 += data[i];
count2++;
}
}
m1 = sum1 / count1;
m2 = sum2 / count2;
sum1 = 0;
sum2 = 0;
count1 = 0;
count2 = 0;
nt = (m1 + m2) / 2;
if(t == nt) {
break;
}
else {
t = nt;
}
}
return t;
}
} |
package org.cactoos.scalar;
import java.util.function.Supplier;
/**
* ScalarOfSupplier.
*
* @param <T> Element type.
* @since 0.47
*/
public final class ScalarOfSupplier<T> extends ScalarEnvelope<T> {
/**
* Ctor.
*
* @param supplier The supplier
*/
public ScalarOfSupplier(final Supplier<? extends T> supplier) {
super(supplier::get);
}
} |
package org.cojen.tupl.rows;
import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.MutableCallSite;
import java.lang.invoke.VarHandle;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.RandomAccess;
import org.cojen.maker.Label;
import org.cojen.maker.MethodMaker;
import org.cojen.maker.Variable;
import org.cojen.tupl.io.Utils;
/**
* Makes code which converts a value declared as Object to a specific type.
*
* @author Brian S O'Neill
*/
public class ConvertCallSite extends MutableCallSite {
private static final MethodHandle cImplementHandle;
private static final VarHandle cImplementedHandle;
static {
try {
var lookup = MethodHandles.lookup();
cImplementHandle = lookup.findVirtual
(ConvertCallSite.class, "implement",
MethodType.methodType(Object.class, Object.class));
cImplementedHandle = lookup.findVarHandle
(ConvertCallSite.class, "mImplemented", int.class);
} catch (Throwable e) {
throw Utils.rethrow(e);
}
}
// 0: not implemented, 1: being implemented, 2: implemented
private volatile int mImplemented;
private ConvertCallSite(MethodType mt) {
super(mt);
}
/**
* Makes code which converts a value declared as an object type to a specific type. If the
* conversion cannot be performed, an exception is thrown at runtime.
*
* @param toType the specific desired "to" type
* @param from variable declared as an object type which contains the "from" value
* @return the "to" value, of type "toType"
*/
static Variable make(MethodMaker mm, Class toType, Variable from) {
return mm.var(ConvertCallSite.class).indy("makeNext").invoke(toType, "_", null, from);
}
/**
* Indy bootstrap method.
*
* @param mt accepts one param, an object, and returns a non-void toType
*/
public static CallSite makeNext(MethodHandles.Lookup lookup, String name, MethodType mt) {
var cs = new ConvertCallSite(mt);
cs.setTarget(cImplementHandle.bindTo(cs).asType(mt));
return cs;
}
private Object implement(Object obj) {
while (true) {
int state = mImplemented;
if (state >= 2) {
break;
}
if (state == 0 && cImplementedHandle.compareAndSet(this, 0, 1)) {
try {
setTarget(makeConverter(obj, type()));
mImplemented = 2;
break;
} catch (Throwable e) {
mImplemented = 0;
throw e;
}
}
Thread.yield();
}
try {
return getTarget().invoke(obj);
} catch (Throwable e) {
throw Utils.rethrow(e);
}
}
/**
* @param obj defines the "from" type, which can be null
* @param mt defines the "to" type (the return type)
*/
private static MethodHandle makeConverter(Object obj, MethodType mt) {
// It's tempting to want to cache the generated converters, but each conversion chain
// is unique to the initial call site it's generated for. A converter cannot therefore
// be identified by just the from/to types and be shared.
Class<?> fromType = obj == null ? null : obj.getClass();
Class<?> toType = mt.returnType();
MethodMaker mm = MethodMaker.begin(MethodHandles.lookup(), "convert", mt);
Variable from = mm.param(0);
final Label next = mm.label();
final Variable result;
if (fromType == null) {
if (toType.isPrimitive()) {
result = null;
} else {
from.ifNe(null, next);
result = mm.var(toType).set(null);
}
} else {
if (fromType.isAssignableFrom(from.classType())) {
// InstanceOf check will always be true, but must still check for null.
from.ifEq(null, next);
} else {
instanceOf(from, fromType, next);
}
if (!toType.isPrimitive() && toType.isAssignableFrom(fromType)) {
result = from.cast(toType);
} else if (toType == String.class) {
result = toString(mm, fromType, from);
} else if (toType == long.class || toType == Long.class) {
result = toLong(mm, fromType, from);
} else if (toType == int.class || toType == Integer.class) {
result = toInt(mm, fromType, from);
} else if (toType == double.class || toType == Double.class) {
result = toDouble(mm, fromType, from);
} else if (toType == float.class || toType == Float.class) {
result = toFloat(mm, fromType, from);
} else if (toType == boolean.class || toType == Boolean.class) {
result = toBoolean(mm, fromType, from);
} else if (toType == BigInteger.class) {
result = toBigInteger(mm, fromType, from);
} else if (toType == BigDecimal.class) {
result = toBigDecimal(mm, fromType, from);
} else if (toType == char.class || toType == Character.class) {
result = toChar(mm, fromType, from);
} else if (toType == byte.class || toType == Byte.class) {
result = toByte(mm, fromType, from);
} else if (toType == short.class || toType == Short.class) {
result = toShort(mm, fromType, from);
} else if (toType.isArray()) {
result = toArray(mm, toType, fromType, from);
} else {
result = null;
}
}
if (result != null) {
mm.return_(result);
} else {
mm.new_(IllegalArgumentException.class,
"Cannot convert " + (fromType == null ? null : fromType.getSimpleName()) +
" to " + toType.getSimpleName()).throw_();
}
if (next != null) {
next.here();
var indy = mm.var(ConvertCallSite.class).indy("makeNext");
mm.return_(indy.invoke(toType, "_", null, from));
}
return mm.finish();
}
/**
* @fail branch here if not instanceOf
*/
private static void instanceOf(Variable fromVar, Class<?> fromType, Label fail) {
if (Modifier.isPublic(fromType.getModifiers())) {
fromVar.instanceOf(fromType).ifFalse(fail);
return;
}
// Cannot generate code against a non-public type. Instead, generate a chain of
// instanceOf checks against all publicly available super classes and interfaces.
var types = new HashSet<Class<?>>();
gatherAccessibleTypes(types, fromType);
// Remove redundant interfaces.
Iterator<Class<?>> it = types.iterator();
outer: while (it.hasNext()) {
Class<?> type = it.next();
for (Class<?> other : types) {
if (other != type && type.isAssignableFrom(other)) {
it.remove();
continue outer;
}
}
}
for (Class<?> type : types) {
fromVar.instanceOf(type).ifFalse(fail);
}
}
private static void gatherAccessibleTypes(HashSet<Class<?>> types, Class<?> type) {
if (types.contains(type)) {
return;
}
if (Modifier.isPublic(type.getModifiers())) {
types.add(type);
}
Class<?> superType = type.getSuperclass();
if (superType != null && superType != Object.class) {
gatherAccessibleTypes(types, superType);
}
Class<?>[] ifaces = type.getInterfaces();
if (ifaces != null) {
for (var iface : ifaces) {
if (iface != java.io.Serializable.class) {
gatherAccessibleTypes(types, iface);
}
}
}
}
private static Variable toBoolean(MethodMaker mm, Class fromType, Variable from) {
if (fromType == Boolean.class) {
return from.cast(Boolean.class);
} else if (fromType == String.class) {
return mm.var(ConvertCallSite.class).invoke("stringToBoolean", from.cast(String.class));
} else {
return null;
}
}
private static Variable toByte(MethodMaker mm, Class fromType, Variable from) {
if (fromType == Byte.class) {
return from.cast(Byte.class);
} else if (fromType == Integer.class) {
return mm.var(ConvertCallSite.class).invoke("intToByte", from.cast(Integer.class));
} else if (fromType == Long.class) {
return mm.var(ConvertCallSite.class).invoke("longToByte", from.cast(Long.class));
} else if (fromType == String.class) {
return mm.var(Byte.class).invoke("parseByte", from.cast(String.class));
} else if (fromType == Double.class) {
return mm.var(ConvertCallSite.class).invoke("doubleToByte", from.cast(Double.class));
} else if (fromType == Float.class) {
return mm.var(ConvertCallSite.class).invoke("floatToByte", from.cast(Float.class));
} else if (fromType == Short.class) {
return mm.var(ConvertCallSite.class).invoke("shortToByte", from.cast(Short.class));
} else if (fromType == BigInteger.class) {
return from.cast(BigInteger.class).invoke("byteValueExact");
} else if (fromType == BigDecimal.class) {
return from.cast(BigDecimal.class).invoke("byteValueExact");
} else {
return null;
}
}
private static Variable toShort(MethodMaker mm, Class fromType, Variable from) {
if (fromType == Short.class) {
return from.cast(Short.class);
} else if (fromType == Integer.class) {
return mm.var(ConvertCallSite.class).invoke("intToShort", from.cast(Integer.class));
} else if (fromType == Long.class) {
return mm.var(ConvertCallSite.class).invoke("longToShort", from.cast(Long.class));
} else if (fromType == String.class) {
return mm.var(Short.class).invoke("parseShort", from.cast(String.class));
} else if (fromType == Double.class) {
return mm.var(ConvertCallSite.class).invoke("doubleToShort", from.cast(Double.class));
} else if (fromType == Float.class) {
return mm.var(ConvertCallSite.class).invoke("floatToShort", from.cast(Float.class));
} else if (fromType == Byte.class) {
return from.cast(Byte.class).invoke("shortValue");
} else if (fromType == BigInteger.class) {
return from.cast(BigInteger.class).invoke("shortValueExact");
} else if (fromType == BigDecimal.class) {
return from.cast(BigDecimal.class).invoke("shortValueExact");
} else {
return null;
}
}
private static Variable toInt(MethodMaker mm, Class fromType, Variable from) {
if (fromType == Integer.class) {
return from.cast(Integer.class);
} else if (fromType == Long.class) {
return mm.var(Math.class).invoke("toIntExact", from.cast(Long.class));
} else if (fromType == String.class) {
return mm.var(Integer.class).invoke("parseInt", from.cast(String.class));
} else if (fromType == Double.class) {
return mm.var(ConvertCallSite.class).invoke("doubleToInt", from.cast(Double.class));
} else if (fromType == Float.class) {
return mm.var(ConvertCallSite.class).invoke("floatToInt", from.cast(Float.class));
} else if (fromType == Byte.class) {
return from.cast(Byte.class).invoke("intValue");
} else if (fromType == Short.class) {
return from.cast(Short.class).invoke("intValue");
} else if (fromType == BigInteger.class) {
return from.cast(BigInteger.class).invoke("intValueExact");
} else if (fromType == BigDecimal.class) {
return from.cast(BigDecimal.class).invoke("intValueExact");
} else {
return null;
}
}
private static Variable toLong(MethodMaker mm, Class fromType, Variable from) {
if (fromType == Long.class) {
return from.cast(Long.class);
} else if (fromType == Integer.class) {
return from.cast(Integer.class).invoke("longValue");
} else if (fromType == String.class) {
return mm.var(Long.class).invoke("parseLong", from.cast(String.class));
} else if (fromType == Double.class) {
return mm.var(ConvertCallSite.class).invoke("doubleToLong", from.cast(Double.class));
} else if (fromType == Float.class) {
return mm.var(ConvertCallSite.class).invoke("floatToLong", from.cast(Float.class));
} else if (fromType == Byte.class) {
return from.cast(Byte.class).invoke("longValue");
} else if (fromType == Short.class) {
return from.cast(Short.class).invoke("longValue");
} else if (fromType == BigInteger.class) {
return from.cast(BigInteger.class).invoke("longValueExact");
} else if (fromType == BigDecimal.class) {
return from.cast(BigDecimal.class).invoke("longValueExact");
} else {
return null;
}
}
private static Variable toFloat(MethodMaker mm, Class fromType, Variable from) {
if (fromType == Float.class) {
return from.cast(Float.class);
} else if (fromType == String.class) {
return mm.var(Float.class).invoke("parseFloat", from.cast(String.class));
} else if (fromType == Integer.class) {
return mm.var(ConvertCallSite.class).invoke("intToFloat", from.cast(Integer.class));
} else if (fromType == Double.class) {
return mm.var(ConvertCallSite.class).invoke("doubleToFloat", from.cast(Double.class));
} else if (fromType == Long.class) {
return mm.var(ConvertCallSite.class).invoke("longToFloat", from.cast(Long.class));
} else if (fromType == Byte.class) {
return from.cast(Byte.class).invoke("floatValue");
} else if (fromType == Short.class) {
return from.cast(Short.class).invoke("floatValue");
} else if (fromType == BigInteger.class) {
var intVar = from.cast(BigInteger.class).invoke("intValueExact");
return mm.var(ConvertCallSite.class).invoke("intToFloat", intVar);
} else if (fromType == BigDecimal.class) {
return mm.var(ConvertCallSite.class).invoke("bdToFloat", from.cast(BigDecimal.class));
} else {
return null;
}
}
private static Variable toDouble(MethodMaker mm, Class fromType, Variable from) {
if (fromType == Double.class) {
return from.cast(Double.class);
} else if (fromType == String.class) {
return mm.var(Double.class).invoke("parseDouble", from.cast(String.class));
} else if (fromType == Integer.class) {
return from.cast(Integer.class);
} else if (fromType == Long.class) {
return mm.var(ConvertCallSite.class).invoke("longToDouble", from.cast(Long.class));
} else if (fromType == Float.class) {
return from.cast(Float.class).invoke("doubleValue");
} else if (fromType == Byte.class) {
return from.cast(Byte.class).invoke("doubleValue");
} else if (fromType == Short.class) {
return from.cast(Short.class).invoke("doubleValue");
} else if (fromType == BigInteger.class) {
var longVar = from.cast(BigInteger.class).invoke("longValueExact");
return mm.var(ConvertCallSite.class).invoke("longToDouble", longVar);
} else if (fromType == BigDecimal.class) {
return mm.var(ConvertCallSite.class).invoke("bdToDouble", from.cast(BigDecimal.class));
} else {
return null;
}
}
private static Variable toChar(MethodMaker mm, Class fromType, Variable from) {
if (fromType == Character.class) {
return from.cast(Character.class);
} else if (fromType == String.class) {
return mm.var(ConvertCallSite.class).invoke("stringToChar", from.cast(String.class));
} else {
return null;
}
}
private static Variable toString(MethodMaker mm, Class fromType, Variable from) {
return mm.var(String.class).invoke("valueOf", from);
}
private static Variable toBigInteger(MethodMaker mm, Class fromType, Variable from) {
Variable longVar;
if (fromType == Integer.class) {
longVar = from.cast(Integer.class);
} else if (fromType == Long.class) {
longVar = from.cast(Long.class);
} else if (fromType == String.class) {
return mm.new_(BigInteger.class, from.cast(String.class));
} else if (fromType == Double.class) {
longVar = mm.var(ConvertCallSite.class).invoke("doubleToLong", from.cast(Double.class));
} else if (fromType == Float.class) {
longVar = mm.var(ConvertCallSite.class).invoke("floatToLong", from.cast(Float.class));
} else if (fromType == Byte.class) {
longVar = from.cast(Byte.class);
} else if (fromType == Short.class) {
longVar = from.cast(Short.class);
} else if (fromType == BigDecimal.class) {
return from.cast(BigDecimal.class).invoke("toBigIntegerExact");
} else {
return null;
}
return mm.var(BigInteger.class).invoke("valueOf", longVar);
}
private static Variable toBigDecimal(MethodMaker mm, Class fromType, Variable from) {
Variable numVar;
if (fromType == String.class) {
return mm.new_(BigDecimal.class, from.cast(String.class));
} else if (fromType == Integer.class) {
numVar = from.cast(Integer.class);
} else if (fromType == Long.class) {
numVar = from.cast(Long.class);
} else if (fromType == Double.class) {
numVar = from.cast(Double.class);
} else if (fromType == Float.class) {
numVar = from.cast(Float.class);
} else if (fromType == Byte.class) {
numVar = from.cast(Byte.class);
} else if (fromType == Short.class) {
numVar = from.cast(Short.class);
} else if (fromType == BigInteger.class) {
return mm.new_(BigDecimal.class, from.cast(BigInteger.class));
} else {
return null;
}
return mm.var(BigDecimal.class).invoke("valueOf", numVar);
}
private static Variable toArray(MethodMaker mm, Class toType, Class fromType, Variable from) {
Class toElementType = toType.getComponentType();
if (fromType.isArray()) {
var fromArrayVar = from.cast(fromType);
var lengthVar = fromArrayVar.alength();
// Copy and conversion loop. Note that the from elements are always boxed for
// simplicity. The generated code is expected to have inlining and autoboxing
// optimizations applied anyhow.
return ConvertUtils.convertArray(mm, toType, lengthVar, ixVar -> {
return make(mm, toElementType, fromArrayVar.aget(ixVar).box());
});
} else if (List.class.isAssignableFrom(fromType) &&
RandomAccess.class.isAssignableFrom(fromType))
{
var fromListVar = from.cast(List.class);
var lengthVar = fromListVar.invoke("size");
return ConvertUtils.convertArray(mm, toType, lengthVar, ixVar -> {
return make(mm, toElementType, fromListVar.invoke("get", ixVar));
});
} else if (Collection.class.isAssignableFrom(fromType)) {
var fromCollectionVar = from.cast(Collection.class);
var lengthVar = fromCollectionVar.invoke("size");
var itVar = fromCollectionVar.invoke("iterator");
return ConvertUtils.convertArray(mm, toType, lengthVar, ixVar -> {
return make(mm, toElementType, itVar.invoke("next"));
});
} else {
return null;
}
}
// Called by generated code.
public static boolean stringToBoolean(String str) {
if (str.equalsIgnoreCase("false")) {
return false;
}
if (str.equalsIgnoreCase("true")) {
return true;
}
throw new IllegalArgumentException("Cannot convert to Boolean: " + str);
}
// Called by generated code.
public static char stringToChar(String str) {
if (str.length() == 1) {
return str.charAt(0);
}
throw new IllegalArgumentException("Cannot convert to Character: " + str);
}
// Called by generated code.
public static int doubleToInt(double d) {
int i = (int) d;
if ((double) i != d) {
throw loss(Integer.class, d);
}
return i;
}
// Called by generated code.
public static long doubleToLong(double d) {
long i = (int) d;
if ((double) i != d) {
throw loss(Long.class, d);
}
return i;
}
// Called by generated code.
public static float doubleToFloat(double d) {
float f = (float) d;
if ((double) f != d && !Double.isNaN(d)) {
throw loss(Float.class, d);
}
return f;
}
// Called by generated code.
public static byte doubleToByte(double d) {
byte b = (byte) d;
if ((double) b != d) {
throw loss(Byte.class, d);
}
return b;
}
// Called by generated code.
public static short doubleToShort(double d) {
short s = (short) d;
if ((double) s != d) {
throw loss(Short.class, d);
}
return s;
}
// Called by generated code.
public static int floatToInt(float f) {
int i = (int) f;
if ((float) i != f) {
throw loss(Integer.class, f);
}
return i;
}
// Called by generated code.
public static long floatToLong(float f) {
long i = (int) f;
if ((float) i != f) {
throw loss(Long.class, f);
}
return i;
}
// Called by generated code.
public static byte floatToByte(float f) {
byte b = (byte) f;
if ((float) b != f) {
throw loss(Byte.class, f);
}
return b;
}
// Called by generated code.
public static short floatToShort(float f) {
short s = (short) f;
if ((float) s != f) {
throw loss(Short.class, f);
}
return s;
}
// Called by generated code.
public static byte shortToByte(short i) {
byte b = (byte) i;
if ((short) b != i) {
throw loss(Byte.class, i);
}
return b;
}
// Called by generated code.
public static byte intToByte(int i) {
byte b = (byte) i;
if ((int) b != i) {
throw loss(Byte.class, i);
}
return b;
}
// Called by generated code.
public static short intToShort(int i) {
short s = (short) i;
if ((int) s != i) {
throw loss(Short.class, i);
}
return s;
}
// Called by generated code.
public static float intToFloat(int i) {
float f = (float) i;
if ((int) f != i) {
throw loss(Float.class, i);
}
return f;
}
// Called by generated code.
public static byte longToByte(long i) {
byte b = (byte) i;
if ((long) b != i) {
throw loss(Byte.class, i);
}
return b;
}
// Called by generated code.
public static short longToShort(long i) {
short s = (short) i;
if ((long) s != i) {
throw loss(Short.class, i);
}
return s;
}
// Called by generated code.
public static float longToFloat(long i) {
float f = (float) i;
if ((long) f != i) {
throw loss(Float.class, i);
}
return f;
}
// Called by generated code.
public static double longToDouble(long i) {
double d = (double) i;
if ((long) d != i) {
throw loss(Double.class, i);
}
return d;
}
// Called by generated code.
public static float bdToFloat(BigDecimal bd) {
float f = bd.floatValue();
if (BigDecimal.valueOf(f).compareTo(bd) != 0) {
throw loss(Float.class, bd);
}
return f;
}
// Called by generated code.
public static double bdToDouble(BigDecimal bd) {
double d = bd.doubleValue();
if (BigDecimal.valueOf(d).compareTo(bd) != 0) {
throw loss(Double.class, bd);
}
return d;
}
private static ArithmeticException loss(Class to, Object value) {
return new ArithmeticException("Cannot convert to " + to.getSimpleName()
+ " without loss: " + value);
}
} |
package org.cyclopsgroup.cym2.awss3;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import javax.activation.MimetypesFileTypeMap;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.maven.wagon.ConnectionException;
import org.apache.maven.wagon.InputData;
import org.apache.maven.wagon.OutputData;
import org.apache.maven.wagon.ResourceDoesNotExistException;
import org.apache.maven.wagon.StreamWagon;
import org.apache.maven.wagon.TransferFailedException;
import org.apache.maven.wagon.authentication.AuthenticationException;
import org.apache.maven.wagon.authentication.AuthenticationInfo;
import org.apache.maven.wagon.authorization.AuthorizationException;
import org.apache.maven.wagon.proxy.ProxyInfo;
import org.apache.maven.wagon.resource.Resource;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.model.S3ObjectSummary;
/**
* Amazon S3 wagon provider implementation
*
* @author <a href="mailto:jiaqi@cyclopsgroup.org">Jiaqi Guo</a>
*/
public class S3Wagon
extends StreamWagon
{
private final MimetypesFileTypeMap typeMap = new MimetypesFileTypeMap();
private String bucketName;
private String keyPrefix;
private AmazonS3 s3;
private final Properties mimeTypes;
/**
* Default constructor reads mime type mapping from generated properties file for later use
*
* @throws IOException Allows IO errors
*/
public S3Wagon()
throws IOException
{
Properties props = new Properties();
InputStream in = getClass().getClassLoader().getResourceAsStream( "mimetypes.properties" );
try
{
props.load( in );
this.mimeTypes = props;
}
finally
{
IOUtils.closeQuietly( in );
}
}
/**
* @inheritDoc
*/
@Override
public void closeConnection()
throws ConnectionException
{
}
private void doPutFromStream( InputStream in, File inFile, String destination, long contentLength, long lastModified )
{
Resource resource = new Resource( destination );
firePutInitiated( resource, inFile );
String key = keyPrefix + destination;
// Prepare for meta data
ObjectMetadata meta = new ObjectMetadata();
// Content length is important. Many S3 client relies on it
if ( contentLength != -1 )
{
meta.setContentLength( contentLength );
}
// Last modified data is used by CloudFront
meta.setLastModified( new Date( lastModified ) );
// Find mime type based on file extension
int lastDot = destination.lastIndexOf( '.' );
String mimeType = null;
if ( lastDot != -1 )
{
String ext = destination.substring( lastDot + 1, destination.length() );
mimeType = mimeTypes.getProperty( ext );
}
if ( mimeType == null )
{
mimeType = typeMap.getContentType( destination );
}
else
{
fireTransferDebug( "Mime type of " + destination + " is " + mimeType + " according to build-in types" );
}
if ( mimeType != null )
{
meta.setContentType( mimeType );
}
try
{
fireTransferDebug( "Uploading file " + inFile + " to key " + key + " in S3 bucket " + bucketName );
firePutStarted( resource, inFile );
// Upload file and allow everyone to read
s3.putObject( bucketName, key, in, meta );
s3.setObjectAcl( bucketName, key, CannedAccessControlList.PublicRead );
firePutCompleted( resource, inFile );
}
finally
{
IOUtils.closeQuietly( in );
}
}
/**
* @inheritDoc
*/
@Override
public void fillInputData( InputData in )
throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
{
fireTransferDebug( "Filling input data" );
String key = keyPrefix + in.getResource().getName();
S3Object object;
try
{
object = s3.getObject( bucketName, key );
}
catch ( AmazonServiceException e )
{
if ( e.getStatusCode() == 404 )
{
throw new ResourceDoesNotExistException( "Key " + key + " does not exist in S3 bucket " + bucketName );
}
else if ( e.getStatusCode() == 403 )
{
// 403 is thrown when key does not exist and configuration doesn't allow user to list keys
throw new ResourceDoesNotExistException( "403 implies that key " + key + " does not exist in bucket "
+ bucketName, e );
}
throw new TransferFailedException( "Can't get object " + key + " from S4 bucket " + bucketName, e );
}
in.getResource().setContentLength( object.getObjectMetadata().getContentLength() );
in.getResource().setLastModified( object.getObjectMetadata().getLastModified().getTime() );
in.setInputStream( object.getObjectContent() );
}
/**
* @inheritDoc
*/
@Override
public void fillOutputData( OutputData out )
throws TransferFailedException
{
throw new UnsupportedOperationException( "This call is not supported" );
}
/**
* @inheritDoc
*/
public void get( String resourceName, File destination )
throws ResourceDoesNotExistException, TransferFailedException
{
Resource resource = new Resource( resourceName );
fireGetInitiated( resource, destination );
String key = keyPrefix + resourceName;
try
{
fireGetStarted( resource, destination );
// This is a bit more efficient than copying stream
s3.getObject( new GetObjectRequest( bucketName, key ), destination );
fireGetCompleted( resource, destination );
}
catch ( AmazonServiceException e )
{
if ( e.getStatusCode() == 404 )
{
throw new ResourceDoesNotExistException( "Key " + key + " does not exist in bucket " + bucketName, e );
}
else if ( e.getStatusCode() == 403 )
{
throw new ResourceDoesNotExistException( "403 implies that key " + key + " does not exist in bucket "
+ bucketName, e );
}
throw new TransferFailedException( "Getting metadata of key " + key + " failed", e );
}
}
/**
* @inheritDoc
*/
@SuppressWarnings( "rawtypes" )
public List getFileList( String destinationDirectory )
throws TransferFailedException, ResourceDoesNotExistException
{
String path = keyPrefix + destinationDirectory;
if ( !path.endsWith( "/" ) )
{
path += "/";
}
fireSessionDebug( "Listing objects with prefix " + path + " under bucket " + bucketName );
// Since S3 does not have concept of directory, result contains all contents with given prefix
ObjectListing result =
s3.listObjects( new ListObjectsRequest().withBucketName( bucketName ).withPrefix( path ).withDelimiter( "/" ) );
if ( result.getObjectSummaries().isEmpty() )
{
throw new ResourceDoesNotExistException( "No keys exist with prefix " + path );
}
Set<String> results = new HashSet<String>();
for ( S3ObjectSummary summary : result.getObjectSummaries() )
{
String name = StringUtils.removeStart( summary.getKey(), path );
if ( name.indexOf( '/' ) == -1 )
{
results.add( name );
}
else
{
results.add( name.substring( 0, name.indexOf( '/' ) ) );
}
}
fireSessionDebug( "Returning result " + results );
return new ArrayList<String>( results );
}
/**
* @inheritDoc
*/
public boolean getIfNewer( String resourceName, File destination, long timestamp )
throws ResourceDoesNotExistException, TransferFailedException
{
ObjectMetadata meta = getRequiredMetadata( resourceName );
if ( meta == null )
{
return false;
}
get( resourceName, destination );
return true;
}
/**
* @inheritDoc
*/
@Override
public boolean getIfNewerToStream( String resourceName, OutputStream out, long timestamp )
throws ResourceDoesNotExistException, TransferFailedException
{
ObjectMetadata meta = getRequiredMetadata( resourceName );
if ( meta == null )
{
return false;
}
Resource resource = new Resource( resourceName );
fireGetInitiated( resource, null );
InputStream in = s3.getObject( bucketName, keyPrefix ).getObjectContent();
try
{
fireGetStarted( resource, null );
IOUtils.copy( in, out );
out.flush();
out.close();
fireGetCompleted( resource, null );
return true;
}
catch ( IOException e )
{
throw new TransferFailedException( "Stream copy failed", e );
}
finally
{
IOUtils.closeQuietly( in );
}
}
private ObjectMetadata getRequiredMetadata( String resourceName )
throws ResourceDoesNotExistException, TransferFailedException
{
String key = keyPrefix + resourceName;
try
{
return s3.getObjectMetadata( bucketName, key );
}
catch ( AmazonServiceException e )
{
if ( e.getStatusCode() == 404 )
{
throw new ResourceDoesNotExistException( "Key " + key + " does not exist in bucket " + bucketName, e );
}
throw new TransferFailedException( "Getting metadata of key " + key + "failed", e );
}
}
/**
* @inheritDoc
*/
@Override
protected void openConnectionInternal()
throws ConnectionException, AuthenticationException
{
// Retrieve credentials from authentication information is always required since it has access key and secret
// key
AuthenticationInfo auth = getAuthenticationInfo();
if ( auth == null )
{
throw new AuthenticationException( "S3 access requires authentication information" );
}
AWSCredentials credentials = new BasicAWSCredentials( auth.getUserName(), auth.getPassword() );
// Pass timeout configuration to AWS client config
ClientConfiguration config = new ClientConfiguration();
config.setConnectionTimeout( getTimeout() );
config.setSocketTimeout( getTimeout() );
fireSessionDebug( "Connect timeout and socket timeout is set to " + getTimeout() + " ms" );
// Possible proxy
ProxyInfo proxy = getProxyInfo();
fireSessionDebug( "Setting up AWS S3 client with source "
+ ToStringBuilder.reflectionToString( getRepository() ) + ", authentication information and proxy "
+ ToStringBuilder.reflectionToString( proxy ) );
if ( proxy != null )
{
config.setProxyDomain( proxy.getNtlmDomain() );
config.setProxyHost( proxy.getHost() );
config.setProxyPassword( proxy.getPassword() );
config.setProxyPort( proxy.getPort() );
config.setProxyUsername( proxy.getUserName() );
config.setProxyWorkstation( proxy.getNtlmHost() );
}
fireSessionDebug( "AWS Client config is " + ToStringBuilder.reflectionToString( config ) );
// Create client
s3 = new AmazonS3Client( credentials, config );
bucketName = getRepository().getHost();
fireSessionDebug( "Bucket name is " + bucketName );
// Figure out path defined in pom.xml
String prefix = StringUtils.trimToEmpty( getRepository().getBasedir() );
if ( !prefix.endsWith( "/" ) )
{
prefix = prefix + "/";
}
prefix = StringUtils.removeStart( prefix, "/" );
keyPrefix = prefix;
fireSessionDebug( "Key prefix " + keyPrefix );
}
/**
* @inheritDoc
*/
public void put( File source, String destination )
throws TransferFailedException, ResourceDoesNotExistException
{
try
{
doPutFromStream( new FileInputStream( source ), source, destination, source.length(), source.lastModified() );
}
catch ( FileNotFoundException e )
{
throw new ResourceDoesNotExistException( "Source file " + source + " does not exist", e );
}
}
/**
* @inheritDoc
*/
public void putDirectory( File sourceDirectory, String destinationDirectory )
throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException
{
if ( destinationDirectory.equals( "." ) )
{
destinationDirectory = "";
}
fireTransferDebug( "Putting " + sourceDirectory + " to " + destinationDirectory + " which is noop" );
for ( File file : sourceDirectory.listFiles() )
{
String dest =
StringUtils.isBlank( destinationDirectory ) ? file.getName()
: ( destinationDirectory + "/" + file.getName() );
fireTransferDebug( "Putting child element " + file + " to " + dest );
if ( file.isDirectory() )
{
putDirectory( file, dest );
}
else
{
put( file, dest );
}
}
}
/**
* @inheritDoc
*/
@Override
public void putFromStream( InputStream in, String destination )
throws TransferFailedException, ResourceDoesNotExistException
{
doPutFromStream( in, null, destination, -1, System.currentTimeMillis() );
}
/**
* @inheritDoc
*/
@Override
public void putFromStream( InputStream in, String destination, long contentLength, long lastModified )
throws TransferFailedException, ResourceDoesNotExistException
{
doPutFromStream( in, null, destination, contentLength, lastModified );
}
/**
* @inheritDoc
*/
public boolean resourceExists( String resourceName )
throws TransferFailedException, AuthorizationException
{
String key = keyPrefix + resourceName;
try
{
s3.getObjectMetadata( bucketName, key );
return true;
}
catch ( AmazonServiceException e )
{
if ( e.getStatusCode() == 404 )
{
return false;
}
throw new TransferFailedException( "Can't verify if resource key " + key + " exist or not", e );
}
}
/**
* @inheritDoc
*/
public boolean supportsDirectoryCopy()
{
return true;
}
} |
package org.davidmoten.rx.pool;
import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.davidmoten.rx.jdbc.pool.PoolClosedException;
import org.reactivestreams.Subscription;
import com.github.davidmoten.guavamini.Preconditions;
import io.reactivex.Scheduler;
import io.reactivex.Scheduler.Worker;
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.fuseable.SimplePlainQueue;
import io.reactivex.internal.queue.MpscLinkedQueue;
import io.reactivex.plugins.RxJavaPlugins;
class MemberSingle<T> extends Single<Member2<T>> implements Subscription, Closeable {
final AtomicReference<Observers<T>> observers;
@SuppressWarnings({ "rawtypes", "unchecked" })
static final Observers EMPTY = new Observers(new MemberSingleObserver[0], new boolean[0], 0, 0);
private final SimplePlainQueue<Member2<T>> queue;
private final AtomicInteger wip = new AtomicInteger();
private final Member2<T>[] members;
private final Scheduler scheduler;
private final int maxSize;
// mutable
private volatile boolean cancelled;
// number of members in the pool at the moment
private int count;
private final NonBlockingPool2<T> pool;
@SuppressWarnings("unchecked")
MemberSingle(NonBlockingPool2<T> pool) {
this.queue = new MpscLinkedQueue<Member2<T>>();
this.members = createMembersArray(pool);
this.scheduler = pool.scheduler;
this.maxSize = pool.maxSize;
this.observers = new AtomicReference<>(EMPTY);
this.count = 1;
this.pool = pool;
queue.offer(members[0]);
}
private static <T> Member2<T>[] createMembersArray(NonBlockingPool2<T> pool) {
@SuppressWarnings("unchecked")
Member2<T>[] m = new Member2[pool.maxSize];
for (int i = 0; i < m.length; i++) {
m[i] = pool.memberFactory.create(pool);
}
return m;
}
public void checkin(Member2<T> member) {
queue.offer(member);
drain();
}
@Override
public void request(long n) {
drain();
}
@Override
public void cancel() {
this.cancelled = true;
}
private void drain() {
if (wip.getAndIncrement() == 0) {
int missed = 1;
while (true) {
while (true) {
if (cancelled) {
queue.clear();
return;
}
Observers<T> obs = observers.get();
if (obs.activeCount == 0) {
break;
}
final Member2<T> m = queue.poll();
if (m == null) {
if (count < maxSize) {
// haven't used all the members of the pool yet
queue.offer(members[count]);
count++;
} else {
break;
}
} else {
Member2<T> m2;
if ((m2 = m.checkout()) != null) {
emit(obs, m2);
} else {
// put back on the queue for consideration later
queue.offer(m);
}
}
}
missed = wip.addAndGet(-missed);
if (missed == 0) {
return;
}
}
}
}
private void emit(Observers<T> obs, Member2<T> m) {
System.out.println("emitting");
// get a fresh worker each time so we jump threads to
// break the stack-trace (a long-enough chain of
// checkout-checkins could otherwise provoke stack
// overflow)
// advance counter so the next and choose an Observer to emit to (round robin)
int index = obs.index;
MemberSingleObserver<T> o = obs.observers[index];
MemberSingleObserver<T> oNext = o;
// atomically bump up the index (if that entry has not been deleted in
// the meantime by disposal)
while (true) {
Observers<T> x = observers.get();
if (x.index == index && x.observers[index] == o) {
System.out.println("inner");
boolean[] active = new boolean[x.active.length];
System.arraycopy(x.active, 0, active, 0, active.length);
active[index] = false;
int nextIndex = (index + 1) % active.length;
while (nextIndex != index && !active[nextIndex]) {
nextIndex = (nextIndex + 1) % active.length;
}
if (observers.compareAndSet(x, new Observers<T>(x.observers, active, x.activeCount - 1, nextIndex))) {
oNext = x.observers[nextIndex];
break;
}
} else {
m.checkin();
return;
}
}
System.out.println("numObs="+obs.observers.length);
System.out.println(oNext.child);
Worker worker = scheduler.createWorker();
worker.schedule(new Emitter<T>(worker, oNext, m));
return;
}
@Override
public void close() throws IOException {
for (Member2<T> member : members) {
try {
member.close();
} catch (Exception e) {
// TODO accumulate and throw?
e.printStackTrace();
}
}
}
@Override
protected void subscribeActual(SingleObserver<? super Member2<T>> observer) {
MemberSingleObserver<T> md = new MemberSingleObserver<T>(observer, this);
observer.onSubscribe(md);
if (pool.isClosed()) {
observer.onError(new PoolClosedException());
return;
}
add(md);
if (md.isDisposed()) {
remove(md);
}
drain();
}
void add(@NonNull MemberSingleObserver<T> inner) {
while (true) {
Observers<T> a = observers.get();
int n = a.observers.length;
@SuppressWarnings("unchecked")
MemberSingleObserver<T>[] b = new MemberSingleObserver[n + 1];
System.arraycopy(a.observers, 0, b, 0, n);
b[n] = inner;
boolean[] active = new boolean[n + 1];
System.arraycopy(a.active, 0, active, 0, n);
active[n] = true;
if (observers.compareAndSet(a, new Observers<T>(b, active, a.activeCount + 1, a.index))) {
return;
}
}
}
@SuppressWarnings("unchecked")
void remove(@NonNull MemberSingleObserver<T> inner) {
while (true) {
Observers<T> a = observers.get();
int n = a.observers.length;
if (n == 0) {
return;
}
int j = -1;
for (int i = 0; i < n; i++) {
if (a.observers[i] == inner) {
j = i;
break;
}
}
if (j < 0) {
return;
}
Observers<T> next;
if (n == 1) {
next = EMPTY;
} else {
MemberSingleObserver<T>[] b = new MemberSingleObserver[n - 1];
System.arraycopy(a.observers, 0, b, 0, j);
System.arraycopy(a.observers, j + 1, b, j, n - j - 1);
boolean[] active = new boolean[n - 1];
System.arraycopy(a.active, 0, active, 0, j);
System.arraycopy(a.active, j + 1, active, j, n - j - 1);
int nextActiveCount = a.active[j] ? a.activeCount - 1 : a.activeCount;
if (a.index > j) {
next = new Observers<T>(b, active, nextActiveCount, a.index - 1);
} else {
next = new Observers<T>(b, active, nextActiveCount, a.index);
}
}
if (observers.compareAndSet(a, next)) {
return;
}
}
}
private static final class Observers<T> {
final MemberSingleObserver<T>[] observers;
// an observer is active until it is emitted to
final boolean[] active;
private int activeCount;
final int index;
Observers(MemberSingleObserver<T>[] observers, boolean[] active, int activeCount, int index) {
Preconditions.checkArgument(observers.length > 0 || index == 0, "index must be -1 for zero length array");
Preconditions.checkArgument(observers.length == active.length);
this.observers = observers;
this.index = index;
this.active = active;
this.activeCount = activeCount;
}
}
private static final class Emitter<T> implements Runnable {
private final Worker worker;
private final MemberSingleObserver<T> observer;
private final Member2<T> m;
Emitter(Worker worker, MemberSingleObserver<T> observer, Member2<T> m) {
this.worker = worker;
this.observer = observer;
this.m = m;
}
@Override
public void run() {
System.out.println("running run");
worker.dispose();
try {
observer.child.onSuccess(m);
observer.dispose();
} catch (Throwable e) {
RxJavaPlugins.onError(e);
}
}
}
static final class MemberSingleObserver<T> extends AtomicReference<MemberSingle<T>> implements Disposable {
private static final long serialVersionUID = -7650903191002190468L;
final SingleObserver<? super Member2<T>> child;
MemberSingleObserver(SingleObserver<? super Member2<T>> child, MemberSingle<T> parent) {
this.child = child;
lazySet(parent);
}
@Override
public void dispose() {
MemberSingle<T> parent = getAndSet(null);
if (parent != null) {
parent.remove(this);
}
}
@Override
public boolean isDisposed() {
return get() == null;
}
}
} |
package org.fife.ui.rtextarea;
import java.awt.AWTEvent;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ComponentEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JTextArea;
import javax.swing.event.CaretEvent;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.TextUI;
import javax.swing.text.AbstractDocument;
import javax.swing.text.BadLocationException;
import javax.swing.text.Caret;
import javax.swing.text.StyleContext;
/**
* This is the base class for <code>RTextArea</code>; basically it's just an
* extension of <code>javax.swing.JTextArea</code> adding a bunch of properties.
* <p>
*
* This class is only supposed to be overridden by <code>RTextArea</code>.
*
* @author Robert Futrell
* @version 0.8
*/
public abstract class RTextAreaBase extends JTextArea {
public static final String BACKGROUND_IMAGE_PROPERTY = "background.image";
public static final String CURRENT_LINE_HIGHLIGHT_COLOR_PROPERTY = "RTA.currentLineHighlightColor";
public static final String CURRENT_LINE_HIGHLIGHT_FADE_PROPERTY = "RTA.currentLineHighlightFade";
public static final String HIGHLIGHT_CURRENT_LINE_PROPERTY = "RTA.currentLineHighlight";
public static final String ROUNDED_SELECTION_PROPERTY = "RTA.roundedSelection";
private boolean tabsEmulatedWithSpaces; // If true, tabs will be expanded to spaces.
private boolean highlightCurrentLine; // If true, the current line is highlighted.
private Color currentLineColor; // The color used to highlight the current line.
private boolean marginLineEnabled; // If true, paint a "margin line."
private Color marginLineColor; // The color used to paint the margin line.
private int marginLineX; // The x-location of the margin line.
private int marginSizeInChars; // How many 'm' widths the margin line is over.
private boolean fadeCurrentLineHighlight; // "Fade effect" for current line highlight.
private boolean roundedSelectionEdges;
private int previousCaretY;
int currentCaretY; // Used to know when to rehighlight current line.
private BackgroundPainterStrategy backgroundPainter; // Paints the background.
private RTAMouseListener mouseListener;
private static final Color DEFAULT_CARET_COLOR = new ColorUIResource(255,51,51);
private static final Color DEFAULT_CURRENT_LINE_HIGHLIGHT_COLOR = new Color(255,255,170);
private static final Color DEFAULT_MARGIN_LINE_COLOR = new Color(255,224,224);
private static final int DEFAULT_TAB_SIZE = 4;
private static final int DEFAULT_MARGIN_LINE_POSITION = 80;
/**
* Constructor.
*/
public RTextAreaBase() {
init();
}
/**
* Constructor.
*
* @param doc The document for the editor.
*/
public RTextAreaBase(AbstractDocument doc) {
super(doc);
init();
}
/**
* Constructor.
*
* @param text The initial text to display.
*/
public RTextAreaBase(String text) {
// Don't call super(text) to avoid NPE due to our funky RTextAreaUI...
init();
setText(text);
}
public RTextAreaBase(int rows, int cols) {
super(rows, cols);
init();
}
public RTextAreaBase(String text, int rows, int cols) {
// Don't call this super() due to NPE from our funky RTextAreaUI...
//super(text, rows, cols);
super(rows, cols);
init();
setText(text);
}
public RTextAreaBase(AbstractDocument doc, String text, int rows,
int cols) {
// Don't call super() with text due to NPE from our funky RTextAreaUI...
super(doc, null/*text*/, rows, cols);
init();
setText(text);
}
/**
* Adds listeners that listen for changes to the current line, so we can
* update our "current line highlight." This is needed only because of an
* apparent difference between the JRE 1.4.2 and 1.5.0 (needed on 1.4.2,
* not needed on 1.5.0).
*/
private void addCurrentLineHighlightListeners() {
boolean add = true;
MouseMotionListener[] mouseMotionListeners = getMouseMotionListeners();
for (int i=0; i<mouseMotionListeners.length; i++) {
if (mouseMotionListeners[i]==mouseListener) {
add = false;
break;
}
}
if (add==true) {
//System.err.println("Adding mouse motion listener!");
addMouseMotionListener(mouseListener);
}
MouseListener[] mouseListeners = getMouseListeners();
for (int i=0; i<mouseListeners.length; i++) {
if (mouseListeners[i]==mouseListener) {
add = false;
break;
}
}
if (add==true) {
//System.err.println("Adding mouse listener!");
addMouseListener(mouseListener);
}
}
/*
* TODO: Figure out why RTextArea doesn't work with RTL orientation!
*/
// public void applyComponentOrientation(ComponentOrientation orientation) {
// super.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
/**
* Converts all instances of a number of spaces equal to a tab size
* into a tab in this text area.
*
* @see #convertTabsToSpaces
* @see #getTabsEmulated
* @see #setTabsEmulated
*/
public void convertSpacesToTabs() {
// FIXME: This is inefficient and will yield an OutOfMemoryError if
// done on a large document. We should scan 1 line at a time and
// replace; it'll be slower but safer.
int caretPosition = getCaretPosition();
int tabSize = getTabSize();
String tabInSpaces = "";
for (int i=0; i<tabSize; i++)
tabInSpaces += " ";
String text = getText();
setText(text.replaceAll(tabInSpaces, "\t"));
int newDocumentLength = getDocument().getLength();
// Place the caret back in its proper position.
if (caretPosition<newDocumentLength)
setCaretPosition(caretPosition);
else
setCaretPosition(newDocumentLength-1);
}
/**
* Converts all instances of a tab into a number of spaces equivalent
* to a tab in this text area.
*
* @see #convertSpacesToTabs
* @see #getTabsEmulated
* @see #setTabsEmulated
*/
public void convertTabsToSpaces() {
// FIXME: This is inefficient and will yield an OutOfMemoryError if
// done on a large document. We should scan 1 line at a time and
// replace; it'll be slower but safer.
int caretPosition = getCaretPosition();
int tabSize = getTabSize();
StringBuilder tabInSpaces = new StringBuilder();
for (int i=0; i<tabSize; i++)
tabInSpaces.append(' ');
String text = getText();
setText(text.replaceAll("\t", tabInSpaces.toString()));
// Put caret back at same place in document.
setCaretPosition(caretPosition);
}
/**
* Returns the caret event/mouse listener for <code>RTextArea</code>s.
*
* @return The caret event/mouse listener.
*/
protected abstract RTAMouseListener createMouseListener();
/**
* Returns the a real UI to install on this text component. Subclasses
* can override this method to return an extended version of
* <code>RTextAreaUI</code>.
*
* @return The UI.
*/
protected abstract RTextAreaUI createRTextAreaUI();
/**
* Forces the current line highlight to be repainted. This hack is
* necessary for those situations when the view (appearance) changes
* but the caret's location hasn't (and thus the current line highlight
* coordinates won't get changed). Examples of this are when
* word wrap is toggled and when syntax styles are changed in an
* <code>RSyntaxTextArea</code>.
*/
protected void forceCurrentLineHighlightRepaint() {
// Check isShowing() to prevent BadLocationException
// in constructor if linewrap is set to true.
if (isShowing()) {
// Changing previousCaretY makes us sure to get a repaint.
previousCaretY = -1;
// Trick it into checking for the need to repaint by firing
// a false caret event.
fireCaretUpdate(mouseListener);
}
}
/**
* Returns the <code>java.awt.Color</code> used as the background color for
* this text area. If a <code>java.awt.Image</code> image is currently
* being used instead, <code>null</code> is returned.
*
* @return The current background color, or <code>null</code> if an image
* is currently the background.
*/
@Override
public final Color getBackground() {
Object bg = getBackgroundObject();
return (bg instanceof Color) ? (Color)bg : null;
}
/**
* Returns the image currently used for the background.
* If the current background is currently a <code>java.awt.Color</code> and
* not a <code>java.awt.Image</code>, then <code>null</code> is returned.
*
* @return A <code>java.awt.Image</code> used for the background, or
* <code>null</code> if the background is not an image.
* @see #setBackgroundImage
*/
public final Image getBackgroundImage() {
Object bg = getBackgroundObject();
return (bg instanceof Image) ? (Image)bg : null;
}
/**
* Returns the <code>Object</code> representing the background for all
* documents in this tabbed pane; either a <code>java.awt.Color</code> or a
* <code>java.lang.Image</code> containing the image used as the background
* for this text area.
*
* @return The <code>Object</code> used for the background.
* @see #setBackgroundObject(Object newBackground)
*/
public final Object getBackgroundObject() {
if (backgroundPainter==null)
return null;
return (backgroundPainter instanceof ImageBackgroundPainterStrategy) ?
(Object)((ImageBackgroundPainterStrategy)backgroundPainter).
getMasterImage() :
(Object)((ColorBackgroundPainterStrategy)backgroundPainter).
getColor();
}
/**
* Gets the line number that the caret is on.
*
* @return The zero-based line number that the caret is on.
*/
public final int getCaretLineNumber() {
try {
return getLineOfOffset(getCaretPosition());
} catch (BadLocationException ble) {
return 0; // Never happens
}
}
/**
* Gets the position from the beginning of the current line that the caret
* is on.
*
* @return The zero-based position from the beginning of the current line
* that the caret is on.
*/
public final int getCaretOffsetFromLineStart() {
try {
int pos = getCaretPosition();
return pos - getLineStartOffset(getLineOfOffset(pos));
} catch (BadLocationException ble) {
return 0; // Never happens
}
}
/**
* Returns the color being used to highlight the current line. Note that
* if highlighting the current line is turned off, you will not be seeing
* this highlight.
*
* @return The color being used to highlight the current line.
* @see #getHighlightCurrentLine()
* @see #setHighlightCurrentLine(boolean)
* @see #setCurrentLineHighlightColor
*/
public Color getCurrentLineHighlightColor() {
return currentLineColor;
}
/**
* Returns the default caret color.
*
* @return The default caret color.
*/
public static final Color getDefaultCaretColor() {
return DEFAULT_CARET_COLOR;
}
/**
* Returns the "default" color for highlighting the current line. Note
* that this color was chosen only because it looks nice (to me) against a
* white background.
*
* @return The default color for highlighting the current line.
*/
public static final Color getDefaultCurrentLineHighlightColor() {
return DEFAULT_CURRENT_LINE_HIGHLIGHT_COLOR;
}
/**
* Returns the default font for text areas.
*
* @return The default font.
*/
public static final Font getDefaultFont() {
// Use StyleContext to get a composite font for better Asian language
// support; see Sun bug S282887.
StyleContext sc = StyleContext.getDefaultStyleContext();
Font font = null;
if (isOSX()) {
// Snow Leopard (1.6) uses Menlo as default monospaced font,
// pre-Snow Leopard used Monaco.
font = sc.getFont("Menlo", Font.PLAIN, 12);
if (!"Menlo".equals(font.getFamily())) {
font = sc.getFont("Monaco", Font.PLAIN, 12);
if (!"Monaco".equals(font.getFamily())) { // Shouldn't happen
font = sc.getFont("Monospaced", Font.PLAIN, 13);
}
}
}
else {
// Consolas added in Vista, used by VS2010+.
font = sc.getFont("Consolas", Font.PLAIN, 13);
if (!"Consolas".equals(font.getFamily())) {
font = sc.getFont("Monospaced", Font.PLAIN, 13);
}
}
//System.out.println(font.getFamily() + ", " + font.getName());
return font;
}
/**
* Returns the default foreground color for text in this text area.
*
* @return The default foreground color.
*/
public static final Color getDefaultForeground() {
return Color.BLACK;
}
/**
* Returns the default color for the margin line.
*
* @return The default margin line color.
* @see #getMarginLineColor()
* @see #setMarginLineColor(Color)
*/
public static final Color getDefaultMarginLineColor() {
return DEFAULT_MARGIN_LINE_COLOR;
}
/**
* Returns the default margin line position.
*
* @return The default margin line position.
* @see #getMarginLinePosition
* @see #setMarginLinePosition
*/
public static final int getDefaultMarginLinePosition() {
return DEFAULT_MARGIN_LINE_POSITION;
}
/**
* Returns the default tab size, in spaces.
*
* @return The default tab size.
*/
public static final int getDefaultTabSize() {
return DEFAULT_TAB_SIZE;
}
/**
* Returns whether the current line highlight is faded.
*
* @return Whether the current line highlight is faded.
* @see #setFadeCurrentLineHighlight
*/
public boolean getFadeCurrentLineHighlight() {
return fadeCurrentLineHighlight;
}
/**
* Returns whether or not the current line is highlighted.
*
* @return Whether or the current line is highlighted.
* @see #setHighlightCurrentLine(boolean)
* @see #getCurrentLineHighlightColor
* @see #setCurrentLineHighlightColor
*/
public boolean getHighlightCurrentLine() {
return highlightCurrentLine;
}
/**
* Returns the offset of the last character of the line that the caret is
* on.
*
* @return The last offset of the line that the caret is currently on.
*/
public final int getLineEndOffsetOfCurrentLine() {
try {
return getLineEndOffset(getCaretLineNumber());
} catch (BadLocationException ble) {
return 0; // Never happens
}
}
/**
* Returns the height of a line of text in this text area.
*
* @return The height of a line of text.
*/
public int getLineHeight() {
return getRowHeight();
}
/**
* Returns the offset of the first character of the line that the caret is
* on.
*
* @return The first offset of the line that the caret is currently on.
*/
public final int getLineStartOffsetOfCurrentLine() {
try {
return getLineStartOffset(getCaretLineNumber());
} catch (BadLocationException ble) {
return 0; // Never happens
}
}
/**
* Returns the color used to paint the margin line.
*
* @return The margin line color.
* @see #setMarginLineColor(Color)
*/
public Color getMarginLineColor() {
return marginLineColor;
}
/**
* Returns the margin line position (in pixels) from the left-hand side of
* the text area.
*
* @return The margin line position.
* @see #getDefaultMarginLinePosition
* @see #setMarginLinePosition
*/
public int getMarginLinePixelLocation() {
return marginLineX;
}
/**
* Returns the margin line position (which is the number of 'm' widths in
* the current font the margin line is over).
*
* @return The margin line position.
* @see #getDefaultMarginLinePosition
* @see #setMarginLinePosition
*/
public int getMarginLinePosition() {
return marginSizeInChars;
}
/**
* Returns whether selection edges are rounded in this text area.
*
* @return Whether selection edges are rounded.
* @see #setRoundedSelectionEdges(boolean)
*/
public boolean getRoundedSelectionEdges() {
return roundedSelectionEdges;
}
/**
* Returns whether or not tabs are emulated with spaces (i.e., "soft"
* tabs).
*
* @return <code>true</code> if tabs are emulated with spaces;
* <code>false</code> if they aren't.
* @see #setTabsEmulated
*/
public boolean getTabsEmulated() {
return tabsEmulatedWithSpaces;
}
/**
* Initializes this text area.
*/
protected void init() {
// Sets the UI. Note that setUI() is overridden in RTextArea to only
// update the popup menu; this method must be called to set the real
// UI. This is done because the look and feel of an RTextArea is
// independent of the installed Java look and feels.
setRTextAreaUI(createRTextAreaUI());
// So we get notified when the component is resized.
enableEvents(AWTEvent.COMPONENT_EVENT_MASK|AWTEvent.KEY_EVENT_MASK);
// Defaults for various properties.
setHighlightCurrentLine(true);
setCurrentLineHighlightColor(getDefaultCurrentLineHighlightColor());
setMarginLineEnabled(false);
setMarginLineColor(getDefaultMarginLineColor());
setMarginLinePosition(getDefaultMarginLinePosition());
setBackgroundObject(Color.WHITE);
setWrapStyleWord(true);// We only support wrapping at word boundaries.
setTabSize(5);
setForeground(Color.BLACK);
setTabsEmulated(false);
// Stuff needed by the caret listener below.
previousCaretY = currentCaretY = getInsets().top;
// Stuff to highlight the current line.
mouseListener = createMouseListener();
// Also acts as a focus listener so we can update our shared actions
// (cut, copy, etc. on the popup menu).
addFocusListener(mouseListener);
addCurrentLineHighlightListeners();
}
/**
* Returns whether or not the margin line is being painted.
*
* @return Whether or not the margin line is being painted.
* @see #setMarginLineEnabled
*/
public boolean isMarginLineEnabled() {
return marginLineEnabled;
}
/**
* Returns whether the OS we're running on is OS X.
*
* @return Whether the OS we're running on is OS X.
*/
public static boolean isOSX() {
// Recommended at:
String osName = System.getProperty("os.name").toLowerCase();
return osName.startsWith("mac os x");
}
/**
* Paints the text area.
*
* @param g The graphics context with which to paint.
*/
@Override
protected void paintComponent(Graphics g) {
//long startTime = System.currentTimeMillis();
backgroundPainter.paint(g, getVisibleRect());
// Paint the main part of the text area.
TextUI ui = getUI();
if (ui != null) {
// Not allowed to modify g, so make a copy.
Graphics scratchGraphics = g.create();
try {
ui.update(scratchGraphics, this);
} finally {
scratchGraphics.dispose();
}
}
//long endTime = System.currentTimeMillis();
//System.err.println(endTime-startTime);
}
/**
* Updates the current line highlight location.
*/
protected void possiblyUpdateCurrentLineHighlightLocation() {
int width = getWidth();
int lineHeight = getLineHeight();
int dot = getCaretPosition();
// If we're wrapping lines we need to check the actual y-coordinate
// of the caret, not just the line number, since a single logical
// line can span multiple physical lines.
if (getLineWrap()) {
try {
Rectangle temp = modelToView(dot);
if (temp!=null) {
currentCaretY = temp.y;
}
} catch (BadLocationException ble) {
ble.printStackTrace(); // Should never happen.
}
}
// No line wrap - we can simply check the line number (quicker).
else {
// Document doc = getDocument();
// if (doc!=null) {
// Element map = doc.getDefaultRootElement();
// int caretLine = map.getElementIndex(dot);
// Rectangle alloc = ((RTextAreaUI)getUI()).
// getVisibleEditorRect();
// if (alloc!=null)
// currentCaretY = alloc.y + caretLine*lineHeight;
// Modified for code folding requirements
try {
Rectangle temp = modelToView(dot);
if (temp!=null) {
currentCaretY = temp.y;
}
} catch (BadLocationException ble) {
ble.printStackTrace(); // Should never happen.
}
}
// Repaint current line (to fill in entire highlight), and old line
// (to erase entire old highlight) if necessary. Always repaint
// current line in case selection is added or removed.
repaint(0,currentCaretY, width,lineHeight);
if (previousCaretY!=currentCaretY) {
repaint(0,previousCaretY, width,lineHeight);
}
previousCaretY = currentCaretY;
}
/**
* Overridden so we can tell when the text area is resized and update the
* current-line highlight, if necessary (i.e., if it is enabled and if
* lineWrap is enabled.
*
* @param e The component event about to be sent to all registered
* <code>ComponentListener</code>s.
*/
@Override
protected void processComponentEvent(ComponentEvent e) {
// In line wrap mode, resizing the text area means that the caret's
// "line" could change - not to a different logical line, but a
// different physical one. So, here we force a repaint of the current
// line's highlight if necessary.
if (e.getID()==ComponentEvent.COMPONENT_RESIZED &&
getLineWrap()==true && getHighlightCurrentLine()) {
previousCaretY = -1; // So we are sure to repaint.
fireCaretUpdate(mouseListener);
}
super.processComponentEvent(e);
}
/**
* Sets the background color of this text editor. Note that this is
* equivalent to calling <code>setBackgroundObject(bg)</code>.
*
* NOTE: the opaque property is set to <code>true</code> when the
* background is set to a color (by this method). When an image is used
* for the background, opaque is set to false. This is because
* we perform better when setOpaque is true, but if we use an
* image for the background when opaque is true, we get on-screen
* garbage when the user scrolls via the arrow keys. Thus we
* need setOpaque to be false in that case.<p>
* You never have to change the opaque property yourself; it is always done
* for you.
*
* @param bg The color to use as the background color.
*/
@Override
public void setBackground(Color bg) {
Object oldBG = getBackgroundObject();
if (oldBG instanceof Color) { // Just change color of strategy.
((ColorBackgroundPainterStrategy)backgroundPainter).
setColor(bg);
}
else { // Was an image painter...
backgroundPainter = new ColorBackgroundPainterStrategy(bg);
}
setOpaque(true);
firePropertyChange("background", oldBG, bg);
repaint();
}
/**
* Sets this image as the background image. This method fires a
* property change event of type {@link #BACKGROUND_IMAGE_PROPERTY}.<p>
*
* NOTE: the opaque property is set to <code>true</code> when the
* background is set to a color. When an image is used for the
* background (by this method), opaque is set to false. This is because
* we perform better when setOpaque is true, but if we use an
* image for the background when opaque is true, we get on-screen
* garbage when the user scrolls via the arrow keys. Thus we
* need setOpaque to be false in that case.<p>
* You never have to change the opaque property yourself; it is always done
* for you.
*
* @param image The image to use as this text area's background.
* @see #getBackgroundImage
*/
public void setBackgroundImage(Image image) {
Object oldBG = getBackgroundObject();
if (oldBG instanceof Image) { // Just change image being displayed.
((ImageBackgroundPainterStrategy)backgroundPainter).
setImage(image);
}
else { // Was a color strategy...
ImageBackgroundPainterStrategy strategy =
new BufferedImageBackgroundPainterStrategy(this);
strategy.setImage(image);
backgroundPainter = strategy;
}
setOpaque(false);
firePropertyChange(BACKGROUND_IMAGE_PROPERTY, oldBG, image);
repaint();
}
/**
* Makes the background into this <code>Object</code>.
*
* @param newBackground The <code>java.awt.Color</code> or
* <code>java.awt.Image</code> object. If <code>newBackground</code>
* is not either of these, the background is set to plain white.
*/
public void setBackgroundObject(Object newBackground) {
if (newBackground instanceof Color) {
setBackground((Color)newBackground);
}
else if (newBackground instanceof Image) {
setBackgroundImage((Image)newBackground);
}
else {
setBackground(Color.WHITE);
}
}
/*
* TODO: Figure out why RTextArea doesn't work with RTL (e.g. Arabic)
* and fix it!
*/
// public void setComponentOrientation(ComponentOrientation o) {
// if (!o.isLeftToRight()) {
// o = ComponentOrientation.LEFT_TO_RIGHT;
// super.setComponentOrientation(o);
/**
* Sets the color to use to highlight the current line. Note that if
* highlighting the current line is turned off, you will not be able to
* see this highlight. This method fires a property change of type
* {@link #CURRENT_LINE_HIGHLIGHT_COLOR_PROPERTY}.
*
* @param color The color to use to highlight the current line.
* @throws NullPointerException if <code>color</code> is <code>null</code>.
* @see #getHighlightCurrentLine()
* @see #setHighlightCurrentLine(boolean)
* @see #getCurrentLineHighlightColor
*/
public void setCurrentLineHighlightColor(Color color) {
if (color==null)
throw new NullPointerException();
if (!color.equals(currentLineColor)) {
Color old = currentLineColor;
currentLineColor = color;
firePropertyChange(CURRENT_LINE_HIGHLIGHT_COLOR_PROPERTY,
old, color);
}
}
/**
* Sets whether the current line highlight should have a "fade" effect.
* This method fires a property change event of type
* <code>CURRENT_LINE_HIGHLIGHT_FADE_PROPERTY</code>.
*
* @param fade Whether the fade effect should be enabled.
* @see #getFadeCurrentLineHighlight
*/
public void setFadeCurrentLineHighlight(boolean fade) {
if (fade!=fadeCurrentLineHighlight) {
fadeCurrentLineHighlight = fade;
if (getHighlightCurrentLine())
forceCurrentLineHighlightRepaint();
firePropertyChange(CURRENT_LINE_HIGHLIGHT_FADE_PROPERTY,
!fade, fade);
}
}
/**
* Sets the font for this text area. This is overridden only so that we
* can update the size of the "current line highlight" and the location of
* the "margin line," if necessary.
*
* @param font The font to use for this text component.
*/
@Override
public void setFont(Font font) {
if (font!=null && font.getSize()<=0) {
throw new IllegalArgumentException("Font size must be > 0");
}
super.setFont(font);
if (font!=null) {
updateMarginLineX();
if (highlightCurrentLine)
possiblyUpdateCurrentLineHighlightLocation();
}
}
/**
* Sets whether or not the current line is highlighted. This method
* fires a property change of type {@link #HIGHLIGHT_CURRENT_LINE_PROPERTY}.
*
* @param highlight Whether or not to highlight the current line.
* @see #getHighlightCurrentLine()
* @see #getCurrentLineHighlightColor
* @see #setCurrentLineHighlightColor
*/
public void setHighlightCurrentLine(boolean highlight) {
if (highlight!=highlightCurrentLine) {
highlightCurrentLine = highlight;
firePropertyChange(HIGHLIGHT_CURRENT_LINE_PROPERTY,
!highlight, highlight);
repaint(); // Repaint entire width of line.
}
}
/**
* Sets whether or not word wrap is enabled. This is overridden so that
* the "current line highlight" gets updated if it needs to be.
*
* @param wrap Whether or not word wrap should be enabled.
*/
@Override
public void setLineWrap(boolean wrap) {
super.setLineWrap(wrap);
forceCurrentLineHighlightRepaint();
}
/**
* Overridden to update the current line highlight location.
*
* @param insets The new insets.
*/
@Override
public void setMargin(Insets insets) {
Insets old = getInsets();
int oldTop = old!=null ? old.top : 0;
int newTop = insets!=null ? insets.top : 0;
if (oldTop!=newTop) {
// The entire editor will be automatically repainted if it is
// visible, so no need to call repaint() or forceCurrentLine...().
previousCaretY = currentCaretY = newTop;
}
super.setMargin(insets);
}
/**
* Sets the color used to paint the margin line.
*
* @param color The new margin line color.
* @see #getDefaultMarginLineColor()
* @see #getMarginLineColor()
*/
public void setMarginLineColor(Color color) {
marginLineColor = color;
if (marginLineEnabled) {
Rectangle visibleRect = getVisibleRect();
repaint(marginLineX,visibleRect.y, 1,visibleRect.height);
}
}
/**
* Enables or disables the margin line.
*
* @param enabled Whether or not the margin line should be enabled.
* @see #isMarginLineEnabled
*/
public void setMarginLineEnabled(boolean enabled) {
if (enabled!=marginLineEnabled) {
marginLineEnabled = enabled;
if (marginLineEnabled) {
Rectangle visibleRect = getVisibleRect();
repaint(marginLineX,visibleRect.y, 1,visibleRect.height);
}
}
}
/**
* Sets the number of 'm' widths the margin line is over.
*
* @param size The margin size.
* #see #getDefaultMarginLinePosition
* @see #getMarginLinePosition
*/
public void setMarginLinePosition(int size) {
marginSizeInChars = size;
if (marginLineEnabled) {
Rectangle visibleRect = getVisibleRect();
repaint(marginLineX,visibleRect.y, 1,visibleRect.height);
updateMarginLineX();
repaint(marginLineX,visibleRect.y, 1,visibleRect.height);
}
}
/**
* Sets whether the edges of selections are rounded in this text area.
* This method fires a property change of type
* {@link #ROUNDED_SELECTION_PROPERTY}.
*
* @param rounded Whether selection edges should be rounded.
* @see #getRoundedSelectionEdges()
*/
public void setRoundedSelectionEdges(boolean rounded) {
if (roundedSelectionEdges!=rounded) {
roundedSelectionEdges = rounded;
Caret c = getCaret();
if (c instanceof ConfigurableCaret) {
((ConfigurableCaret)c).setRoundedSelectionEdges(rounded);
if (c.getDot()!=c.getMark()) { // e.g., there's is a selection
repaint();
}
}
firePropertyChange(ROUNDED_SELECTION_PROPERTY, !rounded,
rounded);
}
}
/**
* Sets the UI for this <code>RTextArea</code>. Note that, for instances
* of <code>RTextArea</code>, <code>setUI</code> only updates the popup
* menu; this is because <code>RTextArea</code>s' look and feels are
* independent of the Java Look and Feel. This method is here so
* subclasses can set a UI (subclass of <code>RTextAreaUI</code>) if they
* have to.
*
* @param ui The new UI.
* @see #setUI
*/
protected void setRTextAreaUI(RTextAreaUI ui) {
super.setUI(ui);
// Workaround as setUI makes the text area opaque, even if we don't
// want it to be.
setOpaque(getBackgroundObject() instanceof Color);
}
/**
* Changes whether or not tabs should be emulated with spaces (i.e., soft
* tabs). Note that this affects all tabs inserted AFTER this call, not
* tabs already in the document. For that, see
* {@link #convertTabsToSpaces} and {@link #convertSpacesToTabs}.
*
* @param areEmulated Whether or not tabs should be emulated with spaces.
* @see #convertSpacesToTabs
* @see #convertTabsToSpaces
* @see #getTabsEmulated
*/
public void setTabsEmulated(boolean areEmulated) {
tabsEmulatedWithSpaces = areEmulated;
}
/**
* Workaround, since in JDK1.4 it appears that <code>setTabSize()</code>
* doesn't work for a <code>JTextArea</code> unless you use the constructor
* specifying the number of rows and columns...<p>
* Sets the number of characters to expand tabs to. This will be multiplied
* by the maximum advance for variable width fonts. A PropertyChange event
* ("tabSize") is fired when the tab size changes.
*
* @param size Number of characters to expand to.
*/
@Override
public void setTabSize(int size) {
super.setTabSize(size);
boolean b = getLineWrap();
setLineWrap(!b);
setLineWrap(b);
}
/**
* This is here so subclasses such as <code>RSyntaxTextArea</code> that
* have multiple fonts can define exactly what it means, for example, for
* the margin line to be "80 characters" over.
*/
protected void updateMarginLineX() {
Font font = getFont();
if (font == null) {
marginLineX = 0;
return;
}
marginLineX = getFontMetrics(font).charWidth('m') *
marginSizeInChars;
}
/**
* Returns the y-coordinate of the specified line.
*
* @param line The line number.
* @return The y-coordinate of the top of the line, or <code>-1</code> if
* this text area doesn't yet have a positive size or the line is
* hidden (i.e. from folding).
* @throws BadLocationException If <code>line</code> isn't a valid line
* number for this document.
*/
public int yForLine(int line) throws BadLocationException {
return ((RTextAreaUI)getUI()).yForLine(line);
}
/**
* Returns the y-coordinate of the line containing an offset.
*
* @param offs The offset info the document.
* @return The y-coordinate of the top of the offset, or <code>-1</code> if
* this text area doesn't yet have a positive size or the line is
* hidden (i.e. from folding).
* @throws BadLocationException If <code>offs</code> isn't a valid offset
* into the document.
*/
public int yForLineContaining(int offs) throws BadLocationException {
return ((RTextAreaUI)getUI()).yForLineContaining(offs);
}
protected class RTAMouseListener extends CaretEvent implements
MouseListener, MouseMotionListener, FocusListener {
RTAMouseListener(RTextAreaBase textArea) {
super(textArea);
}
public void focusGained(FocusEvent e) {}
public void focusLost(FocusEvent e) {}
public void mouseDragged(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
@Override
public int getDot() {
return dot;
}
@Override
public int getMark() {
return mark;
}
protected int dot;
protected int mark;
}
} |
package org.gbif.imgcache;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.imageio.ImageIO;
import com.google.common.base.Preconditions;
import com.google.common.io.ByteStreams;
import com.google.common.io.Closer;
import com.google.common.net.HttpHeaders;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ImageCacheService {
private static final Logger LOG = LoggerFactory.getLogger(ImageCacheService.class);
private final File repo;
private static final String ENC = "UTF8";
private static final String TARGET_FMT = "jpeg";
private static final String MIME_TYPE = "image/" + TARGET_FMT;
private static final String DFT_FILENAME = "image";
private static final String HEAD_METHOD = "HEAD";
private static final int TIMEOUT_MS = 2*60*1000; // 2 minutes
private static final int CONNECT_TIMEOUT_MS = 30*1000; // 30 seconds
@Inject
public ImageCacheService(@Named("imgcache.repository") String repository) {
repo = new File(repository);
LOG.info("Use image repository {}", repo.getAbsolutePath());
if (!repo.exists() && !repo.isDirectory() && !repo.canWrite()) {
throw new IllegalStateException("imgcache.repository needs to be an existing, writable directory: "
+ repo.getAbsolutePath());
}
}
public CachedImage get(URL url, ImageSize size) throws IOException {
Preconditions.checkNotNull(url);
File imgFile = location(url, size);
if (!imgFile.exists()) {
cacheImage(url);
}
// TODO: store mime type or deduce from image/file suffix
return new CachedImage(url, size, MIME_TYPE, imgFile);
}
private static String buildFileName(URL url, ImageSize size) {
// try to get some sensible filename - optional
String fileName;
try {
fileName = new File(url.getPath()).getName();
} catch (Exception e) {
fileName = DFT_FILENAME;
}
if (size != ImageSize.ORIGINAL) {
fileName += "-" + size.name().charAt(0) + "." + TARGET_FMT;
}
return fileName;
}
private void cacheImage(URL url) throws IOException {
LOG.info("Caching image {}", url);
copyOriginal(url);
// now produce thumbnails from the original
produceImage(url, ImageSize.THUMBNAIL, ImageSize.SMALL, ImageSize.MIDSIZE, ImageSize.LARGE);
}
/**
* Creates a copy of the file with its original size.
*/
private void copyOriginal(URL url) throws IOException {
OutputStream out = null;
InputStream source = null;
try (Closer closer = Closer.create()) {
HttpURLConnection con = null;
URL currentUrl = url;
int resp;
int redirectCount = 0;
while (true) {
con = (HttpURLConnection) currentUrl.openConnection();
con.setConnectTimeout(CONNECT_TIMEOUT_MS);
con.setReadTimeout(TIMEOUT_MS);
con.setRequestProperty(HttpHeaders.USER_AGENT, "GBIF image cache");
LOG.debug("URL {} gave HTTP response {}", currentUrl, con.getResponseCode());
resp = con.getResponseCode();
if (resp == HttpURLConnection.HTTP_MOVED_PERM
|| resp == HttpURLConnection.HTTP_MOVED_PERM
|| resp == HttpURLConnection.HTTP_SEE_OTHER) {
redirectCount++;
if (redirectCount > 10) {
throw new IOException(String.format("Too many redirects when retrieving from URL %s", url));
} else {
String location = con.getHeaderField(HttpHeaders.LOCATION);
currentUrl = new URL(currentUrl, location);
continue;
}
}
break;
}
if (resp != HttpURLConnection.HTTP_OK) {
throw new IOException(String.format("HTTP %s when retrieving from URL %s (%i redirects, started at %s)", resp, currentUrl, redirectCount, url));
}
source = closer.register(con.getInputStream());
// create parent folder that is unique for the original image
File origImg = location(url, ImageSize.ORIGINAL);
origImg.getParentFile().mkdir();
out = closer.register(new FileOutputStream(origImg));
ByteStreams.copy(source, out);
}
}
/**
* Creates a location for the image URL with a suffix for the specified size.
*/
private File location(URL url, ImageSize size) throws IOException {
File folder;
try {
folder = new File(repo, URLEncoder.encode(url.toString(), ENC));
} catch (UnsupportedEncodingException e) {
LOG.error("Error setting image location", e);
throw new IOException("Encoding not supported", e);
}
return new File(folder, buildFileName(url, size));
}
/**
* Produces an image for each size in the sizes parameter.
*/
private void produceImage(URL url, ImageSize... sizes) throws IOException {
for (ImageSize size : sizes) {
createImage(url, size);
}
}
/**
* Produces a single image from the url with the specified size.
*/
private void createImage(URL url, ImageSize size) throws IOException {
File orig = location(url, ImageSize.ORIGINAL);
File calc = location(url, size);
BufferedImage bufferedImage = ImageIO.read(orig);
Thumbnails.Builder<BufferedImage> thumb = Thumbnails.of(bufferedImage)
.size(size.width, size.height)
.outputFormat(TARGET_FMT)
.outputQuality(0.85);
// crop thumbnails to squares
if (ImageSize.THUMBNAIL == size) {
thumb.crop(Positions.CENTER);
}
// process
thumb.toFile(calc);
bufferedImage.flush();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.