lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
apache-2.0
error: pathspec 'cli/src/de/dhbw/mannheim/cloudraid/client/cli/CLIMain.java' did not match any file(s) known to git
969c3f6e5a5e61d6d1e6275a8d23254eedb03a1c
1
fbausch/CloudRAID-Client
package de.dhbw.mannheim.cloudraid.client.cli; public class CLIMain { public static void main(String[] args) { System.err.println("Not yet implemented."); } }
cli/src/de/dhbw/mannheim/cloudraid/client/cli/CLIMain.java
added directory for CLI implementation
cli/src/de/dhbw/mannheim/cloudraid/client/cli/CLIMain.java
added directory for CLI implementation
<ide><path>li/src/de/dhbw/mannheim/cloudraid/client/cli/CLIMain.java <add>package de.dhbw.mannheim.cloudraid.client.cli; <add> <add>public class CLIMain { <add> <add> public static void main(String[] args) { <add> System.err.println("Not yet implemented."); <add> } <add> <add>}
JavaScript
mit
398a8b8ab43c729be62ef9dae9f329eb8c963b95
0
mui-org/material-ui,oliviertassinari/material-ui,rscnt/material-ui,oliviertassinari/material-ui,mbrookes/material-ui,mbrookes/material-ui,callemall/material-ui,callemall/material-ui,oliviertassinari/material-ui,rscnt/material-ui,mbrookes/material-ui,callemall/material-ui,callemall/material-ui,mui-org/material-ui,rscnt/material-ui,mui-org/material-ui
const synonyms = { AccessAlarm: 'clock time', AccessAlarms: 'clock time', Accessibility: 'accessible body help human person user', AccessibilityNew: 'accessible arms body help human person user', Accessible: 'accessibility body help human person user wheelchair', AccessibleForward: 'accessibility body help human person wheelchair', AccessTime: 'clock time', AccountBalance: 'bank building court money payment structure temple transaction', AccountBalanceWallet: 'money payment transaction', AccountBox: 'avatar person profile square thumbnail user', AccountCircle: 'avatar person profile thumbnail user', AccountTree: 'sitemap project', AcUnit: 'freeze snowflake', Add: 'create item new plus', AddAlarm: 'clock plus time', AddAlert: 'announcement bell callout information notification plus reminder', AddAPhoto: 'camera', AddBox: 'create new plus square', AddCircle: 'create new plus', AddCircleOutline: 'create new plus', AddLocation: 'gps', AddShoppingCart: 'checkout plus', AddToPhotos: 'plus', AddToQueue: 'backlog display lineup monitor plus television watch', Adjust: 'circle', AirlineSeatFlat: 'bed sleep', AirlineSeatFlatAngled: 'bed sleep', AirlineSeatIndividualSuite: 'bed sleep', AirplanemodeActive: 'flying', AirplanemodeInactive: 'flying', Airplay: 'apple arrow connect control device monitor screen signal television', AirportShuttle: 'bus car vehicle', Alarm: 'clock countdown time', AlarmAdd: 'clock plus time', AlarmOff: 'clock disabled stop time', AlarmOn: 'checkmark clock enabled ready start time', Album: 'artist cd music play record track vinyl', AllInbox: 'delivery email letter post send', AllInclusive: 'infinite', AllOut: 'arrows circle directional expand shape', Android: 'brand character logo mascot operating system toy', Announcement: 'alert balloon bubble chat comment exclamation message news speech', Apartment: 'building', Apple: 'brand logo', Apps: 'grid homescreen icons', ArrowBack: 'left', ArrowBackIos: 'left', ArrowRightAlt: 'pointing shape', ArrowUpward: 'submit', ArtTrack: 'display format insert', AspectRatio: 'expand image monitor resolution scale screen size square', Assessment: 'analytics bars chart graph measure metrics tracking report', Assignment: 'article clipboard document task text writing', AssignmentInd: 'clipboard document person profile task user', AssignmentLate: 'alert announcement clipboard exclamation task', AssignmentReturn: 'arrow clipboard left point task', AssignmentReturned: 'arrow clipboard down point task', AssignmentTurnedIn: 'checkmark clipboard complete done finished task', Assistant: 'chat comment star', AttachFile: 'item paperclip', Attachment: 'file item paperclip', AttachMoney: 'cash currency dollar finance price profit sale', Audiotrack: 'note', Autorenew: 'arrows cached inprogress loader loading refresh rotate status pending', AvTimer: 'clock countdown minutes seconds stopwatch', Backspace: 'clear delete remove', Backup: 'arrow cloud point submit upload', BarChart: 'anlytics graph', Bathtub: 'clean shower', BatteryAlert: 'exclamation', BatteryChargingFull: 'lightning', BatteryUnknown: 'question', BeachAccess: 'parasol sun umbrella', Beenhere: 'checkmark', Biotech: 'test', Block: 'allowed banned cancel disable not', Bluetooth: 'network wireless', BluetoothConnected: 'network wireless', BluetoothDisabled: 'network wireless', BluetoothSearching: 'network wireless', BlurCircular: 'circle', Book: 'bookmark reading blog', Bookmark: 'favorite remember save', BookmarkBorder: 'favorite outline remember save', Bookmarks: 'remember save', BorderColor: 'create marker pencil', BrandingWatermark: 'emblem format identity logo stamp', Brightness2: 'moon night', Brightness3: 'moon night', Brightness4: 'dark moon night sun', Brightness5: 'sun', Brightness6: 'sun', Brightness7: 'sun light', BrokenImage: 'picture', Brush: 'paint', BubbleChart: 'analytics graph', BugReport: 'animal file insect issue ticket', Build: 'spanner tool wrench', BurstMode: 'image picture', Business: 'address apartment building company flat office structure', BusinessCenter: 'briefcase suitcase', Cached: 'arrows inprogress loader loading refresh reload renew rotate', Cake: 'birthday pie', CalendarToday: 'date event month remember reminder week', CalendarViewDay: 'month remember reminder today week', Call: 'device mobile phone talk', CallEnd: 'device mobile phone talk', CallMade: 'arrow device mobile', CallMerge: 'arrow device mobile', CallMissed: 'arrow device mobile', CallMissedOutgoing: 'arrow device mobile', CallReceived: 'arrow device mobile', CallSplit: 'arrow device mobile', CallToAction: 'alert bar cta information message notification', CameraEnhance: 'lens photo picture quality', Cancel: 'close cross disable status', CancelPresentation: 'close device screen share x', CardGiftcard: 'certificate creditcard present', CardMembership: 'certificate creditcard subscription', CardTravel: 'creditcard membership miles trip', Casino: 'dice', Cast: 'chromecast', CastConnected: 'chromecast', ChangeHistory: 'shape triangle', Chat: 'bubble comment message speech talk text', ChatBubble: 'comment message speech talk text', ChatBubbleOutline: 'comment message speech talk text', Check: 'checkmark success tick', CheckBox: 'checkmark square success tick', CheckBoxOutlineBlank: 'checkmark square tick', CheckCircle: 'checkmark complete done finished success tick', CheckCircleOutline: 'checkmark complete done finished success tick', ChevronLeft: 'arrow', ChevronRight: 'arrow', ChildCare: 'baby', ChildFriendly: 'baby', ChromeReaderMode: 'text', Class: 'category item', Clear: 'allowed cancel cross disable not times x', ClearAll: 'delete document erase format lines list notifications wipe', Close: 'allowed cancel cross disable not times x status', ClosedCaption: 'accessible decoder language subtitles', Cloud: 'weather', CloudDone: 'checkmark', Code: 'brackets css developer engineering html parenthesis platform', Colorize: 'color picker pipette', Comment: 'bubble chat document message note', Commute: 'car train transportation vehicle', CompareArrows: 'directional facing pointing', Computer: 'laptop monitor pc', ConfirmationNumber: 'ticket', Contactless: 'applepay tap wifi', ContactMail: 'address information person profile user', ContactPhone: 'information number person profile user', Contacts: 'address information number person phone profile user', ContactSupport: 'alert announcement bubble help information mark question speech', ControlCamera: 'adjust arrows direction left move right', ControlPoint: 'circle plus', ControlPointDuplicate: 'circle plus', Copyright: 'emblem symbol', Create: 'item new pencil write', CreateNewFolder: 'directory', CreditCard: 'charge creditcard finance information money payment price', Crop169: 'image picture square', Crop32: 'image picture square', Crop54: 'image picture square', Crop75: 'image picture square', CropDin: 'image picture square', CropFree: 'barcode qrcode square', CropLandscape: 'image picture square', CropOriginal: 'image picture square', CropPortrait: 'image picture square', Dashboard: 'cards rectangle shapes square', DataUsage: 'circle', DateRange: 'agenda calendar event month remember reminder today week', Deck: 'furniture garden patio', Delete: 'bin garbage junk recycle remove trashcan', DeleteForever: 'bin garbage junk recycle remove trashcan x', DeleteOutline: 'can garbage remove trash', DeleteSweep: 'bin junk recycle trashcan', Description: 'article bill document file invoice item text writing', DesktopAccessDisabled: 'apple device monitor off pc screen', DesktopMac: 'apple monitor pc', DesktopWindows: 'monitor pc', Details: 'triangle', DeveloperBoard: 'devkit', DeveloperMode: 'code', Devices: 'laptop mobile phone', DevicesOther: 'smartwatch', DialerSip: 'call internet phone protocol routing', Dialpad: 'call device dots numbers phone', Directions: 'arrow naviate', DirectionsBike: 'bicycle', DirectionsRun: 'health person', DirectionsTransit: 'metro subway', DirectionsWalk: 'person', DiscFull: 'cd exclamation vinyl', Dns: 'address bars domain information ip list lookup name network server', Dock: 'charger', Domain: 'building', DomainDisabled: 'building internet off website', Done: 'checkmark complete finished success tick', DoneAll: 'checkmark complete finished multiple success tick', DoneOutline: 'checkmark complete finished success tick', DonutLarge: 'chart circle complete graph inprogress,', DonutSmall: 'chart circle', DoubleArrow: 'chevron right', Drafts: 'email envelope letter read', DragHandle: 'lines', DragIndicator: 'circle dots drop move shape shift', DriveEta: 'car transport vehicle', Duo: 'call chat conference device video', Dvr: 'laptop monitor', DynamicFeed: 'live refresh update', Eco: 'environment green leaf', EditLocation: 'gps map pin write', Eject: 'arrow player remove triangle up', Elderly: 'old', Email: 'envelope letter message note post receive send write', EmojiEmotions: 'emoticon face happy like smiley', EmojiFoodBeverage: 'cup dring mug tea', EmojiNature: 'bee flower honey', EmojiObjects: 'lamp lightbulb', EmojiPeople: 'man person wave waving', EmojiSymbols: 'ampersand music note percent', EmojiTransportation: 'building car commute company office vehicle', EnhancedEncryption: 'lock security', Equalizer: 'adjustment chart graph noise sound static volume', Error: 'alert announcement circle danger exclamation feedback problem warning', ErrorOutline: 'alert announcement circle danger exclamation feedback problem warning', Euro: 'cash currency finance money price profit', EuroSymbol: 'cash currency dollar finance money price profit', Event: 'agenda calendar date item mark month range remember reminder today week', EventAvailable: 'agenda calendar date item', EventBusy: 'agenda calendar date item', EventNote: 'agenda calendar date item', EventSeat: 'assigned bench chair reservation row section sit', EvStation: 'car charge filling fuel gasoline power station vehicle', ExitToApp: 'arrow back leave login logout pointing quit right signin signup register signout', ExpandLess: 'arrow up', ExpandMore: 'arrow down', Explicit: 'adult content language', Explore: 'compass destination location map needle travel', ExploreOff: 'compass destination disabled location map needle travel', Exposure: 'minus plus', Extension: 'extended item jigsaw piece puzzle shape add-ons', Face: 'avatar eyes human person profile thumbnail user', Facebook: 'brand logo social', Fastfood: 'burger drink', FastForward: 'control music speed time video', FastRewind: 'control music speed time video', Favorite: 'health heart like love remember save shape success', FavoriteBorder: 'health heart like love remember save shape success', FeaturedPlayList: 'audio collection highlighted item music playlist recommended', FeaturedVideo: 'highlighted item play recommended watch,advertised', Feedback: 'alert announcement bubble chat comment exclamation message speech', FiberDvr: 'digital electronics network recorder tv video', FiberManualRecord: 'circle dot play watch', FiberNew: 'network', FiberPin: 'network', FiberSmartRecord: 'play watch', FileCopy: 'bill invoice item page duplicate clone', FilterDrama: 'cloud', FilterHdr: 'mountains', FilterList: 'lines', FilterVintage: 'flower', FindInPage: 'document glass look magnifying paper search see', FindReplace: 'arrows glass inprogress look magnifying refresh rotate search see', Fingerprint: 'biometrics identification identity reader thumbprint touchid', Fireplace: 'flame', FirstPage: 'arrow', FitnessCenter: 'health weights workout', FiveG: '5g', Flare: 'bright lensflare light shine sparkle star sun', FlashAuto: 'lightning', FlashOff: 'lightning', FlashOn: 'lightning', Flight: 'airplane flying', FlightLand: 'airplane arrival arriving flying landing transportation travel', FlightTakeoff: 'airplane departed departing flying landing transportation travel', FlipCameraAndroid: 'front rear reverse', FlipCameraIos: 'front rear reverse', FlipToBack: 'arrangement front move order sort', FlipToFront: 'arrangement back move order sort', Folder: 'directory', FolderOpen: 'directory', FolderShared: 'directory', FolderSpecial: 'directory', FontDownload: 'letter square', FormatAlignCenter: 'lines', FormatAlignJustify: 'lines', FormatAlignLeft: 'lines', FormatAlignRight: 'lines', FormatColorFill: 'bucket', FormatColorReset: 'drop liquid water', FormatListBulleted: 'task todo', FormatListNumbered: 'task todo', FormatListNumberedRtl: 'task todo', FormatPaint: 'paintroller', FormatQuote: 'quotation', FormatTextdirectionLToR: 'paragraph', FormatTextdirectionRToL: 'paragraph', Forum: 'bubble chat community conversation hub messages speech talk', Forward: 'arrow', Forward10: 'arrow circle control fast music rotate speed time video', Forward30: 'arrow circle control fast music rotate speed time video', Forward5: 'arrow circle control fast music rotate speed time video', FourK: '4000 display pixels resolution', FreeBreakfast: 'coffee drink tea', Functions: 'math sigma', Games: 'adjust arrows controller direction dpad left move nintendo playstation right xbox', Gavel: 'court document government hammer judge law mallet official police rules', Gesture: 'drawing line', GetApp: 'arrow download pointing retrieve', Gif: 'animated animation bitmap format graphics interchange', GitHub: 'brand code', GolfCourse: 'flag', GpsFixed: 'location', Google: 'brand logo', Grade: 'likes rated rating shape star', GraphicEq: 'audio equalizer', GridOn: 'sheet', Group: 'people person team users', GroupAdd: 'people person users', GroupWork: 'alliance circle collaboration film partnership reel teamwork together', GTranslate: 'emblem google language logo mark speaking speech translator words', Hd: 'definition high movies resolution tv', Headset: 'earmuffs headphones', HeadsetMic: 'headphones', Healing: 'bandaid health', Hearing: 'accessibility accessible impaired listen sound', Height: 'arrows down resize stretch up', Help: 'alert announcement information mark question support', HelpOutline: 'alert announcement information mark question support', Highlight: 'flashlight marker', HighlightOff: 'circle clear click close delete disable focus remove stop target times x', HighQuality: 'definition hq movies resolution tv', History: 'arrow backwards clock refresh reverse revert rotate time undo', Home: 'address building house place residence structure unit', HomeWork: 'building house office', HorizontalSplit: 'bars stacked', Hotel: 'bed sleep', HotTub: 'jacuzzi', HourglassEmpty: 'countdown loading minutes start time waiting', HourglassFull: 'countdown loading minutes time waiting', Http: 'internet network transfer url website', Https: 'connection encrypt internet key locked network secure security ssl web', Image: 'picture', ImportantDevices: 'cell computer monitor phone star', ImportContacts: 'address book friends information magazine open', ImportExport: 'arrows direction down explort up', IndeterminateCheckBox: 'minus square', Info: 'about alert announcement bubble circle information', Input: 'arrow box right', InsertChart: 'barchart graph', InsertComment: 'chat message', InsertDriveFile: 'bill document invoice item', InsertEmoticon: 'emoji face happy like smiley', InsertInvitation: 'agenda calendar', InsertLink: 'anchor', InsertPhoto: 'image wallpaper', Instagram: 'brand logo social', InvertColors: 'droplet hue inverted liquid palette tone water', InvertColorsOff: 'droplet hue inverted liquid opacity palette tone water', KeyboardArrowDown: 'chevron open', KeyboardArrowLeft: 'chevron', KeyboardArrowRight: 'chevron open start', KeyboardArrowUp: 'chevron submit', KeyboardBackspace: 'left', KeyboardCapslock: 'arrow', KeyboardReturn: 'arrow', KeyboardTab: 'arrow', KingBed: 'double hotel sleep', Kitchen: 'cabinet food freezer refrigerator', Label: 'badge indent item stamp sticker tag', LabelImportant: 'badge important. indent item mail stamp sticker tag wing', LabelOff: 'indent stamp sticker tag', Language: 'earth globe i18n l10n planet website world www country', LaptopMac: 'apple', LastPage: 'arrow', Launch: 'arrow box new open window', LibraryAdd: 'collection plus', LibraryBooks: 'add collection', LibraryMusic: 'add collection song', LineStyle: 'dash dotted editor rule spacing', LineWeight: 'editor height spacing style thickness', Link: 'anchor', LinkedIn: 'brand logo social', LinkOff: 'anchor', List: 'editor file format index menu task todo playlist', ListAlt: 'box contained editor format lines reorder stacked task title todo sheet', LiveHelp: 'alert announcement bubble comment faq information mark question support', LiveTv: 'monitor television', LocalActivity: 'star', LocalAirport: 'airplane flying', LocalAtm: 'cash currency dollar financial money price profit', LocalBar: 'alcohol drink martini', LocalCafe: 'coffee cup drink mug', LocalConvenienceStore: 'building', LocalDining: 'cutlery knife spoon', LocalDrink: 'glass water', LocalFlorist: 'flower', LocalGasStation: 'car filling fuel gasoline station vehicle', LocalHospital: 'aid doctor first health medical plus', LocalHotel: 'bed sleep', LocalLaundryService: 'clean', LocalLibrary: 'book person', LocalMall: 'bag shopping', LocalOffer: 'price tag', LocalPharmacy: 'food', LocalShipping: 'car semi truck vehicle', LocalTaxi: 'car vehicle', LocationCity: 'building company', LocationOff: 'gps', LocationOn: 'gps', Lock: 'connection key locked logout padlock password secure security signout', LockOpen: 'connection key login padlock password secure security signin signup register unlocked', Looks: 'rainbow', Loop: 'arrows loader loading music refresh repeat rotate', LowPriority: 'arrow list task todo', Loyalty: 'badge card credit heart love membership miles points program sale tag travel trip', Mail: 'envelope letter', MailOutline: 'email envelope letter message note post receive send write', Markunread: 'envelope letter', MarkunreadMailbox: 'deliver envelop letter postal postbox receive send', Maximize: 'line shape', MeetingRoom: 'door logout signout', Memory: 'chip', Menu: 'hamburger playlist', MenuBook: 'page', MenuOpen: 'chevron hamburger left', MergeType: 'arrow', Message: 'bubble chat comment speech talk text', Mic: 'hearing microphone noise record sound voice', MicNone: 'hearing microphone noise record sound voice', MicOff: 'hearing microphone noise record sound voice', Minimize: 'line shape', MissedVideoCall: 'arrow record', Mms: 'chat comment message', MobileScreenShare: 'arrow device mirror monitor phone tv', ModeComment: 'chat message', MonetizationOn: 'cash currency dollar finance money price profit sale', Money: 'cash currency finance price profit', MoneyOff: 'cash currency dollar finance money price profit', Mood: 'emoji emoticon face smiley', MoodBad: 'emoji emoticon face smiley', More: 'badge tag', MoreHoriz: 'dots pending status', MoreVert: 'dots', Movie: 'film screen show tv video watch', MovieCreation: 'film video', MovieFilter: 'film video', MultilineChart: 'analytics graph line', MusicVideo: 'band recording screen tv watch', Nature: 'forest tree', NaturePeople: 'forest person tree', NavigateBefore: 'arrow', NavigateNext: 'arrow', Navigation: 'arrow', NearMe: 'arrow', NetworkCheck: 'wifi', NetworkLocked: 'wifi', NewReleases: 'alert announcement burst exclamation star', NextWeek: 'briefcase suitcase', NightsStay: 'cloud moon', NoEncryption: 'disabled lock security', NoMeetingRoom: 'door', NoSim: 'camera card device eject insert memory phone storage', Note: 'bookmark message paper', NoteAdd: 'create document', NotificationImportant: 'alert announcement bell feedback problem', Notifications: 'alert bell ring', NotificationsActive: 'alert bell ring', NotificationsNone: 'alert bell ring', NotificationsOff: 'alert bell ring', NotificationsPaused: 'aleet bell ring', NotInterested: 'allowed banned circle disabled dislike interested not off prohibited x', NotListedLocation: 'map pin questionmark', OfflineBolt: 'circle flash lightning spark', OfflinePin: 'checkmark circle', OndemandVideo: 'monitor television', Opacity: 'color droplet hue inverted liquid palette tone water', OpenInBrowser: 'arrow box new window', OpenInNew: 'arrow box window', OpenWith: 'arrows directional expand move', OutdoorGrill: 'barbeque bbq', Pageview: 'document find glass magnifying paper search', Palette: 'color', Panorama: 'image picture', PanTool: 'drag hand human move scan stop touch wait', Pause: 'controls music video wait status pending', PauseCircleFilled: 'controls music video wait status pending', PauseCircleOutline: 'controls music video wait status pending', PausePresentation: 'device screen share wait status pending', Payment: 'charge creditcard financial information money price', People: 'group person team users', PeopleAlt: 'group person users', PeopleOutline: 'group person team users', PermCameraMic: 'microphone photo speaker', PermContactCalendar: 'agenda human person profile user', PermDataSetting: 'cellular configure information network settings wifi wireless', PermDeviceInformation: 'alert announcement cell important mobile phone', PermIdentity: 'human information person profile save, user', PermMedia: 'collection directories folders images mountain save', PermPhoneMsg: 'bubble chat message mobile recording save speech voice', PermScanWifi: 'alert announcement information internet network service wireless', Person: 'avatar profile user', PersonAdd: 'user', PersonAddDisabled: 'profile user', PersonalVideo: 'monitor television', PersonOutline: 'avatar profile user', PersonPin: 'gps location', PersonPinCircle: 'gps location', Pets: 'animal cat claw dog hand paw', Phone: 'call chat device mobile text', PhoneAndroid: 'mobile', PhoneIphone: 'apple mobile', PhonelinkErase: 'device mobile', PhonelinkLock: 'device mobile security', PhonelinkRing: 'device mobile', PhonelinkSetup: 'device information mobile settings', PhoneLocked: 'security', PhonePaused: 'wait', PhotoAlbum: 'image picture', PhotoCamera: 'image picture', PhotoLibrary: 'image picture', PictureInPicture: 'cropped overlap photo shape', PictureInPictureAlt: 'cropped overlap photo shape', PieChart: 'analytics graph', PieChartOutlined: 'graph', PinDrop: 'gps location', Pinterest: 'brand logo social', PlayArrow: 'controls music start video', PlayCircleFilled: 'arrow controls music start video', PlayCircleFilledWhite: 'start', PlayCircleOutline: 'arrow controls music start video', PlayForWork: 'arrow circle down google half', PlaylistAdd: 'collection music plus task todo', PlaylistAddCheck: 'checkmark collection music task tick todo', PlaylistPlay: 'collection music', PlusOne: 'add', Policy: 'glass magnifying shield', Poll: 'analytics barchart graph', Pool: 'swimming water', PortableWifiOff: 'connected connection device internet network service usage', PostAdd: 'document item page plus', Power: 'plug socket online', PowerInput: 'dc', PowerSettingsNew: 'information off save shutdown', PregnantWoman: 'baby birth female human lady maternity person user', PresentToAll: 'arrow', Print: 'draft ink paper printer send', PriorityHigh: 'exclamation', Public: 'earth globe world country language', Publish: 'arrow submit upload', QueryBuilder: 'clock hour minute save time', QuestionAnswer: 'bubble chat comment conversation converse message speech talk', Queue: 'add collection music playlist stream video', QueueMusic: 'add collection playlist stream', QueuePlayNext: 'add arrow collection device monitor music playlist plus screen video', Radio: 'antenna device listen music player tune', RadioButtonChecked: 'circle', RadioButtonUnchecked: 'circle', RateReview: 'chat comment message', Receipt: 'bill credit invoice paper payment sale transaction', RecentActors: 'cards carousel contacts human profile user', RecordVoiceOver: 'human person profile recording sound speaking speech transcript user', Reddit: 'brand logo social', Redeem: 'certificate credit giftcard present', Redo: 'arrow', Remove: 'line minus subtract', RemoveCircle: 'allowed banned disable not', RemoveCircleOutline: 'allowed banned disable not', RemoveFromQueue: 'collection device list monitor screen television', RemoveShoppingCart: 'checkout', Reorder: 'format lines list stacked', Repeat: 'arrows controls music video', RepeatOne: '1 arrows controls music video', Replay: 'arrows controls music refresh reload repeat rewind undo video retry', Replay10: 'arrows controls music repeat rewind video', Replay30: 'arrows controls music repeat rewind video', Replay5: 'arrows controls music repeat rewind video', Reply: 'arrow', ReplyAll: 'arrows', Report: 'exclamation', ReportProblem: 'alert announcement danger exclamation feedback triangle warning', Restaurant: 'cutlery fork knife', Restore: 'arrow backwards clock history refresh reverse rotate time undo', RestoreFromTrash: 'arrow can delete garbage remove up', RestorePage: 'arrow history paper refresh rotate undo web', RingVolume: 'mobile phone', Room: 'gps location map marker pin place spot', RoomService: 'bell concierge', Rotate90DegreesCcw: 'arrow', RotateLeft: 'arrow circle refresh reload reset', RotateRight: 'arrow circle', RoundedCorner: 'shape square transform', Router: 'device network', Rowing: 'activity boat canoe human person sports water', RssFeed: 'network wifi', Save: 'diskette floppy write', SaveAlt: 'diskette floppy write', Scanner: 'device', Schedule: 'calendar clock date mark save time', School: 'college university', ScreenLockLandscape: 'mobile phone security', ScreenLockPortrait: 'mobile phone security', ScreenLockRotation: 'mobile phone', ScreenRotation: 'mobile phone', ScreenShare: 'laptop monitor', SdStorage: 'microsd', Search: 'filter find glass look magnifying up', Security: 'shield', Send: 'chat message telegram', SentimentDissatisfied: 'emoji emoticon sad smiley', SentimentSatisfied: 'emoji emoticon happy like smiley', SentimentVeryDissatisfied: 'emoji emoticon sad smiley unhappy', SentimentVerySatisfied: 'emoji emoticon happy like smiley', Settings: 'gear', SettingsApplications: 'details gear information personal save service', SettingsBackupRestore: 'arrow backwards history refresh reverse rotate time undo', SettingsBluetooth: 'connection connectivity network wifi', SettingsBrightness: 'dark light mode sun', SettingsCell: 'cellphone device mobile', SettingsEthernet: 'arrows brackets connection connectivity dots network parenthesis wifi', SettingsInputAntenna: 'connection connectivity network wifi', SettingsInputComponent: 'cable connection connectivity plugs points', SettingsInputComposite: 'cable component connection connectivity plugs points', SettingsInputHdmi: 'cable connection connectivity plugin points', SettingsInputSvideo: 'connection connectivity plugin plugs points svideo,', SettingsOverscan: 'arrows expand image photo picture', SettingsPhone: 'cell device mobile', SettingsPower: 'information off save shutdown', SettingsRemote: 'bluetooth control wifi', SettingsSystemDaydream: 'cloud', SettingsVoice: 'microphone recorder speaker', Shop: 'arrow briefcase buy cart google play purchase shopping', ShoppingBasket: 'add buy cart purchase', ShoppingCart: 'add buy checkout purchase', ShopTwo: 'arrow briefcase buy cart google play purchase shopping', ShortText: 'lines', ShowChart: 'analytics graph line stock', Shuffle: 'arrows controls music video', SignalCellular4Bar: 'network', SignalCellularConnectedNoInternet0Bar: 'network', SignalCellularConnectedNoInternet1Bar: 'network', SignalCellularConnectedNoInternet2Bar: 'network', SignalCellularConnectedNoInternet3Bar: 'network', SignalCellularConnectedNoInternet4Bar: 'network', SignalCellularNoSim: 'network', SignalCellularNull: 'network', SignalCellularOff: 'network', SignalWifi0Bar: 'network', SignalWifi1Bar: 'network', SignalWifi1BarLock: 'network', SignalWifi2Bar: 'network', SignalWifi2BarLock: 'network', SignalWifi3Bar: 'network', SignalWifi3BarLock: 'network', SignalWifi4Bar: 'network', SignalWifi4BarLock: 'network', SignalWifiOff: 'network', SimCard: 'network', SingleBed: 'hotel queen sleep', SkipNext: 'arrow back controls music play previous video', SkipPrevious: 'arrow controls forward music next play video', Slideshow: 'presentation', SlowMotionVideo: 'arrow circle controls music play time', Smartphone: 'mobile', SmokeFree: 'cigarette', SmokingRooms: 'cigarette', Sms: 'chat comment message', SmsFailed: 'chat comment message', Snooze: 'alarm clock set timer', Sort: 'lines', SortByAlpha: 'alphabetize letters list order organize', Spa: 'flower', Speaker: 'audio', SpeakerGroup: 'audio', SpeakerNotes: 'bubble cards chat comment format list message speech', SpeakerNotesOff: 'bubble cards chat comment format list message speech', SpeakerPhone: 'mobile', Speed: 'clock dial measure test', Spellcheck: 'alphabet checkmark edit letter processor word write', Sports: 'whistle', SportsEsports: 'controller gamepad playstation xbox', SportsFootball: 'american', SportsHockey: 'ice', SportsKabaddi: 'fighting judo martial', SportsSoccer: 'football', Star: 'rating', StarBorder: 'rating', StarHalf: 'rating', Stars: 'circle favorite like love rate rating', StayCurrentLandscape: 'mobile phone', StayCurrentPortrait: 'mobile phone', StayPrimaryLandscape: 'mobile phone', StayPrimaryPortrait: 'mobile phone', Stop: 'arrow controls music play square video', StopScreenShare: 'laptop monitor', Storage: 'database network server', Store: 'building buy e-commerce purchase shop storefront', Storefront: 'merchant shop stall', StoreMallDirectory: 'building', Straighten: 'piano', Streetview: 'gps location map', SubdirectoryArrowLeft: 'arrow', SubdirectoryArrowRight: 'arrow', Subject: 'document email full justify lines list note text writing', Subscriptions: 'enroll order playlist queue subscribe youtube', Subtitles: 'accessibility accessible captions language translate', Subway: 'metro', SupervisedUserCircle: 'avatar human people person profile supervisor', SupervisorAccount: 'administrator avatar human people person profile supervised user', SurroundSound: 'audio circle speaker system volumn', SwapCalls: 'arrow', SwapHoriz: 'arrows back direction horizontal', SwapHorizontalCircle: 'arrows back direction', SwapVert: 'arrows back direction vertical', SwapVerticalCircle: 'arrows back direction horizontal', Sync: 'arrows refresh', SyncAlt: 'arrows', SyncDisabled: 'arrows refresh', SyncProblem: 'arrows refresh', SystemUpdate: 'arrow download', SystemUpdateAlt: 'arrow download', TabletMac: 'apple', TapAndPlay: 'nfc wifi', Telegram: 'brand call chat logo messaging voice', TextFormat: 'letter', TextRotateUp: 'arrow field move', TextRotateVertical: 'arrow field move verticle', TextRotationAngledown: 'arrow field move rotate', TextRotationAngleup: 'arrow field move rotate', TextRotationDown: 'arrow field move rotate', TextRotationNone: 'arrow field move rotate', Textsms: 'chat comment message', Theaters: 'media movies photography showtimes video watch', ThreeDRotation: '3d arrows vr', ThumbDown: 'dislike favorite finger hand rate rating reject up vote', ThumbDownAlt: 'dislike hand reject vote', ThumbsUpDown: 'dislike favorite finger hand rate rating vote', ThumbUp: 'approve dislike down favorite finger hand rate rating success vote', ThumbUpAlt: 'approve hand like success vote', Timeline: 'analytics chart graph history line movement points trending zigzap', Timer: 'clock stopwatch wait', TimerOff: 'clock stopwatch', Toc: 'content format lines list reorder stacked table text titles', Today: 'agenda calendar date event mark month range remember reminder week', Toll: 'booth car circles payment ticket', TouchApp: 'arrow finger gesture hand swipe', Toys: 'fan', TrackChanges: 'bullseye circle evolve lines movement radar rotate shift target', Traffic: 'light', TransferWithinAStation: 'man person transit', Translate: 'alphabet language letter speaking speech text translator words', TrendingDown: 'arrow change chart graph metric movement rate sale tracking', TrendingFlat: 'arrow change chart graph metric movement rate tracking', TrendingUp: 'arrow change chart graph metric movement rate tracking', Tune: 'settings sliders', TurnedIn: 'bookmark item remember save submit', TurnedInNot: 'bookmark item outline remember save submit', Tv: 'television', Twitter: 'brand logo social', TwoWheeler: 'bicycle moped motorbike ride riding transportation vehicle wheels', Unarchive: 'arrow', Undo: 'arrow', UnfoldLess: 'arrow', UnfoldMore: 'arrow', Update: 'arrow backwards clock future history refresh reverse rotate time', VerifiedUser: 'audit certified checkmark security shield', VerticalAlignBottom: 'arrow', VerticalAlignCenter: 'arrow', VerticalAlignTop: 'arrow', VerticalSplit: 'format paragraph text website', Vibration: 'mobile phone', VideoCall: 'camera chat conference plus screen', Videocam: 'camera chat conference screen', VideocamOff: 'camera chat conference screen', VideogameAsset: 'controller gamepad nintendo playstation xbox', VideoLabel: 'device item screen', VideoLibrary: 'collection', ViewAgenda: 'blocks cards format website,stacked', ViewArray: 'blocks format website', ViewCarousel: 'banner blocks cards format images', ViewColumn: 'blocks format grid vertical website', ViewComfy: 'grid', ViewCompact: 'grid', ViewDay: 'blocks calendar cards carousel format week', ViewHeadline: 'blocks format paragraph text website', ViewList: 'blocks format lines reorder stacked title', ViewModule: 'blocks format reorder squares stacked title', ViewQuilt: 'blocks format reorder squares stacked title', ViewStream: 'blocks format lines list reorder stacked title', ViewWeek: 'bars blocks columns day format', Vignette: 'effect photo', Visibility: 'eye on password reveal see shown view visability preview', VisibilityOff: 'eye hidden invisible on password reveal see show view visability', VoiceChat: 'camera', VolumeDown: 'control sound', VolumeMute: 'control sound', VolumeOff: 'control sound', VolumeUp: 'control sound', VpnKey: 'login password security signin signup register', VpnLock: 'earth globe password security world', Wallpaper: 'image picture', Warning: 'alert announcement danger error exclamation feedback problem triangle', Watch: 'smartwatch', WatchLater: 'clock hour minute time', WbIncandescent: 'lamp lightbulb', WbSunny: 'weather', Wc: 'gender person toilet unisex gender', Web: 'blocks browser internet screen website www', WebAsset: 'browser download image internet screen video website www', Weekend: 'chair couch seat', WhatsApp: 'brand call chat logo messaging voice', Whatshot: 'fire trending', Widgets: 'blocks', Wifi: 'network', WifiLock: 'network', WifiTethering: 'network', Work: 'briefcase job suitcase', WorkOff: 'briefcase job suitcase', WorkOutline: 'briefcase job suitcase', WrapText: 'arrow', YouTube: 'brand logo social video', YoutubeSearchedFor: 'arrow backwards refresh restore reverse rotate', ZoomIn: 'bigger glass grow magnifier magnifying plus scale size', ZoomOut: 'glass magnifier magnifying minus negative scale size smaller', ZoomOutMap: 'arrows', }; export default synonyms;
docs/src/pages/components/material-icons/synonyms.js
const synonyms = { AccessAlarm: 'clock time', AccessAlarms: 'clock time', Accessibility: 'accessible body help human person user', AccessibilityNew: 'accessible arms body help human person user', Accessible: 'accessibility body help human person user wheelchair', AccessibleForward: 'accessibility body help human person wheelchair', AccessTime: 'clock time', AccountBalance: 'bank building court money payment structure temple transaction', AccountBalanceWallet: 'money payment transaction', AccountBox: 'avatar person profile square thumbnail user', AccountCircle: 'avatar person profile thumbnail user', AccountTree: 'sitemap project', AcUnit: 'freeze snowflake', Add: 'create item new plus', AddAlarm: 'clock plus time', AddAlert: 'announcement bell callout information notification plus reminder', AddAPhoto: 'camera', AddBox: 'create new plus square', AddCircle: 'create new plus', AddCircleOutline: 'create new plus', AddLocation: 'gps', AddShoppingCart: 'checkout plus', AddToPhotos: 'plus', AddToQueue: 'backlog display lineup monitor plus television watch', Adjust: 'circle', AirlineSeatFlat: 'bed sleep', AirlineSeatFlatAngled: 'bed sleep', AirlineSeatIndividualSuite: 'bed sleep', AirplanemodeActive: 'flying', AirplanemodeInactive: 'flying', Airplay: 'apple arrow connect control device monitor screen signal television', AirportShuttle: 'bus car vehicle', Alarm: 'clock countdown time', AlarmAdd: 'clock plus time', AlarmOff: 'clock disabled stop time', AlarmOn: 'checkmark clock enabled ready start time', Album: 'artist cd music play record track vinyl', AllInbox: 'delivery email letter post send', AllInclusive: 'infinite', AllOut: 'arrows circle directional expand shape', Android: 'brand character logo mascot operating system toy', Announcement: 'alert balloon bubble chat comment exclamation message news speech', Apartment: 'building', Apple: 'brand logo', Apps: 'grid homescreen icons', ArrowBack: 'left', ArrowBackIos: 'left', ArrowRightAlt: 'pointing shape', ArrowUpward: 'submit', ArtTrack: 'display format insert', AspectRatio: 'expand image monitor resolution scale screen size square', Assessment: 'analytics bars chart graph measure metrics tracking report', Assignment: 'article clipboard document task text writing', AssignmentInd: 'clipboard document person profile task user', AssignmentLate: 'alert announcement clipboard exclamation task', AssignmentReturn: 'arrow clipboard left point task', AssignmentReturned: 'arrow clipboard down point task', AssignmentTurnedIn: 'checkmark clipboard complete done finished task', Assistant: 'chat comment star', AttachFile: 'item paperclip', Attachment: 'file item paperclip', AttachMoney: 'cash currency dollar finance price profit sale', Audiotrack: 'note', Autorenew: 'arrows cached inprogress loader loading refresh rotate status pending', AvTimer: 'clock countdown minutes seconds stopwatch', Backspace: 'clear delete remove', Backup: 'arrow cloud point submit upload', BarChart: 'anlytics graph', Bathtub: 'clean shower', BatteryAlert: 'exclamation', BatteryChargingFull: 'lightning', BatteryUnknown: 'question', BeachAccess: 'parasol sun umbrella', Beenhere: 'checkmark', Biotech: 'test', Block: 'allowed banned cancel disable not', Bluetooth: 'network wireless', BluetoothConnected: 'network wireless', BluetoothDisabled: 'network wireless', BluetoothSearching: 'network wireless', BlurCircular: 'circle', Book: 'bookmark reading blog', Bookmark: 'favorite remember save', BookmarkBorder: 'favorite outline remember save', Bookmarks: 'remember save', BorderColor: 'create marker pencil', BrandingWatermark: 'emblem format identity logo stamp', Brightness2: 'moon night', Brightness3: 'moon night', Brightness4: 'dark moon night sun', Brightness5: 'sun', Brightness6: 'sun', Brightness7: 'sun light', BrokenImage: 'picture', Brush: 'paint', BubbleChart: 'analytics graph', BugReport: 'animal file insect issue ticket', Build: 'spanner tool wrench', BurstMode: 'image picture', Business: 'address apartment building company flat office structure', BusinessCenter: 'briefcase suitcase', Cached: 'arrows inprogress loader loading refresh reload renew rotate', Cake: 'birthday pie', CalendarToday: 'date event month remember reminder week', CalendarViewDay: 'month remember reminder today week', Call: 'device mobile phone talk', CallEnd: 'device mobile phone talk', CallMade: 'arrow device mobile', CallMerge: 'arrow device mobile', CallMissed: 'arrow device mobile', CallMissedOutgoing: 'arrow device mobile', CallReceived: 'arrow device mobile', CallSplit: 'arrow device mobile', CallToAction: 'alert bar cta information message notification', CameraEnhance: 'lens photo picture quality', Cancel: 'close cross disable status', CancelPresentation: 'close device screen share x', CardGiftcard: 'certificate creditcard present', CardMembership: 'certificate creditcard subscription', CardTravel: 'creditcard membership miles trip', Casino: 'dice', Cast: 'chromecast', CastConnected: 'chromecast', ChangeHistory: 'shape triangle', Chat: 'bubble comment message speech talk text', ChatBubble: 'comment message speech talk text', ChatBubbleOutline: 'comment message speech talk text', Check: 'checkmark success tick', CheckBox: 'checkmark square success tick', CheckBoxOutlineBlank: 'checkmark square tick', CheckCircle: 'checkmark complete done finished success tick', CheckCircleOutline: 'checkmark complete done finished success tick', ChevronLeft: 'arrow', ChevronRight: 'arrow', ChildCare: 'baby', ChildFriendly: 'baby', ChromeReaderMode: 'text', Class: 'category item', Clear: 'allowed cancel cross disable not times x', ClearAll: 'delete document erase format lines list notifications wipe', Close: 'allowed cancel cross disable not times x status', ClosedCaption: 'accessible decoder language subtitles', Cloud: 'weather', CloudDone: 'checkmark', Code: 'brackets css developer engineering html parenthesis platform', Colorize: 'color picker pipette', Comment: 'bubble chat document message note', Commute: 'car train transportation vehicle', CompareArrows: 'directional facing pointing', Computer: 'laptop monitor pc', ConfirmationNumber: 'ticket', Contactless: 'applepay tap wifi', ContactMail: 'address information person profile user', ContactPhone: 'information number person profile user', Contacts: 'address information number person phone profile user', ContactSupport: 'alert announcement bubble help information mark question speech', ControlCamera: 'adjust arrows direction left move right', ControlPoint: 'circle plus', ControlPointDuplicate: 'circle plus', Copyright: 'emblem symbol', Create: 'item new pencil write', CreateNewFolder: 'directory', CreditCard: 'charge creditcard finance information money payment price', Crop169: 'image picture square', Crop32: 'image picture square', Crop54: 'image picture square', Crop75: 'image picture square', CropDin: 'image picture square', CropFree: 'barcode qrcode square', CropLandscape: 'image picture square', CropOriginal: 'image picture square', CropPortrait: 'image picture square', Dashboard: 'cards rectangle shapes square', DataUsage: 'circle', DateRange: 'agenda calendar event month remember reminder today week', Deck: 'furniture garden patio', Delete: 'bin garbage junk recycle remove trashcan', DeleteForever: 'bin garbage junk recycle remove trashcan x', DeleteOutline: 'can garbage remove trash', DeleteSweep: 'bin junk recycle trashcan', Description: 'article bill document file invoice item text writing', DesktopAccessDisabled: 'apple device monitor off pc screen', DesktopMac: 'apple monitor pc', DesktopWindows: 'monitor pc', Details: 'triangle', DeveloperBoard: 'devkit', DeveloperMode: 'code', Devices: 'laptop mobile phone', DevicesOther: 'smartwatch', DialerSip: 'call internet phone protocol routing', Dialpad: 'call device dots numbers phone', Directions: 'arrow naviate', DirectionsBike: 'bicycle', DirectionsRun: 'health person', DirectionsTransit: 'metro subway', DirectionsWalk: 'person', DiscFull: 'cd exclamation vinyl', Dns: 'address bars domain information ip list lookup name network server', Dock: 'charger', Domain: 'building', DomainDisabled: 'building internet off website', Done: 'checkmark complete finished success tick', DoneAll: 'checkmark complete finished multiple success tick', DoneOutline: 'checkmark complete finished success tick', DonutLarge: 'chart circle complete graph inprogress,', DonutSmall: 'chart circle', DoubleArrow: 'chevron right', Drafts: 'email envelope letter', DragHandle: 'lines', DragIndicator: 'circle dots drop move shape shift', DriveEta: 'car transport vehicle', Duo: 'call chat conference device video', Dvr: 'laptop monitor', DynamicFeed: 'live refresh update', Eco: 'environment green leaf', EditLocation: 'gps map pin write', Eject: 'arrow player remove triangle up', Elderly: 'old', Email: 'envelope letter message note post receive send write', EmojiEmotions: 'emoticon face happy like smiley', EmojiFoodBeverage: 'cup dring mug tea', EmojiNature: 'bee flower honey', EmojiObjects: 'lamp lightbulb', EmojiPeople: 'man person wave waving', EmojiSymbols: 'ampersand music note percent', EmojiTransportation: 'building car commute company office vehicle', EnhancedEncryption: 'lock security', Equalizer: 'adjustment chart graph noise sound static volume', Error: 'alert announcement circle danger exclamation feedback problem warning', ErrorOutline: 'alert announcement circle danger exclamation feedback problem warning', Euro: 'cash currency finance money price profit', EuroSymbol: 'cash currency dollar finance money price profit', Event: 'agenda calendar date item mark month range remember reminder today week', EventAvailable: 'agenda calendar date item', EventBusy: 'agenda calendar date item', EventNote: 'agenda calendar date item', EventSeat: 'assigned bench chair reservation row section sit', EvStation: 'car charge filling fuel gasoline power station vehicle', ExitToApp: 'arrow back leave login logout pointing quit right signin signup register signout', ExpandLess: 'arrow up', ExpandMore: 'arrow down', Explicit: 'adult content language', Explore: 'compass destination location map needle travel', ExploreOff: 'compass destination disabled location map needle travel', Exposure: 'minus plus', Extension: 'extended item jigsaw piece puzzle shape add-ons', Face: 'avatar eyes human person profile thumbnail user', Facebook: 'brand logo social', Fastfood: 'burger drink', FastForward: 'control music speed time video', FastRewind: 'control music speed time video', Favorite: 'health heart like love remember save shape success', FavoriteBorder: 'health heart like love remember save shape success', FeaturedPlayList: 'audio collection highlighted item music playlist recommended', FeaturedVideo: 'highlighted item play recommended watch,advertised', Feedback: 'alert announcement bubble chat comment exclamation message speech', FiberDvr: 'digital electronics network recorder tv video', FiberManualRecord: 'circle dot play watch', FiberNew: 'network', FiberPin: 'network', FiberSmartRecord: 'play watch', FileCopy: 'bill invoice item page duplicate clone', FilterDrama: 'cloud', FilterHdr: 'mountains', FilterList: 'lines', FilterVintage: 'flower', FindInPage: 'document glass look magnifying paper search see', FindReplace: 'arrows glass inprogress look magnifying refresh rotate search see', Fingerprint: 'biometrics identification identity reader thumbprint touchid', Fireplace: 'flame', FirstPage: 'arrow', FitnessCenter: 'health weights workout', FiveG: '5g', Flare: 'bright lensflare light shine sparkle star sun', FlashAuto: 'lightning', FlashOff: 'lightning', FlashOn: 'lightning', Flight: 'airplane flying', FlightLand: 'airplane arrival arriving flying landing transportation travel', FlightTakeoff: 'airplane departed departing flying landing transportation travel', FlipCameraAndroid: 'front rear reverse', FlipCameraIos: 'front rear reverse', FlipToBack: 'arrangement front move order sort', FlipToFront: 'arrangement back move order sort', Folder: 'directory', FolderOpen: 'directory', FolderShared: 'directory', FolderSpecial: 'directory', FontDownload: 'letter square', FormatAlignCenter: 'lines', FormatAlignJustify: 'lines', FormatAlignLeft: 'lines', FormatAlignRight: 'lines', FormatColorFill: 'bucket', FormatColorReset: 'drop liquid water', FormatListBulleted: 'task todo', FormatListNumbered: 'task todo', FormatListNumberedRtl: 'task todo', FormatPaint: 'paintroller', FormatQuote: 'quotation', FormatTextdirectionLToR: 'paragraph', FormatTextdirectionRToL: 'paragraph', Forum: 'bubble chat community conversation hub messages speech talk', Forward: 'arrow', Forward10: 'arrow circle control fast music rotate speed time video', Forward30: 'arrow circle control fast music rotate speed time video', Forward5: 'arrow circle control fast music rotate speed time video', FourK: '4000 display pixels resolution', FreeBreakfast: 'coffee drink tea', Functions: 'math sigma', Games: 'adjust arrows controller direction dpad left move nintendo playstation right xbox', Gavel: 'court document government hammer judge law mallet official police rules', Gesture: 'drawing line', GetApp: 'arrow download pointing retrieve', Gif: 'animated animation bitmap format graphics interchange', GitHub: 'brand code', GolfCourse: 'flag', GpsFixed: 'location', Google: 'brand logo', Grade: 'likes rated rating shape star', GraphicEq: 'audio equalizer', GridOn: 'sheet', Group: 'people person team users', GroupAdd: 'people person users', GroupWork: 'alliance circle collaboration film partnership reel teamwork together', GTranslate: 'emblem google language logo mark speaking speech translator words', Hd: 'definition high movies resolution tv', Headset: 'earmuffs headphones', HeadsetMic: 'headphones', Healing: 'bandaid health', Hearing: 'accessibility accessible impaired listen sound', Height: 'arrows down resize stretch up', Help: 'alert announcement information mark question support', HelpOutline: 'alert announcement information mark question support', Highlight: 'flashlight marker', HighlightOff: 'circle clear click close delete disable focus remove stop target times x', HighQuality: 'definition hq movies resolution tv', History: 'arrow backwards clock refresh reverse revert rotate time undo', Home: 'address building house place residence structure unit', HomeWork: 'building house office', HorizontalSplit: 'bars stacked', Hotel: 'bed sleep', HotTub: 'jacuzzi', HourglassEmpty: 'countdown loading minutes start time waiting', HourglassFull: 'countdown loading minutes time waiting', Http: 'internet network transfer url website', Https: 'connection encrypt internet key locked network secure security ssl web', Image: 'picture', ImportantDevices: 'cell computer monitor phone star', ImportContacts: 'address book friends information magazine open', ImportExport: 'arrows direction down explort up', IndeterminateCheckBox: 'minus square', Info: 'about alert announcement bubble circle information', Input: 'arrow box right', InsertChart: 'barchart graph', InsertComment: 'chat message', InsertDriveFile: 'bill document invoice item', InsertEmoticon: 'emoji face happy like smiley', InsertInvitation: 'agenda calendar', InsertLink: 'anchor', InsertPhoto: 'image wallpaper', Instagram: 'brand logo social', InvertColors: 'droplet hue inverted liquid palette tone water', InvertColorsOff: 'droplet hue inverted liquid opacity palette tone water', KeyboardArrowDown: 'chevron open', KeyboardArrowLeft: 'chevron', KeyboardArrowRight: 'chevron open start', KeyboardArrowUp: 'chevron submit', KeyboardBackspace: 'left', KeyboardCapslock: 'arrow', KeyboardReturn: 'arrow', KeyboardTab: 'arrow', KingBed: 'double hotel sleep', Kitchen: 'cabinet food freezer refrigerator', Label: 'badge indent item stamp sticker tag', LabelImportant: 'badge important. indent item mail stamp sticker tag wing', LabelOff: 'indent stamp sticker tag', Language: 'earth globe i18n l10n planet website world www country', LaptopMac: 'apple', LastPage: 'arrow', Launch: 'arrow box new open window', LibraryAdd: 'collection plus', LibraryBooks: 'add collection', LibraryMusic: 'add collection song', LineStyle: 'dash dotted editor rule spacing', LineWeight: 'editor height spacing style thickness', Link: 'anchor', LinkedIn: 'brand logo social', LinkOff: 'anchor', List: 'editor file format index menu task todo playlist', ListAlt: 'box contained editor format lines reorder stacked task title todo sheet', LiveHelp: 'alert announcement bubble comment faq information mark question support', LiveTv: 'monitor television', LocalActivity: 'star', LocalAirport: 'airplane flying', LocalAtm: 'cash currency dollar financial money price profit', LocalBar: 'alcohol drink martini', LocalCafe: 'coffee cup drink mug', LocalConvenienceStore: 'building', LocalDining: 'cutlery knife spoon', LocalDrink: 'glass water', LocalFlorist: 'flower', LocalGasStation: 'car filling fuel gasoline station vehicle', LocalHospital: 'aid doctor first health medical plus', LocalHotel: 'bed sleep', LocalLaundryService: 'clean', LocalLibrary: 'book person', LocalMall: 'bag shopping', LocalOffer: 'price tag', LocalPharmacy: 'food', LocalShipping: 'car semi truck vehicle', LocalTaxi: 'car vehicle', LocationCity: 'building company', LocationOff: 'gps', LocationOn: 'gps', Lock: 'connection key locked logout padlock password secure security signout', LockOpen: 'connection key login padlock password secure security signin signup register unlocked', Looks: 'rainbow', Loop: 'arrows loader loading music refresh repeat rotate', LowPriority: 'arrow list task todo', Loyalty: 'badge card credit heart love membership miles points program sale tag travel trip', Mail: 'envelope letter', MailOutline: 'email envelope letter message note post receive send write', Markunread: 'envelope letter', MarkunreadMailbox: 'deliver envelop letter postal postbox receive send', Maximize: 'line shape', MeetingRoom: 'door logout signout', Memory: 'chip', Menu: 'hamburger playlist', MenuBook: 'page', MenuOpen: 'chevron hamburger left', MergeType: 'arrow', Message: 'bubble chat comment speech talk text', Mic: 'hearing microphone noise record sound voice', MicNone: 'hearing microphone noise record sound voice', MicOff: 'hearing microphone noise record sound voice', Minimize: 'line shape', MissedVideoCall: 'arrow record', Mms: 'chat comment message', MobileScreenShare: 'arrow device mirror monitor phone tv', ModeComment: 'chat message', MonetizationOn: 'cash currency dollar finance money price profit sale', Money: 'cash currency finance price profit', MoneyOff: 'cash currency dollar finance money price profit', Mood: 'emoji emoticon face smiley', MoodBad: 'emoji emoticon face smiley', More: 'badge tag', MoreHoriz: 'dots pending status', MoreVert: 'dots', Movie: 'film screen show tv video watch', MovieCreation: 'film video', MovieFilter: 'film video', MultilineChart: 'analytics graph line', MusicVideo: 'band recording screen tv watch', Nature: 'forest tree', NaturePeople: 'forest person tree', NavigateBefore: 'arrow', NavigateNext: 'arrow', Navigation: 'arrow', NearMe: 'arrow', NetworkCheck: 'wifi', NetworkLocked: 'wifi', NewReleases: 'alert announcement burst exclamation star', NextWeek: 'briefcase suitcase', NightsStay: 'cloud moon', NoEncryption: 'disabled lock security', NoMeetingRoom: 'door', NoSim: 'camera card device eject insert memory phone storage', Note: 'bookmark message paper', NoteAdd: 'create document', NotificationImportant: 'alert announcement bell feedback problem', Notifications: 'alert bell ring', NotificationsActive: 'alert bell ring', NotificationsNone: 'alert bell ring', NotificationsOff: 'alert bell ring', NotificationsPaused: 'aleet bell ring', NotInterested: 'allowed banned circle disabled dislike interested not off prohibited x', NotListedLocation: 'map pin questionmark', OfflineBolt: 'circle flash lightning spark', OfflinePin: 'checkmark circle', OndemandVideo: 'monitor television', Opacity: 'color droplet hue inverted liquid palette tone water', OpenInBrowser: 'arrow box new window', OpenInNew: 'arrow box window', OpenWith: 'arrows directional expand move', OutdoorGrill: 'barbeque bbq', Pageview: 'document find glass magnifying paper search', Palette: 'color', Panorama: 'image picture', PanTool: 'drag hand human move scan stop touch wait', Pause: 'controls music video wait status pending', PauseCircleFilled: 'controls music video wait status pending', PauseCircleOutline: 'controls music video wait status pending', PausePresentation: 'device screen share wait status pending', Payment: 'charge creditcard financial information money price', People: 'group person team users', PeopleAlt: 'group person users', PeopleOutline: 'group person team users', PermCameraMic: 'microphone photo speaker', PermContactCalendar: 'agenda human person profile user', PermDataSetting: 'cellular configure information network settings wifi wireless', PermDeviceInformation: 'alert announcement cell important mobile phone', PermIdentity: 'human information person profile save, user', PermMedia: 'collection directories folders images mountain save', PermPhoneMsg: 'bubble chat message mobile recording save speech voice', PermScanWifi: 'alert announcement information internet network service wireless', Person: 'avatar profile user', PersonAdd: 'user', PersonAddDisabled: 'profile user', PersonalVideo: 'monitor television', PersonOutline: 'avatar profile user', PersonPin: 'gps location', PersonPinCircle: 'gps location', Pets: 'animal cat claw dog hand paw', Phone: 'call chat device mobile text', PhoneAndroid: 'mobile', PhoneIphone: 'apple mobile', PhonelinkErase: 'device mobile', PhonelinkLock: 'device mobile security', PhonelinkRing: 'device mobile', PhonelinkSetup: 'device information mobile settings', PhoneLocked: 'security', PhonePaused: 'wait', PhotoAlbum: 'image picture', PhotoCamera: 'image picture', PhotoLibrary: 'image picture', PictureInPicture: 'cropped overlap photo shape', PictureInPictureAlt: 'cropped overlap photo shape', PieChart: 'analytics graph', PieChartOutlined: 'graph', PinDrop: 'gps location', Pinterest: 'brand logo social', PlayArrow: 'controls music start video', PlayCircleFilled: 'arrow controls music start video', PlayCircleFilledWhite: 'start', PlayCircleOutline: 'arrow controls music start video', PlayForWork: 'arrow circle down google half', PlaylistAdd: 'collection music plus task todo', PlaylistAddCheck: 'checkmark collection music task tick todo', PlaylistPlay: 'collection music', PlusOne: 'add', Policy: 'glass magnifying shield', Poll: 'analytics barchart graph', Pool: 'swimming water', PortableWifiOff: 'connected connection device internet network service usage', PostAdd: 'document item page plus', Power: 'plug socket online', PowerInput: 'dc', PowerSettingsNew: 'information off save shutdown', PregnantWoman: 'baby birth female human lady maternity person user', PresentToAll: 'arrow', Print: 'draft ink paper printer send', PriorityHigh: 'exclamation', Public: 'earth globe world country language', Publish: 'arrow submit upload', QueryBuilder: 'clock hour minute save time', QuestionAnswer: 'bubble chat comment conversation converse message speech talk', Queue: 'add collection music playlist stream video', QueueMusic: 'add collection playlist stream', QueuePlayNext: 'add arrow collection device monitor music playlist plus screen video', Radio: 'antenna device listen music player tune', RadioButtonChecked: 'circle', RadioButtonUnchecked: 'circle', RateReview: 'chat comment message', Receipt: 'bill credit invoice paper payment sale transaction', RecentActors: 'cards carousel contacts human profile user', RecordVoiceOver: 'human person profile recording sound speaking speech transcript user', Reddit: 'brand logo social', Redeem: 'certificate credit giftcard present', Redo: 'arrow', Remove: 'line minus subtract', RemoveCircle: 'allowed banned disable not', RemoveCircleOutline: 'allowed banned disable not', RemoveFromQueue: 'collection device list monitor screen television', RemoveShoppingCart: 'checkout', Reorder: 'format lines list stacked', Repeat: 'arrows controls music video', RepeatOne: '1 arrows controls music video', Replay: 'arrows controls music refresh reload repeat rewind undo video retry', Replay10: 'arrows controls music repeat rewind video', Replay30: 'arrows controls music repeat rewind video', Replay5: 'arrows controls music repeat rewind video', Reply: 'arrow', ReplyAll: 'arrows', Report: 'exclamation', ReportProblem: 'alert announcement danger exclamation feedback triangle warning', Restaurant: 'cutlery fork knife', Restore: 'arrow backwards clock history refresh reverse rotate time undo', RestoreFromTrash: 'arrow can delete garbage remove up', RestorePage: 'arrow history paper refresh rotate undo web', RingVolume: 'mobile phone', Room: 'gps location map marker pin place spot', RoomService: 'bell concierge', Rotate90DegreesCcw: 'arrow', RotateLeft: 'arrow circle refresh reload reset', RotateRight: 'arrow circle', RoundedCorner: 'shape square transform', Router: 'device network', Rowing: 'activity boat canoe human person sports water', RssFeed: 'network wifi', Save: 'diskette floppy write', SaveAlt: 'diskette floppy write', Scanner: 'device', Schedule: 'calendar clock date mark save time', School: 'college university', ScreenLockLandscape: 'mobile phone security', ScreenLockPortrait: 'mobile phone security', ScreenLockRotation: 'mobile phone', ScreenRotation: 'mobile phone', ScreenShare: 'laptop monitor', SdStorage: 'microsd', Search: 'filter find glass look magnifying up', Security: 'shield', Send: 'chat message telegram', SentimentDissatisfied: 'emoji emoticon sad smiley', SentimentSatisfied: 'emoji emoticon happy like smiley', SentimentVeryDissatisfied: 'emoji emoticon sad smiley unhappy', SentimentVerySatisfied: 'emoji emoticon happy like smiley', Settings: 'gear', SettingsApplications: 'details gear information personal save service', SettingsBackupRestore: 'arrow backwards history refresh reverse rotate time undo', SettingsBluetooth: 'connection connectivity network wifi', SettingsBrightness: 'dark light mode sun', SettingsCell: 'cellphone device mobile', SettingsEthernet: 'arrows brackets connection connectivity dots network parenthesis wifi', SettingsInputAntenna: 'connection connectivity network wifi', SettingsInputComponent: 'cable connection connectivity plugs points', SettingsInputComposite: 'cable component connection connectivity plugs points', SettingsInputHdmi: 'cable connection connectivity plugin points', SettingsInputSvideo: 'connection connectivity plugin plugs points svideo,', SettingsOverscan: 'arrows expand image photo picture', SettingsPhone: 'cell device mobile', SettingsPower: 'information off save shutdown', SettingsRemote: 'bluetooth control wifi', SettingsSystemDaydream: 'cloud', SettingsVoice: 'microphone recorder speaker', Shop: 'arrow briefcase buy cart google play purchase shopping', ShoppingBasket: 'add buy cart purchase', ShoppingCart: 'add buy checkout purchase', ShopTwo: 'arrow briefcase buy cart google play purchase shopping', ShortText: 'lines', ShowChart: 'analytics graph line stock', Shuffle: 'arrows controls music video', SignalCellular4Bar: 'network', SignalCellularConnectedNoInternet0Bar: 'network', SignalCellularConnectedNoInternet1Bar: 'network', SignalCellularConnectedNoInternet2Bar: 'network', SignalCellularConnectedNoInternet3Bar: 'network', SignalCellularConnectedNoInternet4Bar: 'network', SignalCellularNoSim: 'network', SignalCellularNull: 'network', SignalCellularOff: 'network', SignalWifi0Bar: 'network', SignalWifi1Bar: 'network', SignalWifi1BarLock: 'network', SignalWifi2Bar: 'network', SignalWifi2BarLock: 'network', SignalWifi3Bar: 'network', SignalWifi3BarLock: 'network', SignalWifi4Bar: 'network', SignalWifi4BarLock: 'network', SignalWifiOff: 'network', SimCard: 'network', SingleBed: 'hotel queen sleep', SkipNext: 'arrow back controls music play previous video', SkipPrevious: 'arrow controls forward music next play video', Slideshow: 'presentation', SlowMotionVideo: 'arrow circle controls music play time', Smartphone: 'mobile', SmokeFree: 'cigarette', SmokingRooms: 'cigarette', Sms: 'chat comment message', SmsFailed: 'chat comment message', Snooze: 'alarm clock set timer', Sort: 'lines', SortByAlpha: 'alphabetize letters list order organize', Spa: 'flower', Speaker: 'audio', SpeakerGroup: 'audio', SpeakerNotes: 'bubble cards chat comment format list message speech', SpeakerNotesOff: 'bubble cards chat comment format list message speech', SpeakerPhone: 'mobile', Speed: 'clock dial measure test', Spellcheck: 'alphabet checkmark edit letter processor word write', Sports: 'whistle', SportsEsports: 'controller gamepad playstation xbox', SportsFootball: 'american', SportsHockey: 'ice', SportsKabaddi: 'fighting judo martial', SportsSoccer: 'football', Star: 'rating', StarBorder: 'rating', StarHalf: 'rating', Stars: 'circle favorite like love rate rating', StayCurrentLandscape: 'mobile phone', StayCurrentPortrait: 'mobile phone', StayPrimaryLandscape: 'mobile phone', StayPrimaryPortrait: 'mobile phone', Stop: 'arrow controls music play square video', StopScreenShare: 'laptop monitor', Storage: 'database network server', Store: 'building buy e-commerce purchase shop storefront', Storefront: 'merchant shop stall', StoreMallDirectory: 'building', Straighten: 'piano', Streetview: 'gps location map', SubdirectoryArrowLeft: 'arrow', SubdirectoryArrowRight: 'arrow', Subject: 'document email full justify lines list note text writing', Subscriptions: 'enroll order playlist queue subscribe youtube', Subtitles: 'accessibility accessible captions language translate', Subway: 'metro', SupervisedUserCircle: 'avatar human people person profile supervisor', SupervisorAccount: 'administrator avatar human people person profile supervised user', SurroundSound: 'audio circle speaker system volumn', SwapCalls: 'arrow', SwapHoriz: 'arrows back direction horizontal', SwapHorizontalCircle: 'arrows back direction', SwapVert: 'arrows back direction vertical', SwapVerticalCircle: 'arrows back direction horizontal', Sync: 'arrows refresh', SyncAlt: 'arrows', SyncDisabled: 'arrows refresh', SyncProblem: 'arrows refresh', SystemUpdate: 'arrow download', SystemUpdateAlt: 'arrow download', TabletMac: 'apple', TapAndPlay: 'nfc wifi', Telegram: 'brand call chat logo messaging voice', TextFormat: 'letter', TextRotateUp: 'arrow field move', TextRotateVertical: 'arrow field move verticle', TextRotationAngledown: 'arrow field move rotate', TextRotationAngleup: 'arrow field move rotate', TextRotationDown: 'arrow field move rotate', TextRotationNone: 'arrow field move rotate', Textsms: 'chat comment message', Theaters: 'media movies photography showtimes video watch', ThreeDRotation: '3d arrows vr', ThumbDown: 'dislike favorite finger hand rate rating reject up vote', ThumbDownAlt: 'dislike hand reject vote', ThumbsUpDown: 'dislike favorite finger hand rate rating vote', ThumbUp: 'approve dislike down favorite finger hand rate rating success vote', ThumbUpAlt: 'approve hand like success vote', Timeline: 'analytics chart graph history line movement points trending zigzap', Timer: 'clock stopwatch wait', TimerOff: 'clock stopwatch', Toc: 'content format lines list reorder stacked table text titles', Today: 'agenda calendar date event mark month range remember reminder week', Toll: 'booth car circles payment ticket', TouchApp: 'arrow finger gesture hand swipe', Toys: 'fan', TrackChanges: 'bullseye circle evolve lines movement radar rotate shift target', Traffic: 'light', TransferWithinAStation: 'man person transit', Translate: 'alphabet language letter speaking speech text translator words', TrendingDown: 'arrow change chart graph metric movement rate sale tracking', TrendingFlat: 'arrow change chart graph metric movement rate tracking', TrendingUp: 'arrow change chart graph metric movement rate tracking', Tune: 'settings sliders', TurnedIn: 'bookmark item remember save submit', TurnedInNot: 'bookmark item outline remember save submit', Tv: 'television', Twitter: 'brand logo social', TwoWheeler: 'bicycle moped motorbike ride riding transportation vehicle wheels', Unarchive: 'arrow', Undo: 'arrow', UnfoldLess: 'arrow', UnfoldMore: 'arrow', Update: 'arrow backwards clock future history refresh reverse rotate time', VerifiedUser: 'audit certified checkmark security shield', VerticalAlignBottom: 'arrow', VerticalAlignCenter: 'arrow', VerticalAlignTop: 'arrow', VerticalSplit: 'format paragraph text website', Vibration: 'mobile phone', VideoCall: 'camera chat conference plus screen', Videocam: 'camera chat conference screen', VideocamOff: 'camera chat conference screen', VideogameAsset: 'controller gamepad nintendo playstation xbox', VideoLabel: 'device item screen', VideoLibrary: 'collection', ViewAgenda: 'blocks cards format website,stacked', ViewArray: 'blocks format website', ViewCarousel: 'banner blocks cards format images', ViewColumn: 'blocks format grid vertical website', ViewComfy: 'grid', ViewCompact: 'grid', ViewDay: 'blocks calendar cards carousel format week', ViewHeadline: 'blocks format paragraph text website', ViewList: 'blocks format lines reorder stacked title', ViewModule: 'blocks format reorder squares stacked title', ViewQuilt: 'blocks format reorder squares stacked title', ViewStream: 'blocks format lines list reorder stacked title', ViewWeek: 'bars blocks columns day format', Vignette: 'effect photo', Visibility: 'eye on password reveal see shown view visability preview', VisibilityOff: 'eye hidden invisible on password reveal see show view visability', VoiceChat: 'camera', VolumeDown: 'control sound', VolumeMute: 'control sound', VolumeOff: 'control sound', VolumeUp: 'control sound', VpnKey: 'login password security signin signup register', VpnLock: 'earth globe password security world', Wallpaper: 'image picture', Warning: 'alert announcement danger error exclamation feedback problem triangle', Watch: 'smartwatch', WatchLater: 'clock hour minute time', WbIncandescent: 'lamp lightbulb', WbSunny: 'weather', Wc: 'gender person toilet unisex gender', Web: 'blocks browser internet screen website www', WebAsset: 'browser download image internet screen video website www', Weekend: 'chair couch seat', WhatsApp: 'brand call chat logo messaging voice', Whatshot: 'fire trending', Widgets: 'blocks', Wifi: 'network', WifiLock: 'network', WifiTethering: 'network', Work: 'briefcase job suitcase', WorkOff: 'briefcase job suitcase', WorkOutline: 'briefcase job suitcase', WrapText: 'arrow', YouTube: 'brand logo social video', YoutubeSearchedFor: 'arrow backwards refresh restore reverse rotate', ZoomIn: 'bigger glass grow magnifier magnifying plus scale size', ZoomOut: 'glass magnifier magnifying minus negative scale size smaller', ZoomOutMap: 'arrows', }; export default synonyms;
[docs] Add read synonym to drafts (#24854)
docs/src/pages/components/material-icons/synonyms.js
[docs] Add read synonym to drafts (#24854)
<ide><path>ocs/src/pages/components/material-icons/synonyms.js <ide> DonutLarge: 'chart circle complete graph inprogress,', <ide> DonutSmall: 'chart circle', <ide> DoubleArrow: 'chevron right', <del> Drafts: 'email envelope letter', <add> Drafts: 'email envelope letter read', <ide> DragHandle: 'lines', <ide> DragIndicator: 'circle dots drop move shape shift', <ide> DriveEta: 'car transport vehicle',
Java
mpl-2.0
b82aaaf5edfacc58d20787708fb379f33a9bfb5c
0
tuchida/rhino,tuchida/rhino,lv7777/egit_test,tntim96/rhino-apigee,tuchida/rhino,AlexTrotsenko/rhino,tuchida/rhino,swannodette/rhino,tntim96/htmlunit-rhino-fork,sam/htmlunit-rhino-fork,jsdoc3/rhino,lv7777/egit_test,lv7777/egit_test,AlexTrotsenko/rhino,sam/htmlunit-rhino-fork,rasmuserik/rhino,tuchida/rhino,tejassaoji/RhinoCoarseTainting,tntim96/rhino-jscover-repackaged,AlexTrotsenko/rhino,rasmuserik/rhino,ashwinrayaprolu1984/rhino,sainaen/rhino,swannodette/rhino,Angelfirenze/rhino,Pilarbrist/rhino,tntim96/rhino-apigee,qhanam/rhino,tntim96/htmlunit-rhino-fork,Angelfirenze/rhino,sam/htmlunit-rhino-fork,sam/htmlunit-rhino-fork,AlexTrotsenko/rhino,ashwinrayaprolu1984/rhino,ashwinrayaprolu1984/rhino,qhanam/rhino,tntim96/rhino-jscover,swannodette/rhino,InstantWebP2P/rhino-android,tuchida/rhino,AlexTrotsenko/rhino,sam/htmlunit-rhino-fork,jsdoc3/rhino,swannodette/rhino,jsdoc3/rhino,lv7777/egit_test,Pilarbrist/rhino,tntim96/rhino-apigee,AlexTrotsenko/rhino,sam/htmlunit-rhino-fork,tuchida/rhino,tejassaoji/RhinoCoarseTainting,Pilarbrist/rhino,Angelfirenze/rhino,tejassaoji/RhinoCoarseTainting,swannodette/rhino,qhanam/rhino,lv7777/egit_test,tejassaoji/RhinoCoarseTainting,swannodette/rhino,sainaen/rhino,Angelfirenze/rhino,Distrotech/rhino,InstantWebP2P/rhino-android,tntim96/rhino-jscover,Angelfirenze/rhino,ashwinrayaprolu1984/rhino,Angelfirenze/rhino,tejassaoji/RhinoCoarseTainting,tntim96/rhino-jscover-repackaged,qhanam/rhino,sainaen/rhino,swannodette/rhino,tejassaoji/RhinoCoarseTainting,lv7777/egit_test,lv7777/egit_test,Pilarbrist/rhino,Pilarbrist/rhino,tejassaoji/RhinoCoarseTainting,Pilarbrist/rhino,AlexTrotsenko/rhino,Pilarbrist/rhino,sainaen/rhino,ashwinrayaprolu1984/rhino,ashwinrayaprolu1984/rhino,sainaen/rhino,sam/htmlunit-rhino-fork,sainaen/rhino,ashwinrayaprolu1984/rhino,Distrotech/rhino,Angelfirenze/rhino,sainaen/rhino
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.lang.reflect.UndeclaredThrowableException; import java.net.URL; import java.security.AccessController; import java.security.CodeSource; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.security.SecureClassLoader; import java.util.Map; import java.util.WeakHashMap; /** * @author Attila Szegedi */ public abstract class SecureCaller { private static final byte[] secureCallerImplBytecode = loadBytecode(); // We're storing a CodeSource -> (ClassLoader -> SecureRenderer), since we // need to have one renderer per class loader. We're using weak hash maps // and soft references all the way, since we don't want to interfere with // cleanup of either CodeSource or ClassLoader objects. private static final Map callers = new WeakHashMap(); public abstract Object call(Callable callable, Context cx, Scriptable scope, Scriptable thisObj, Object[] args); /** * Call the specified callable using a protection domain belonging to the * specified code source. */ static Object callSecurely(final CodeSource codeSource, Callable callable, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { final Thread thread = Thread.currentThread(); // Run in doPrivileged as we might be checked for "getClassLoader" // runtime permission final ClassLoader classLoader = (ClassLoader)AccessController.doPrivileged( new PrivilegedAction() { public Object run() { return thread.getContextClassLoader(); } }); Map classLoaderMap; synchronized(callers) { classLoaderMap = (Map)callers.get(codeSource); if(classLoaderMap == null) { classLoaderMap = new WeakHashMap(); callers.put(codeSource, classLoaderMap); } } SecureCaller caller; synchronized(classLoaderMap) { SoftReference ref = (SoftReference)classLoaderMap.get(classLoader); if(ref != null) { caller = (SecureCaller)ref.get(); } else { caller = null; } if(caller == null) { try { // Run in doPrivileged as we'll be checked for // "createClassLoader" runtime permission caller = (SecureCaller)AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws Exception { ClassLoader effectiveClassLoader; Class thisClass = getClass(); if(classLoader.loadClass(thisClass.getName()) != thisClass) { effectiveClassLoader = thisClass.getClassLoader(); } else { effectiveClassLoader = classLoader; } SecureClassLoaderImpl secCl = new SecureClassLoaderImpl(effectiveClassLoader); Class c = secCl.defineAndLinkClass( SecureCaller.class.getName() + "Impl", secureCallerImplBytecode, codeSource); return c.newInstance(); } }); classLoaderMap.put(classLoader, new SoftReference(caller)); } catch(PrivilegedActionException ex) { throw new UndeclaredThrowableException(ex.getCause()); } } } return caller.call(callable, cx, scope, thisObj, args); } private static class SecureClassLoaderImpl extends SecureClassLoader { SecureClassLoaderImpl(ClassLoader parent) { super(parent); } Class defineAndLinkClass(String name, byte[] bytes, CodeSource cs) { Class cl = defineClass(name, bytes, 0, bytes.length, cs); resolveClass(cl); return cl; } } private static byte[] loadBytecode() { return (byte[])AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return loadBytecodePrivileged(); } }); } private static byte[] loadBytecodePrivileged() { URL url = SecureCaller.class.getResource("SecureCallerImpl.clazz"); try { InputStream in = url.openStream(); try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); for(;;) { int r = in.read(); if(r == -1) { return bout.toByteArray(); } bout.write(r); } } finally { in.close(); } } catch(IOException e) { throw new UndeclaredThrowableException(e); } } }
src/org/mozilla/javascript/SecureCaller.java
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-1999 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.lang.reflect.UndeclaredThrowableException; import java.net.URL; import java.security.AccessController; import java.security.CodeSource; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.security.SecureClassLoader; import java.util.Map; import java.util.WeakHashMap; /** * @author Attila Szegedi */ public abstract class SecureCaller { private static final byte[] secureCallerImplBytecode = loadBytecode(); // We're storing a CodeSource -> (ClassLoader -> SecureRenderer), since we // need to have one renderer per class loader. We're using weak hash maps // and soft references all the way, since we don't want to interfere with // cleanup of either CodeSource or ClassLoader objects. private static final Map callers = new WeakHashMap(); public abstract Object call(Callable callable, Context cx, Scriptable scope, Scriptable thisObj, Object[] args); /** * Render the specified template element with the specified environment, * using a protection domain belonging to the specified code source. * @param codeSource the code source defining the protection domain * @param env the processing environment * @param t the processed template element * @throws TemplateException if environment's processing of the template * element throws the exception * @throws IOException if environment's processing of the template * element throws the exception */ static Object callSecurely(final CodeSource codeSource, Callable callable, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { final Thread thread = Thread.currentThread(); // Run in doPrivileged as we might be checked for "getClassLoader" // runtime permission final ClassLoader classLoader = (ClassLoader)AccessController.doPrivileged( new PrivilegedAction() { public Object run() { return thread.getContextClassLoader(); } }); Map classLoaderMap; synchronized(callers) { classLoaderMap = (Map)callers.get(codeSource); if(classLoaderMap == null) { classLoaderMap = new WeakHashMap(); callers.put(codeSource, classLoaderMap); } } SecureCaller caller; synchronized(classLoaderMap) { SoftReference ref = (SoftReference)classLoaderMap.get(classLoader); if(ref != null) { caller = (SecureCaller)ref.get(); } else { caller = null; } if(caller == null) { try { // Run in doPrivileged as we'll be checked for // "createClassLoader" runtime permission caller = (SecureCaller)AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws Exception { ClassLoader effectiveClassLoader; Class thisClass = getClass(); if(classLoader.loadClass(thisClass.getName()) != thisClass) { effectiveClassLoader = thisClass.getClassLoader(); } else { effectiveClassLoader = classLoader; } SecureClassLoaderImpl secCl = new SecureClassLoaderImpl(effectiveClassLoader); Class c = secCl.defineAndLinkClass( SecureCaller.class.getName() + "Impl", secureCallerImplBytecode, codeSource); return c.newInstance(); } }); classLoaderMap.put(classLoader, new SoftReference(caller)); } catch(PrivilegedActionException ex) { throw new UndeclaredThrowableException(ex.getCause()); } } } return caller.call(callable, cx, scope, thisObj, args); } private static class SecureClassLoaderImpl extends SecureClassLoader { SecureClassLoaderImpl(ClassLoader parent) { super(parent); } Class defineAndLinkClass(String name, byte[] bytes, CodeSource cs) { Class cl = defineClass(name, bytes, 0, bytes.length, cs); resolveClass(cl); return cl; } } private static byte[] loadBytecode() { return (byte[])AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return loadBytecodePrivileged(); } }); } private static byte[] loadBytecodePrivileged() { URL url = SecureCaller.class.getResource("SecureCallerImpl.clazz"); try { InputStream in = url.openStream(); try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); for(;;) { int r = in.read(); if(r == -1) { return bout.toByteArray(); } bout.write(r); } } finally { in.close(); } } catch(IOException e) { throw new UndeclaredThrowableException(e); } } }
Fix javadoc.
src/org/mozilla/javascript/SecureCaller.java
Fix javadoc.
<ide><path>rc/org/mozilla/javascript/SecureCaller.java <ide> Scriptable scope, Scriptable thisObj, Object[] args); <ide> <ide> /** <del> * Render the specified template element with the specified environment, <del> * using a protection domain belonging to the specified code source. <del> * @param codeSource the code source defining the protection domain <del> * @param env the processing environment <del> * @param t the processed template element <del> * @throws TemplateException if environment's processing of the template <del> * element throws the exception <del> * @throws IOException if environment's processing of the template <del> * element throws the exception <add> * Call the specified callable using a protection domain belonging to the <add> * specified code source. <ide> */ <ide> static Object callSecurely(final CodeSource codeSource, Callable callable, <ide> Context cx, Scriptable scope, Scriptable thisObj, Object[] args)
Java
agpl-3.0
813255953cc05837dae3ec32dbfd8e333d418245
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
36a48abe-2e62-11e5-9284-b827eb9e62be
hello.java
369f1d7c-2e62-11e5-9284-b827eb9e62be
36a48abe-2e62-11e5-9284-b827eb9e62be
hello.java
36a48abe-2e62-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>369f1d7c-2e62-11e5-9284-b827eb9e62be <add>36a48abe-2e62-11e5-9284-b827eb9e62be
Java
apache-2.0
e0cfc645728b74a407bf72462d96da05f96c5757
0
pubudu538/carbon-apimgt,rswijesena/carbon-apimgt,pradeepmurugesan/carbon-apimgt,Minoli/carbon-apimgt,bhathiya/carbon-apimgt,dewmini/carbon-apimgt,ruks/carbon-apimgt,pradeepmurugesan/carbon-apimgt,Rajith90/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,hevayo/carbon-apimgt,Arshardh/carbon-apimgt,Arshardh/carbon-apimgt,thusithak/carbon-apimgt,Minoli/carbon-apimgt,abimarank/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,malinthaprasan/carbon-apimgt,charithag/carbon-apimgt,thilinicooray/carbon-apimgt,wso2/carbon-apimgt,chamindias/carbon-apimgt,sambaheerathan/carbon-apimgt,hevayo/carbon-apimgt,uvindra/carbon-apimgt,nuwand/carbon-apimgt,pradeepmurugesan/carbon-apimgt,charithag/carbon-apimgt,ruks/carbon-apimgt,bhathiya/carbon-apimgt,nuwand/carbon-apimgt,charithag/carbon-apimgt,fazlan-nazeem/carbon-apimgt,lakmali/carbon-apimgt,Minoli/carbon-apimgt,abimarank/carbon-apimgt,praminda/carbon-apimgt,pubudu538/carbon-apimgt,dhanuka84/carbon-apimgt,tharindu1st/carbon-apimgt,chamindias/carbon-apimgt,thusithak/carbon-apimgt,tharikaGitHub/carbon-apimgt,wso2/carbon-apimgt,lalaji/carbon-apimgt,dhanuka84/carbon-apimgt,abimarank/carbon-apimgt,charithag/carbon-apimgt,rswijesena/carbon-apimgt,uvindra/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,chamindias/carbon-apimgt,thilinicooray/carbon-apimgt,jaadds/carbon-apimgt,jaadds/carbon-apimgt,nuwand/carbon-apimgt,chamindias/carbon-apimgt,lalaji/carbon-apimgt,Rajith90/carbon-apimgt,ruks/carbon-apimgt,knPerera/carbon-apimgt,praminda/carbon-apimgt,prasa7/carbon-apimgt,wso2/carbon-apimgt,knPerera/carbon-apimgt,lakmali/carbon-apimgt,dewmini/carbon-apimgt,chamilaadhi/carbon-apimgt,bhathiya/carbon-apimgt,jaadds/carbon-apimgt,ChamNDeSilva/carbon-apimgt,uvindra/carbon-apimgt,tharikaGitHub/carbon-apimgt,wso2/carbon-apimgt,sineth-neranjana/carbon-apimgt,thilinicooray/carbon-apimgt,tharindu1st/carbon-apimgt,dhanuka84/carbon-apimgt,tharindu1st/carbon-apimgt,pubudu538/carbon-apimgt,Rajith90/carbon-apimgt,thilinicooray/carbon-apimgt,prasa7/carbon-apimgt,praminda/carbon-apimgt,uvindra/carbon-apimgt,isharac/carbon-apimgt,dhanuka84/carbon-apimgt,prasa7/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,ChamNDeSilva/carbon-apimgt,harsha89/carbon-apimgt,nuwand/carbon-apimgt,rswijesena/carbon-apimgt,knPerera/carbon-apimgt,chamilaadhi/carbon-apimgt,bhathiya/carbon-apimgt,fazlan-nazeem/carbon-apimgt,sineth-neranjana/carbon-apimgt,knPerera/carbon-apimgt,tharindu1st/carbon-apimgt,prasa7/carbon-apimgt,isharac/carbon-apimgt,sineth-neranjana/carbon-apimgt,ChamNDeSilva/carbon-apimgt,fazlan-nazeem/carbon-apimgt,lakmali/carbon-apimgt,harsha89/carbon-apimgt,harsha89/carbon-apimgt,Rajith90/carbon-apimgt,pubudu538/carbon-apimgt,harsha89/carbon-apimgt,malinthaprasan/carbon-apimgt,pradeepmurugesan/carbon-apimgt,lalaji/carbon-apimgt,isharac/carbon-apimgt,sambaheerathan/carbon-apimgt,sambaheerathan/carbon-apimgt,isharac/carbon-apimgt,fazlan-nazeem/carbon-apimgt,sineth-neranjana/carbon-apimgt,Arshardh/carbon-apimgt,malinthaprasan/carbon-apimgt,hevayo/carbon-apimgt,Arshardh/carbon-apimgt,malinthaprasan/carbon-apimgt,tharikaGitHub/carbon-apimgt,tharikaGitHub/carbon-apimgt,hevayo/carbon-apimgt,chamilaadhi/carbon-apimgt,jaadds/carbon-apimgt,thusithak/carbon-apimgt,chamilaadhi/carbon-apimgt,dewmini/carbon-apimgt,ruks/carbon-apimgt
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.apimgt.impl.executors; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.APIProvider; import org.wso2.carbon.apimgt.api.FaultGatewaysException; import org.wso2.carbon.apimgt.api.model.API; import org.wso2.carbon.apimgt.api.model.APIStatus; import org.wso2.carbon.apimgt.api.model.Tier; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.APIManagerFactory; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.apimgt.impl.utils.APIVersionComparator; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.governance.api.generic.GenericArtifactManager; import org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact; import org.wso2.carbon.governance.registry.extensions.interfaces.Execution; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.jdbc.handlers.RequestContext; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import java.util.List; import java.util.Map; import java.util.Set; /** * This class is an implementation of the * interface {@link org.wso2.carbon.governance.registry.extensions.interfaces.Execution} * This class consists methods that will create, prototype, publish, block, deprecate and * retire an API to API Manager. * <p/> * This executor used to publish a service to API store as a API. * * @see org.wso2.carbon.governance.registry.extensions.interfaces.Execution */ public class APIExecutor implements Execution { Log log = LogFactory.getLog(APIExecutor.class); /** * This method is called when the execution class is initialized. * All the execution classes are initialized only once. * * @param parameterMap Static parameter map given by the user. * These are the parameters that have been given in the * lifecycle configuration as the parameters of the executor. */ public void init(Map parameterMap) { } /** * @param context The request context that was generated from the registry core. * The request context contains the resource, resource path and other * variables generated during the initial call. * @param currentState The current lifecycle state. * @param targetState The target lifecycle state. * @return Returns whether the execution was successful or not. */ public boolean execute(RequestContext context, String currentState, String targetState) { boolean executed = false; String user = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String domain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); //String userWithDomain = APIUtil.appendDomainWithUser(user, domain); String userWithDomain = user; if(!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(domain)){ //userWithDomain = APIUtil.appendDomainWithUser(user, domain); userWithDomain = user + APIConstants.EMAIL_DOMAIN_SEPARATOR + domain; } userWithDomain = APIUtil.replaceEmailDomainBack(userWithDomain); try { String tenantUserName = MultitenantUtils.getTenantAwareUsername(userWithDomain); int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(domain); GenericArtifactManager artifactManager = APIUtil .getArtifactManager(context.getSystemRegistry(), APIConstants.API_KEY); Registry registry = ServiceReferenceHolder.getInstance(). getRegistryService().getGovernanceUserRegistry(tenantUserName, tenantId); Resource apiResource = context.getResource(); String artifactId = apiResource.getUUID(); if (artifactId == null) { return executed; } GenericArtifact apiArtifact = artifactManager.getGenericArtifact(artifactId); API api = APIUtil.getAPI(apiArtifact); APIProvider apiProvider = APIManagerFactory.getInstance().getAPIProvider(userWithDomain); APIStatus oldStatus = api.getStatus(); APIStatus newStatus = APIUtil.getApiStatus(targetState); if ((oldStatus.equals(APIStatus.CREATED) || oldStatus.equals(APIStatus.PROTOTYPED)) && newStatus.equals(APIStatus.PUBLISHED)) { Set<Tier> tiers = api.getAvailableTiers(); String endPoint = api.getEndpointConfig(); if (endPoint != null && endPoint.trim().length() > 0) { if (tiers == null || tiers.size() <= 0) { throw new APIManagementException("Failed to publish service to API store while executing " + "APIExecutor. No Tiers selected"); } } else { throw new APIManagementException("Failed to publish service to API store while executing APIExecutor." + " No endpoint selected"); } } boolean deprecateOldVersions = false; boolean makeKeysForwardCompatible = false; //If the API status is CREATED ,check for check list items of lifecycle if (oldStatus.equals(APIStatus.CREATED)) { deprecateOldVersions = apiArtifact.isLCItemChecked(0, APIConstants.API_LIFE_CYCLE); makeKeysForwardCompatible = !(apiArtifact.isLCItemChecked(1, APIConstants.API_LIFE_CYCLE)); } //executed = apiProvider.updateAPIStatus(api.getId(), targetState, true, deprecateOldVersions, makeKeysForwardCompatible); //push the state change to gateway Map<String, String> failedGateways = apiProvider.propergateAPIStatusChangeToGateways(api.getId(), newStatus); //update api related information for state change executed = apiProvider.updateAPIforStateChange(api.getId(), newStatus, failedGateways); if ((oldStatus.equals(APIStatus.CREATED) || oldStatus.equals(APIStatus.PROTOTYPED)) && newStatus.equals(APIStatus.PUBLISHED)) { if (makeKeysForwardCompatible) { apiProvider.makeAPIKeysForwardCompatible(api); } if(deprecateOldVersions) { String provider = APIUtil.replaceEmailDomain(api.getId().getProviderName()); List<API> apiList = apiProvider.getAPIsByProvider(provider); APIVersionComparator versionComparator = new APIVersionComparator(); for (API oldAPI : apiList) { if (oldAPI.getId().getApiName().equals(api.getId().getApiName()) && versionComparator.compare(oldAPI, api) < 0 && (oldAPI.getStatus().equals(APIStatus.PUBLISHED))) { apiProvider.changeLifeCycleStatus(oldAPI.getId(), APIConstants.API_LC_ACTION_DEPRECATE); } } } } //Setting resource again to the context as it's updated within updateAPIStatus method String apiPath = APIUtil.getAPIPath(api.getId()); apiResource = registry.get(apiPath); context.setResource(apiResource); } catch (RegistryException e) { log.error("Failed to get the generic artifact while executing APIExecutor. ", e); } catch (APIManagementException e) { log.error("Failed to publish service to API store while executing APIExecutor. ", e); } catch (FaultGatewaysException e) { log.error("Failed to publish service gateway while executing APIExecutor. ", e); } catch (UserStoreException e) { log.error("Failed to publish service gateway while executing APIExecutor. ", e); } return executed; } }
components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/executors/APIExecutor.java
/* * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.wso2.carbon.apimgt.impl.executors; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.APIProvider; import org.wso2.carbon.apimgt.api.FaultGatewaysException; import org.wso2.carbon.apimgt.api.model.API; import org.wso2.carbon.apimgt.api.model.APIStatus; import org.wso2.carbon.apimgt.api.model.Tier; import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.APIManagerFactory; import org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder; import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.apimgt.impl.utils.APIVersionComparator; import org.wso2.carbon.context.CarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.governance.api.generic.GenericArtifactManager; import org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact; import org.wso2.carbon.governance.registry.extensions.interfaces.Execution; import org.wso2.carbon.registry.core.Registry; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.jdbc.handlers.RequestContext; import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.utils.multitenancy.MultitenantConstants; import org.wso2.carbon.utils.multitenancy.MultitenantUtils; import java.util.List; import java.util.Map; import java.util.Set; /** * This class is an implementation of the * interface {@link org.wso2.carbon.governance.registry.extensions.interfaces.Execution} * This class consists methods that will create, prototype, publish, block, deprecate and * retire an API to API Manager. * <p/> * This executor used to publish a service to API store as a API. * * @see org.wso2.carbon.governance.registry.extensions.interfaces.Execution */ public class APIExecutor implements Execution { Log log = LogFactory.getLog(APIExecutor.class); /** * This method is called when the execution class is initialized. * All the execution classes are initialized only once. * * @param parameterMap Static parameter map given by the user. * These are the parameters that have been given in the * lifecycle configuration as the parameters of the executor. */ public void init(Map parameterMap) { } /** * @param context The request context that was generated from the registry core. * The request context contains the resource, resource path and other * variables generated during the initial call. * @param currentState The current lifecycle state. * @param targetState The target lifecycle state. * @return Returns whether the execution was successful or not. */ public boolean execute(RequestContext context, String currentState, String targetState) { boolean executed = false; String user = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername(); String domain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain(); //String userWithDomain = APIUtil.appendDomainWithUser(user, domain); String userWithDomain = user; if(!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(domain)){ userWithDomain = APIUtil.appendDomainWithUser(user, domain); } userWithDomain = APIUtil.replaceEmailDomainBack(userWithDomain); try { String tenantUserName = MultitenantUtils.getTenantAwareUsername(userWithDomain); int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(domain); GenericArtifactManager artifactManager = APIUtil .getArtifactManager(context.getSystemRegistry(), APIConstants.API_KEY); Registry registry = ServiceReferenceHolder.getInstance(). getRegistryService().getGovernanceUserRegistry(tenantUserName, tenantId); Resource apiResource = context.getResource(); String artifactId = apiResource.getUUID(); if (artifactId == null) { return executed; } GenericArtifact apiArtifact = artifactManager.getGenericArtifact(artifactId); API api = APIUtil.getAPI(apiArtifact); APIProvider apiProvider = APIManagerFactory.getInstance().getAPIProvider(userWithDomain); APIStatus oldStatus = api.getStatus(); APIStatus newStatus = APIUtil.getApiStatus(targetState); if ((oldStatus.equals(APIStatus.CREATED) || oldStatus.equals(APIStatus.PROTOTYPED)) && newStatus.equals(APIStatus.PUBLISHED)) { Set<Tier> tiers = api.getAvailableTiers(); String endPoint = api.getEndpointConfig(); if (endPoint != null && endPoint.trim().length() > 0) { if (tiers == null || tiers.size() <= 0) { throw new APIManagementException("Failed to publish service to API store while executing " + "APIExecutor. No Tiers selected"); } } else { throw new APIManagementException("Failed to publish service to API store while executing APIExecutor." + " No endpoint selected"); } } boolean deprecateOldVersions = false; boolean makeKeysForwardCompatible = false; //If the API status is CREATED ,check for check list items of lifecycle if (oldStatus.equals(APIStatus.CREATED)) { deprecateOldVersions = apiArtifact.isLCItemChecked(0, APIConstants.API_LIFE_CYCLE); makeKeysForwardCompatible = !(apiArtifact.isLCItemChecked(1, APIConstants.API_LIFE_CYCLE)); } //executed = apiProvider.updateAPIStatus(api.getId(), targetState, true, deprecateOldVersions, makeKeysForwardCompatible); //push the state change to gateway Map<String, String> failedGateways = apiProvider.propergateAPIStatusChangeToGateways(api.getId(), newStatus); //update api related information for state change executed = apiProvider.updateAPIforStateChange(api.getId(), newStatus, failedGateways); if ((oldStatus.equals(APIStatus.CREATED) || oldStatus.equals(APIStatus.PROTOTYPED)) && newStatus.equals(APIStatus.PUBLISHED)) { if (makeKeysForwardCompatible) { apiProvider.makeAPIKeysForwardCompatible(api); } if(deprecateOldVersions) { String provider = APIUtil.replaceEmailDomain(api.getId().getProviderName()); List<API> apiList = apiProvider.getAPIsByProvider(provider); APIVersionComparator versionComparator = new APIVersionComparator(); for (API oldAPI : apiList) { if (oldAPI.getId().getApiName().equals(api.getId().getApiName()) && versionComparator.compare(oldAPI, api) < 0 && (oldAPI.getStatus().equals(APIStatus.PUBLISHED))) { apiProvider.changeLifeCycleStatus(oldAPI.getId(), APIConstants.API_LC_ACTION_DEPRECATE); } } } } //Setting resource again to the context as it's updated within updateAPIStatus method String apiPath = APIUtil.getAPIPath(api.getId()); apiResource = registry.get(apiPath); context.setResource(apiResource); } catch (RegistryException e) { log.error("Failed to get the generic artifact while executing APIExecutor. ", e); } catch (APIManagementException e) { log.error("Failed to publish service to API store while executing APIExecutor. ", e); } catch (FaultGatewaysException e) { log.error("Failed to publish service gateway while executing APIExecutor. ", e); } catch (UserStoreException e) { log.error("Failed to publish service gateway while executing APIExecutor. ", e); } return executed; } }
fix for APIMANAGER-4303
components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/executors/APIExecutor.java
fix for APIMANAGER-4303
<ide><path>omponents/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/executors/APIExecutor.java <ide> <ide> String userWithDomain = user; <ide> if(!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(domain)){ <del> userWithDomain = APIUtil.appendDomainWithUser(user, domain); <add> //userWithDomain = APIUtil.appendDomainWithUser(user, domain); <add> userWithDomain = user + APIConstants.EMAIL_DOMAIN_SEPARATOR + domain; <ide> } <ide> <ide> userWithDomain = APIUtil.replaceEmailDomainBack(userWithDomain);
JavaScript
agpl-3.0
f7d7fd690bb8013a89d13f3ae699b152bfdc3455
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
00e403fe-2e63-11e5-9284-b827eb9e62be
helloWorld.js
00de9dec-2e63-11e5-9284-b827eb9e62be
00e403fe-2e63-11e5-9284-b827eb9e62be
helloWorld.js
00e403fe-2e63-11e5-9284-b827eb9e62be
<ide><path>elloWorld.js <del>00de9dec-2e63-11e5-9284-b827eb9e62be <add>00e403fe-2e63-11e5-9284-b827eb9e62be
JavaScript
bsd-3-clause
d6f9fa7e6e3775736a79b23affd01aca4772d6b6
0
yahoo/flux-router-component
var debug = require('debug')('navigateAction'), queryString = require('query-string'), searchPattern = /\?([^\#]*)/; function parseQueryString(path) { var search; var matches = path.match(searchPattern); if (matches) { search = matches[1]; } return (search && queryString.parse(search)) || {}; } module.exports = function (context, payload, done) { if (!context.router || !context.router.getRoute) { debug('no router available for navigate handling'); done(new Error('missing router')); return; } debug('executing', payload); var options = { navigate: payload, method: payload.method }; var route = context.router.getRoute(payload.path, options); if (!route) { var err = new Error('Url does not exist'); err.status = 404; done(err); return; } // add parsed query parameter object to route object, // and make it part of CHANGE_ROUTE_XXX action payload. route.query = parseQueryString(route.path); debug('dispatching CHANGE_ROUTE', route); context.dispatch('CHANGE_ROUTE_START', route); var action = route.config && route.config.action; if ('string' === typeof action && context.getAction) { action = context.getAction(action); } if (!action || 'function' !== typeof action) { debug('route has no action, dispatching without calling action'); context.dispatch('CHANGE_ROUTE_SUCCESS', route); done(); return; } debug('executing route action'); context.executeAction(action, route, function (err) { if (err) { context.dispatch('CHANGE_ROUTE_FAILURE', route); } else { context.dispatch('CHANGE_ROUTE_SUCCESS', route); } done(err); }); };
actions/navigate.js
var debug = require('debug')('navigateAction'), queryString = require('query-string'), searchPattern = /\?([^\#]*)/; function parseQueryString(path) { var search; var matches = path.match(searchPattern); if (matches) { search = matches[1]; } return (search && queryString.parse(search)) || {}; } module.exports = function (context, payload, done) { if (!context.router || !context.router.getRoute) { debug('no router available for navigate handling'); done(new Error('missing router')); return; } debug('executing', payload); var route = context.router.getRoute(payload.path, {navigate: payload}); if (!route) { var err = new Error('Url does not exist'); err.status = 404; done(err); return; } // add parsed query parameter object to route object, // and make it part of CHANGE_ROUTE_XXX action payload. route.query = parseQueryString(route.path); debug('dispatching CHANGE_ROUTE', route); context.dispatch('CHANGE_ROUTE_START', route); var action = route.config && route.config.action; if ('string' === typeof action && context.getAction) { action = context.getAction(action); } if (!action || 'function' !== typeof action) { debug('route has no action, dispatching without calling action'); context.dispatch('CHANGE_ROUTE_SUCCESS', route); done(); return; } debug('executing route action'); context.executeAction(action, route, function (err) { if (err) { context.dispatch('CHANGE_ROUTE_FAILURE', route); } else { context.dispatch('CHANGE_ROUTE_SUCCESS', route); } done(err); }); };
added 'method' to getRoute options
actions/navigate.js
added 'method' to getRoute options
<ide><path>ctions/navigate.js <ide> return; <ide> } <ide> debug('executing', payload); <del> var route = context.router.getRoute(payload.path, {navigate: payload}); <add> <add> var options = { <add> navigate: payload, <add> method: payload.method <add> }; <add> <add> var route = context.router.getRoute(payload.path, options); <ide> <ide> if (!route) { <ide> var err = new Error('Url does not exist');
Java
apache-2.0
e4466697d6559427cba5c11ef2674e2f6e1bd547
0
Khyzad/PID-webservice,HawaiiStateDigitalArchives/PID-webservice,Khyzad/PID-webservice,HawaiiStateDigitalArchives/PID-webservice
package com.hida.configuration; import java.util.Properties; import javax.sql.DataSource; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.hibernate4.HibernateTransactionManager; import org.springframework.orm.hibernate4.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; /** * Used to create a test environment for test cases. * * @author lruffin */ @Configuration @EnableTransactionManagement @ComponentScan({"com.hida.dao"}) public class HibernateTestConfiguration { @Autowired private Environment environment; @Bean public LocalSessionFactoryBean sessionFactory() { LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(dataSource()); sessionFactory.setPackagesToScan(new String[]{"com.hida.model"}); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; } @Bean(name = "dataSource") public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.hsqldb.jdbcDriver"); dataSource.setUrl("jdbc:hsqldb:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); dataSource.setUsername(""); dataSource.setPassword(""); return dataSource; } private Properties hibernateProperties() { Properties properties = new Properties(); properties.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); properties.put("hibernate.hbm2ddl.auto", "create-drop"); return properties; } @Bean @Autowired public HibernateTransactionManager transactionManager(SessionFactory s) { HibernateTransactionManager txManager = new HibernateTransactionManager(); txManager.setSessionFactory(s); return txManager; } }
Minter/src/test/java/com/hida/configuration/HibernateTestConfiguration.java
package com.hida.configuration; import java.util.Properties; import javax.sql.DataSource; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.hibernate4.HibernateTransactionManager; import org.springframework.orm.hibernate4.LocalSessionFactoryBean; import org.springframework.transaction.annotation.EnableTransactionManagement; /** * * @author lruffin */ @Configuration @EnableTransactionManagement @ComponentScan({ "com.hida.dao" }) public class HibernateTestConfiguration { @Autowired private Environment environment; @Bean public LocalSessionFactoryBean sessionFactory() { LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(dataSource()); sessionFactory.setPackagesToScan(new String[] { "com.hida.model" }); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; } @Bean(name = "dataSource") public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.hsqldb.jdbcDriver"); dataSource.setUrl("jdbc:hsqldb:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); dataSource.setUsername(""); dataSource.setPassword(""); return dataSource; } private Properties hibernateProperties() { Properties properties = new Properties(); properties.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); properties.put("hibernate.hbm2ddl.auto", "create-drop"); return properties; } @Bean @Autowired public HibernateTransactionManager transactionManager(SessionFactory s) { HibernateTransactionManager txManager = new HibernateTransactionManager(); txManager.setSessionFactory(s); return txManager; } }
Add javadocs to HibernateTestConfiguration
Minter/src/test/java/com/hida/configuration/HibernateTestConfiguration.java
Add javadocs to HibernateTestConfiguration
<ide><path>inter/src/test/java/com/hida/configuration/HibernateTestConfiguration.java <ide> package com.hida.configuration; <ide> <ide> import java.util.Properties; <del>import javax.sql.DataSource; <add>import javax.sql.DataSource; <ide> import org.hibernate.SessionFactory; <ide> import org.springframework.beans.factory.annotation.Autowired; <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.transaction.annotation.EnableTransactionManagement; <ide> <ide> /** <add> * Used to create a test environment for test cases. <ide> * <ide> * @author lruffin <ide> */ <ide> @Configuration <ide> @EnableTransactionManagement <del>@ComponentScan({ "com.hida.dao" }) <add>@ComponentScan({"com.hida.dao"}) <ide> public class HibernateTestConfiguration { <add> <ide> @Autowired <ide> private Environment environment; <del> <add> <ide> @Bean <ide> public LocalSessionFactoryBean sessionFactory() { <ide> LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); <ide> sessionFactory.setDataSource(dataSource()); <del> sessionFactory.setPackagesToScan(new String[] { "com.hida.model" }); <add> sessionFactory.setPackagesToScan(new String[]{"com.hida.model"}); <ide> sessionFactory.setHibernateProperties(hibernateProperties()); <ide> return sessionFactory; <ide> } <del> <add> <ide> @Bean(name = "dataSource") <ide> public DataSource dataSource() { <ide> DriverManagerDataSource dataSource = new DriverManagerDataSource(); <ide> dataSource.setDriverClassName("org.hsqldb.jdbcDriver"); <ide> dataSource.setUrl("jdbc:hsqldb:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE"); <ide> dataSource.setUsername(""); <del> dataSource.setPassword(""); <add> dataSource.setPassword(""); <ide> return dataSource; <ide> } <del> <add> <ide> private Properties hibernateProperties() { <ide> Properties properties = new Properties(); <ide> properties.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect"); <ide> properties.put("hibernate.hbm2ddl.auto", "create-drop"); <ide> return properties; <del> } <del> <add> } <add> <ide> @Bean <ide> @Autowired <ide> public HibernateTransactionManager transactionManager(SessionFactory s) {
Java
mit
5b76533cafbb57c8c0e6afc817a7501d01196a91
0
eduardodaluz/xfire,eduardodaluz/xfire
package org.codehaus.xfire.spring.remoting; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.MalformedURLException; import java.util.Arrays; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.wsdl.Definition; import javax.wsdl.factory.WSDLFactory; import javax.xml.namespace.QName; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.codehaus.xfire.XFireRuntimeException; import org.codehaus.xfire.client.Client; import org.codehaus.xfire.client.XFireProxy; import org.codehaus.xfire.client.XFireProxyFactory; import org.codehaus.xfire.service.Endpoint; import org.codehaus.xfire.service.Service; import org.codehaus.xfire.service.ServiceFactory; import org.codehaus.xfire.service.binding.ObjectServiceFactory; import org.codehaus.xfire.transport.Channel; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; /** * Factory bean to easily create XFire clients via Spring, if the service's Java * interface is available. Naming of properties is done to be the same as * {@link org.springframework.remoting.jaxrpc.JaxRpcPortProxyFactoryBean}. * <br> * The only mandatory properties to set before using this factory are: * {@link #setServiceClass(Class)} and {@link #setWsdlDocumentUrl(String)}. * <br> * By default this factory bean creates a service endpoint using an instance of * {@link org.codehaus.xfire.service.binding.ObjectServiceFactory}. Another one can * be configured using {@link #setServiceFactory(ServiceFactory)} * <br> * serviceName and namespaceUri can be derived from the content of the WSDL document * (if the document only contains one service), but unfortunately that does not (yet) * work if username/password needs to be supplied to get at the WSDL. * * @author Fried Hoeben */ public class XFireClientFactoryBean implements FactoryBean, InitializingBean { private static final Log LOG = LogFactory.getLog(XFireClientFactoryBean.class); // client proxy, in case lookupServiceOnStartup == true // proxy to the client proxy, otherwise private Object _serviceProxy; private Class _serviceClass; private ServiceFactory _serviceFactory = new ObjectServiceFactory(); private String _wsdlDocumentUrl; private String _serviceName; private String _namespaceUri; private String _username; private String _password; private String _url; private QName _endpointName; private Map _properties; private boolean _lookupServiceOnStartup = true; public Object getObject() throws Exception { return _serviceProxy; } public Class getObjectType() { return (_serviceProxy != null) ? _serviceProxy.getClass() : getServiceClass(); } public boolean isSingleton() { return true; } public void afterPropertiesSet() throws Exception { if (getServiceClass() == null) { throw new IllegalStateException("serviceInterface is required"); } if (getWsdlDocumentUrl() == null) { throw new IllegalStateException("wsdlDocumentUrl is required"); } ProxyInterceptor interceptor; if (getLookupServiceOnStartup()) { // create XFire client proxy directly _serviceProxy = createClient(); } else { // create proxy for XFire client proxy, this will create the XFire // client proxy // when it is first called interceptor = new ProxyInterceptor(); _serviceProxy = ProxyFactory.getProxy(getServiceClass(), interceptor); } } /** * @return the service factory that this factory will use */ public ServiceFactory getServiceFactory() { return _serviceFactory; } /** * Sets the service factory that will be used to create a client. If this method is never * called an instance of {@link org.codehaus.xfire.service.binding.ObjectServiceFactory} will * be used. * * @param factory * service factory this factory should use to create a client */ public void setServiceFactory(ServiceFactory factory) { if (factory == null) { throw new IllegalArgumentException("Can not set the service factory to null"); } _serviceFactory = factory; } /** * @return Returns the service's interface. */ public Class getServiceClass() { return _serviceClass; } /** * @param serviceClass * The interface implemented by the service called via the proxy. */ public void setServiceClass(Class serviceClass) { _serviceClass = serviceClass; } /** * @return Returns the URL where the WSDL to this service can be found. */ public String getWsdlDocumentUrl() { return _wsdlDocumentUrl; } /** * @param wsdlUrl * The URL where the WSDL to this service can be found. */ public void setWsdlDocumentUrl(String wsdlUrl) { _wsdlDocumentUrl = wsdlUrl.trim(); } /** * Gets the name of the service. If <code>null</code> the name will be * looked up from the WSDL, or generated from the interface name by XFire. * * @return Returns the serviceName. */ public String getServiceName() { return _serviceName; } /** * Sets the name of the service to access. If left <code>null</code> the * name will be looked up from the WSDL, or generated from the interface * name by XFire. * * @param serviceName * The service name to set. */ public void setServiceName(String serviceName) { _serviceName = serviceName; } /** * Gets the default namespace for the service. If <code>null</code> the * namespace will be looked up from the WSDL, or generated from the * interface package by XFire. * * @return Returns the namespace for the service. */ public String getNamespaceUri() { return _namespaceUri; } /** * Sets the default namespace for the service. If left <code>null</code> * the namespace will be looked up from the WSDL, or generated from the * interface package by XFire. * * @param namespace * The namespace to set. */ public void setNamespaceUri(String namespace) { _namespaceUri = namespace; } /** * Gets whether to look up the XFire service on startup. * * @return whether to look up the service on startup. */ public boolean getLookupServiceOnStartup() { return _lookupServiceOnStartup; } /** * Sets whether to look up the XFire service on startup. Default is * <code>true</code>. * <p> * Can be set to <code>false</code> to allow for late start of the target * server. In this case, the XFire service client proxy will be created on * first access. This does add some overhead (on each call) since * synchronization is used to ensure only one client proxy is ever created, * furthermore errors in the WSDL document URL are not detected until the * first call. * * @param lookupServiceOnStartup * whether to look up the service on startup. */ public void setLookupServiceOnStartup(boolean lookupServiceOnStartup) { _lookupServiceOnStartup = lookupServiceOnStartup; } /** * Gets the username for HTTP basic authentication. * * @return Returns the username to send. */ public String getUsername() { return _username; } /** * Sets the username for HTTP basic authentication. * * @param username * The username to set. */ public void setUsername(String username) { _username = username; } /** * Gets the password for HTTP basic authentication. * * @return Returns the password to send. */ public String getPassword() { return _password; } /** * Sets the password for HTTP basic authentication. * * @param password * The password to set. */ public void setPassword(String password) { _password = password; } /** * The properties that will be set on the Client. */ public Map getProperties() { return _properties; } /** * Set the properties for the Client. */ public void setProperties(Map properties) { this._properties = properties; } public QName getEndpoint() { return _endpointName; } /** * Set the name of the Endpoint/Port in the WSDL to use with the Client. * * @param name */ public void setEndpoint(QName name) { _endpointName = name; } public String getUrl() { return _url; } /** * Set the URL the Client is to invoke. If this is not supplied, the one from the * WSDL will be used instead. * @return */ public void setUrl(String _url) { this._url = _url; } /** * Creates actual XFire client proxy that this interceptor will delegate to. * * @throws Exception * if the client proxy could not be created. */ private Object createClient() throws Exception { Object serviceClient = makeClient(); Class interf = getServiceClass(); if (LOG.isDebugEnabled()) { LOG.debug("Created: " + toString()); } String username = getUsername(); if (username != null) { XFireProxy proxy = (XFireProxy) Proxy.getInvocationHandler(serviceClient); Client client = proxy.getClient(); client.setProperty(Channel.USERNAME, username); String password = getPassword(); client.setProperty(Channel.PASSWORD, password); if (LOG.isDebugEnabled()) { LOG.debug("Enabled HTTP basic authentication for: " + interf + " with username: " + username); } } return serviceClient; } /** * Performs actual creation of XFire client proxy. * * @return XFire proxy to the service * @throws java.net.MalformedURLException * if {@link XFireProxyFactory#create} threw one */ private Object makeClient() throws Exception { String serviceName = getServiceName(); String namespace = getNamespaceUri(); if ((serviceName == null || namespace == null) && _wsdlDocumentUrl != null) { // try to determine properties for name and namespace based on the // WSDL setWSDLProperties(); } Service serviceModel = getServiceFactory().create(getServiceClass(), serviceName, namespace, _properties); String serviceUrl = getServiceUrl(); if (_endpointName != null) { Endpoint ep = serviceModel.getEndpoint(_endpointName); if (ep == null) throw new XFireRuntimeException("Could not find endpoint with name " + _endpointName + " on service."); return new XFireProxyFactory().create(ep); } else return new XFireProxyFactory().create(serviceModel, serviceUrl); } private String getServiceUrl() { String serviceUrl = _url; if (serviceUrl == null) serviceUrl = getWsdlDocumentUrl().replaceAll("\\?wsdl", "").replaceAll("\\?WSDL", ""); return serviceUrl; } /** * Sets additional properties based on the WSDL Document configured. * Will lookup (and then set) ServiceName and NamespaceUri. */ protected void setWSDLProperties() { String wsdlUrl = getWsdlDocumentUrl(); try { Definition d = getWSDLDefinition(); if (LOG.isDebugEnabled()) { // if we are not able to parse the WSDL the exception will also // log the WSDL URL LOG.debug("Determining properties based on WSDL at: " + wsdlUrl); } Map services = d.getServices(); javax.wsdl.Service service = (javax.wsdl.Service) getOnlyElem(services); if (service != null) { if (getServiceName() == null) { setServiceName(service.getQName().getLocalPart()); } if (LOG.isDebugEnabled()) { LOG.debug("ServiceName is: " + getServiceName()); } if (getNamespaceUri() == null) { setNamespaceUri(service.getQName().getNamespaceURI()); } if (LOG.isDebugEnabled()) { LOG.debug("NamespaceUri is: " + getNamespaceUri()); } } else { LOG.warn("Unable to determine which service is meant. WSDL does not contain " + "exactly one service, but: " + services.size()); } } catch (Exception e) { throw new XFireRuntimeException("Unable to parse WSDL at: " + wsdlUrl, e); } } /** * Gets the Definition contained in the WSDL document (does not currently support reading * WSDL that is protected with authentication). * @return Definition describing the service(s) * @throws Exception if the definition could not be read */ protected Definition getWSDLDefinition() throws Exception { return WSDLFactory.newInstance().newWSDLReader().readWSDL(getWsdlDocumentUrl()); } /** * Returns the only value in a Map * * @param map * @return the only value in the map, if it contained exactly 1 key/value * pair <br> * <code>null</code>, otherwise <br> */ private Object getOnlyElem(Map map) { if (map.size() == 1) { Set keySet = map.keySet(); Iterator i = keySet.iterator(); return map.get(i.next()); } else { return null; } } public String toString() { StringBuffer builder = new StringBuffer(); builder.append("XFire client proxy for: "); builder.append(getServiceClass()); builder.append(" at: "); builder.append(getServiceUrl()); return builder.toString(); } /** * Interceptor for (i.e. proxy to) the actual XFire client proxy. This class * performs lazy initialization of the XFire client proxy, which can come in * handy if the service is not guaranteed to be available by the time the * factory bean is used to created an instance, but will be available by the * time the client is actually called. * <p> * This does add some overhead since synchronization is used to ensure only * one client is ever allocated. Furthermore if there is a problem accessing * the service it is not detected until the first call. */ private class ProxyInterceptor implements MethodInterceptor { // actual XFire client proxy private Object _serviceClient; public Object invoke(MethodInvocation invocation) throws Throwable { if (_serviceClient == null) { if (AopUtils.isToStringMethod(invocation.getMethod())) { // do not lookup service for toString() return "Un-initialized " + XFireClientFactoryBean.this.toString(); } } Method method = invocation.getMethod(); Object[] args = invocation.getArguments(); Object client = getClient(); try { return method.invoke(client, args); } catch (InvocationTargetException e) { String callTarget = getServiceUrl() + " arguments: " + Arrays.toString(args); Throwable targetException = e.getTargetException(); if (targetException instanceof XFireRuntimeException) { // convert XFire runtime exception to one detailing call // made XFireRuntimeException xfRt = (XFireRuntimeException) targetException; Throwable cause = xfRt.getCause(); throw new XFireRuntimeException("Exception while calling: " + callTarget, cause); } throw targetException; } } /** * Gets the actual client proxy. This implementation ensures only one * client proxy is ever created, even in multi-threaded situations * * @return service client proxy * @throws MalformedURLException */ private synchronized Object getClient() throws Exception { if (_serviceClient == null) { _serviceClient = createClient(); } return _serviceClient; } } }
xfire-spring/src/main/org/codehaus/xfire/spring/remoting/XFireClientFactoryBean.java
package org.codehaus.xfire.spring.remoting; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.net.MalformedURLException; import java.util.Arrays; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.wsdl.Definition; import javax.wsdl.factory.WSDLFactory; import javax.xml.namespace.QName; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.codehaus.xfire.XFireRuntimeException; import org.codehaus.xfire.client.Client; import org.codehaus.xfire.client.XFireProxy; import org.codehaus.xfire.client.XFireProxyFactory; import org.codehaus.xfire.service.Endpoint; import org.codehaus.xfire.service.Service; import org.codehaus.xfire.service.ServiceFactory; import org.codehaus.xfire.service.binding.ObjectServiceFactory; import org.codehaus.xfire.transport.Channel; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; /** * Factory bean to easily create XFire clients via Spring, if the service's Java * interface is available. Naming of properties is done to be the same as * {@link org.springframework.remoting.jaxrpc.JaxRpcPortProxyFactoryBean}. * <br> * The only mandatory properties to set before using this factory are: * {@link #setServiceClass(Class)} and {@link #setWsdlDocumentUrl(String)}. * <br> * By default this factory bean creates a service endpoint using an instance of * {@link org.codehaus.xfire.service.binding.ObjectServiceFactory}. Another one can * be configured using {@link #setServiceFactory(ServiceFactory)} * <br> * serviceName and namespaceUri can be derived from the content of the WSDL document * (if the document only contains one service), but unfortunately that does not (yet) * work if username/password needs to be supplied to get at the WSDL. * * @author Fried Hoeben */ public class XFireClientFactoryBean implements FactoryBean, InitializingBean { private static final Log LOG = LogFactory.getLog(XFireClientFactoryBean.class); // client proxy, in case lookupServiceOnStartup == true // proxy to the client proxy, otherwise private Object _serviceProxy; private Class _serviceClass; private ServiceFactory _serviceFactory = new ObjectServiceFactory(); private String _wsdlDocumentUrl; private String _serviceName; private String _namespaceUri; private String _username; private String _password; private String _url; private QName _endpointName; private Map _properties; private boolean _lookupServiceOnStartup = true; public Object getObject() throws Exception { return _serviceProxy; } public Class getObjectType() { return (_serviceProxy != null) ? _serviceProxy.getClass() : getServiceClass(); } public boolean isSingleton() { return true; } public void afterPropertiesSet() throws Exception { if (getServiceClass() == null) { throw new IllegalStateException("serviceInterface is required"); } if (getWsdlDocumentUrl() == null) { throw new IllegalStateException("wsdlDocumentUrl is required"); } ProxyInterceptor interceptor; if (getLookupServiceOnStartup()) { // create XFire client proxy directly _serviceProxy = createClient(); } else { // create proxy for XFire client proxy, this will create the XFire // client proxy // when it is first called interceptor = new ProxyInterceptor(); _serviceProxy = ProxyFactory.getProxy(getServiceClass(), interceptor); } } /** * @return the service factory that this factory will use */ public ServiceFactory getServiceFactory() { return _serviceFactory; } /** * Sets the service factory that will be used to create a client. If this method is never * called an instance of {@link org.codehaus.xfire.service.binding.ObjectServiceFactory} will * be used. * * @param factory * service factory this factory should use to create a client */ public void setServiceFactory(ServiceFactory factory) { if (factory == null) { throw new IllegalArgumentException("Can not set the service factory to null"); } _serviceFactory = factory; } /** * @return Returns the service's interface. */ public Class getServiceClass() { return _serviceClass; } /** * @param serviceClass * The interface implemented by the service called via the proxy. */ public void setServiceClass(Class serviceClass) { _serviceClass = serviceClass; } /** * @return Returns the URL where the WSDL to this service can be found. */ public String getWsdlDocumentUrl() { return _wsdlDocumentUrl; } /** * @param wsdlUrl * The URL where the WSDL to this service can be found. */ public void setWsdlDocumentUrl(String wsdlUrl) { _wsdlDocumentUrl = wsdlUrl; } /** * Gets the name of the service. If <code>null</code> the name will be * looked up from the WSDL, or generated from the interface name by XFire. * * @return Returns the serviceName. */ public String getServiceName() { return _serviceName; } /** * Sets the name of the service to access. If left <code>null</code> the * name will be looked up from the WSDL, or generated from the interface * name by XFire. * * @param serviceName * The service name to set. */ public void setServiceName(String serviceName) { _serviceName = serviceName; } /** * Gets the default namespace for the service. If <code>null</code> the * namespace will be looked up from the WSDL, or generated from the * interface package by XFire. * * @return Returns the namespace for the service. */ public String getNamespaceUri() { return _namespaceUri; } /** * Sets the default namespace for the service. If left <code>null</code> * the namespace will be looked up from the WSDL, or generated from the * interface package by XFire. * * @param namespace * The namespace to set. */ public void setNamespaceUri(String namespace) { _namespaceUri = namespace; } /** * Gets whether to look up the XFire service on startup. * * @return whether to look up the service on startup. */ public boolean getLookupServiceOnStartup() { return _lookupServiceOnStartup; } /** * Sets whether to look up the XFire service on startup. Default is * <code>true</code>. * <p> * Can be set to <code>false</code> to allow for late start of the target * server. In this case, the XFire service client proxy will be created on * first access. This does add some overhead (on each call) since * synchronization is used to ensure only one client proxy is ever created, * furthermore errors in the WSDL document URL are not detected until the * first call. * * @param lookupServiceOnStartup * whether to look up the service on startup. */ public void setLookupServiceOnStartup(boolean lookupServiceOnStartup) { _lookupServiceOnStartup = lookupServiceOnStartup; } /** * Gets the username for HTTP basic authentication. * * @return Returns the username to send. */ public String getUsername() { return _username; } /** * Sets the username for HTTP basic authentication. * * @param username * The username to set. */ public void setUsername(String username) { _username = username; } /** * Gets the password for HTTP basic authentication. * * @return Returns the password to send. */ public String getPassword() { return _password; } /** * Sets the password for HTTP basic authentication. * * @param password * The password to set. */ public void setPassword(String password) { _password = password; } /** * The properties that will be set on the Client. */ public Map getProperties() { return _properties; } /** * Set the properties for the Client. */ public void setProperties(Map properties) { this._properties = properties; } public QName getEndpoint() { return _endpointName; } /** * Set the name of the Endpoint/Port in the WSDL to use with the Client. * * @param name */ public void setEndpoint(QName name) { _endpointName = name; } public String getUrl() { return _url; } /** * Set the URL the Client is to invoke. If this is not supplied, the one from the * WSDL will be used instead. * @return */ public void setUrl(String _url) { this._url = _url; } /** * Creates actual XFire client proxy that this interceptor will delegate to. * * @throws Exception * if the client proxy could not be created. */ private Object createClient() throws Exception { Object serviceClient = makeClient(); Class interf = getServiceClass(); if (LOG.isDebugEnabled()) { LOG.debug("Created: " + toString()); } String username = getUsername(); if (username != null) { XFireProxy proxy = (XFireProxy) Proxy.getInvocationHandler(serviceClient); Client client = proxy.getClient(); client.setProperty(Channel.USERNAME, username); String password = getPassword(); client.setProperty(Channel.PASSWORD, password); if (LOG.isDebugEnabled()) { LOG.debug("Enabled HTTP basic authentication for: " + interf + " with username: " + username); } } return serviceClient; } /** * Performs actual creation of XFire client proxy. * * @return XFire proxy to the service * @throws java.net.MalformedURLException * if {@link XFireProxyFactory#create} threw one */ private Object makeClient() throws Exception { String serviceName = getServiceName(); String namespace = getNamespaceUri(); if ((serviceName == null || namespace == null) && _wsdlDocumentUrl != null) { // try to determine properties for name and namespace based on the // WSDL setWSDLProperties(); } Service serviceModel = getServiceFactory().create(getServiceClass(), serviceName, namespace, _properties); String serviceUrl = getServiceUrl(); if (_endpointName != null) { Endpoint ep = serviceModel.getEndpoint(_endpointName); if (ep == null) throw new XFireRuntimeException("Could not find endpoint with name " + _endpointName + " on service."); return new XFireProxyFactory().create(ep); } else return new XFireProxyFactory().create(serviceModel, serviceUrl); } private String getServiceUrl() { String serviceUrl = _url; if (serviceUrl == null) serviceUrl = getWsdlDocumentUrl().replaceAll("\\?wsdl", "").replaceAll("\\?WSDL", ""); return serviceUrl; } /** * Sets additional properties based on the WSDL Document configured. * Will lookup (and then set) ServiceName and NamespaceUri. */ protected void setWSDLProperties() { String wsdlUrl = getWsdlDocumentUrl(); try { Definition d = getWSDLDefinition(); if (LOG.isDebugEnabled()) { // if we are not able to parse the WSDL the exception will also // log the WSDL URL LOG.debug("Determining properties based on WSDL at: " + wsdlUrl); } Map services = d.getServices(); javax.wsdl.Service service = (javax.wsdl.Service) getOnlyElem(services); if (service != null) { if (getServiceName() == null) { setServiceName(service.getQName().getLocalPart()); } if (LOG.isDebugEnabled()) { LOG.debug("ServiceName is: " + getServiceName()); } if (getNamespaceUri() == null) { setNamespaceUri(service.getQName().getNamespaceURI()); } if (LOG.isDebugEnabled()) { LOG.debug("NamespaceUri is: " + getNamespaceUri()); } } else { LOG.warn("Unable to determine which service is meant. WSDL does not contain " + "exactly one service, but: " + services.size()); } } catch (Exception e) { throw new XFireRuntimeException("Unable to parse WSDL at: " + wsdlUrl, e); } } /** * Gets the Definition contained in the WSDL document (does not currently support reading * WSDL that is protected with authentication). * @return Definition describing the service(s) * @throws Exception if the definition could not be read */ protected Definition getWSDLDefinition() throws Exception { return WSDLFactory.newInstance().newWSDLReader().readWSDL(getWsdlDocumentUrl()); } /** * Returns the only value in a Map * * @param map * @return the only value in the map, if it contained exactly 1 key/value * pair <br> * <code>null</code>, otherwise <br> */ private Object getOnlyElem(Map map) { if (map.size() == 1) { Set keySet = map.keySet(); Iterator i = keySet.iterator(); return map.get(i.next()); } else { return null; } } public String toString() { StringBuffer builder = new StringBuffer(); builder.append("XFire client proxy for: "); builder.append(getServiceClass()); builder.append(" at: "); builder.append(getServiceUrl()); return builder.toString(); } /** * Interceptor for (i.e. proxy to) the actual XFire client proxy. This class * performs lazy initialization of the XFire client proxy, which can come in * handy if the service is not guaranteed to be available by the time the * factory bean is used to created an instance, but will be available by the * time the client is actually called. * <p> * This does add some overhead since synchronization is used to ensure only * one client is ever allocated. Furthermore if there is a problem accessing * the service it is not detected until the first call. */ private class ProxyInterceptor implements MethodInterceptor { // actual XFire client proxy private Object _serviceClient; public Object invoke(MethodInvocation invocation) throws Throwable { if (_serviceClient == null) { if (AopUtils.isToStringMethod(invocation.getMethod())) { // do not lookup service for toString() return "Un-initialized " + XFireClientFactoryBean.this.toString(); } } Method method = invocation.getMethod(); Object[] args = invocation.getArguments(); Object client = getClient(); try { return method.invoke(client, args); } catch (InvocationTargetException e) { String callTarget = getServiceUrl() + " arguments: " + Arrays.toString(args); Throwable targetException = e.getTargetException(); if (targetException instanceof XFireRuntimeException) { // convert XFire runtime exception to one detailing call // made XFireRuntimeException xfRt = (XFireRuntimeException) targetException; Throwable cause = xfRt.getCause(); throw new XFireRuntimeException("Exception while calling: " + callTarget, cause); } throw targetException; } } /** * Gets the actual client proxy. This implementation ensures only one * client proxy is ever created, even in multi-threaded situations * * @return service client proxy * @throws MalformedURLException */ private synchronized Object getClient() throws Exception { if (_serviceClient == null) { _serviceClient = createClient(); } return _serviceClient; } } }
XFIRE-419 - Add a trim() to XFireClientFactoryBean for the wsdl location as it was causing problems for some users. git-svn-id: 9326b53cbc4a8f4c3d02979b62b178127d5150fe@1601 c7d0bf07-ec0d-0410-b2cc-d48fa9be22ba
xfire-spring/src/main/org/codehaus/xfire/spring/remoting/XFireClientFactoryBean.java
XFIRE-419 - Add a trim() to XFireClientFactoryBean for the wsdl location as it was causing problems for some users.
<ide><path>fire-spring/src/main/org/codehaus/xfire/spring/remoting/XFireClientFactoryBean.java <ide> */ <ide> public void setWsdlDocumentUrl(String wsdlUrl) <ide> { <del> _wsdlDocumentUrl = wsdlUrl; <add> _wsdlDocumentUrl = wsdlUrl.trim(); <ide> } <ide> <ide> /**
JavaScript
apache-2.0
7fb6cd1bc054599dc4f127905f1eacb5f134dec1
0
appcelerator/titanium_mobile_tizen,appcelerator/titanium_mobile_tizen,appcelerator/titanium_mobile_tizen,appcelerator/titanium_mobile_tizen,appcelerator/titanium_mobile_tizen,appcelerator/titanium_mobile_tizen
/* * Appcelerator Titanium Mobile * Copyright (c) 2011-2012 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ // This test depends on call history already being present. If call history is empty, the test will // still succeed, but will not test much. Currently it is not possible to add calls programmatically. module.exports = new function() { var finish, valueOf, reportError, callhistoryObj, tizenObj; this.init = function(testUtils) { finish = testUtils.finish; valueOf = testUtils.valueOf; reportError = testUtils.reportError; callhistoryObj = require('Ti/Tizen/Callhistory'); tizenObj = require('Ti/Tizen'); } this.name = 'call'; this.tests = [ {name: 'call_history'}, {name: 'remove'}, {name: 'remove_batch'}, {name: 'remove_all'}, {name: 'listeners'} ] // Search for history of call this.call_history = function(testRun) { // Type of call var tFilter = tizenObj.createAttributeFilter({ attributeName: 'type', matchFlag: tizenObj.FILTER_MATCH_FLAG_EXACTLY, matchValue: 'TEL' }), // Sort output sortMode = tizenObj.createSortMode({ attributeName: 'startTime', order: tizenObj.SORT_MODE_ORDER_DESC }), // From number numberFilter = tizenObj.createAttributeFilter({ attributeName: 'remoteParties.remoteParty', matchFlag: tizenObj.FILTER_MATCH_FLAG_EXACTLY, matchValue: '12345678' }), // Add filters iFilter = tizenObj.createCompositeFilter({ type: tizenObj.COMPOSITE_FILTER_TYPE_INTERSECTION, filters: [ numberFilter, tFilter ] }); valueOf(testRun, callhistoryObj).shouldBeObject(); valueOf(testRun, tFilter).shouldBeObject(); valueOf(testRun, sortMode).shouldBeObject(); valueOf(testRun, numberFilter).shouldBeObject(); valueOf(testRun, iFilter).shouldBeObject(); function onSuccess(results) { if (results.length <= 0) { reportError(testRun, 'This test requires at least one call in the phone\'s call history. Please make several calls and restart the test.'); finish(testRun); } valueOf(testRun, results).shouldNotBeUndefined(); valueOf(testRun, results).shouldBeObject(); for (var i in results) { valueOf(testRun, results[i].uid).shouldBeString(); valueOf(testRun, results[i].remoteParties).shouldBeArray(); valueOf(testRun, results[i].startTime).shouldBeObject(); valueOf(testRun, results[i].direction).shouldBeString(); valueOf(testRun, results[i].type).shouldBeString(); valueOf(testRun, results[i].toString()).shouldBe('[object TizenCallhistoryCallHistoryEntry]'); } } function onError(error) { reportError(testRun, 'The following error occurred: ' + error.message); } // Find call history valueOf(testRun, function() { callhistoryObj.find(onSuccess, onError, tFilter, sortMode); }).shouldNotThrowException(); setTimeout( function() { finish(testRun); }, 10 ); } // Remove: deletes a call history entries. this.remove = function(testRun) { function onSuccess(results) { valueOf(testRun, results).shouldNotBeUndefined(); valueOf(testRun, results).shouldBeObject(); if (results.length > 0) { // Delete call from call history valueOf(testRun, function() { callhistoryObj.remove(results[0]); }).shouldNotThrowException(); } else { reportError(testRun, 'This test requires at least one call in the phone\'s call history. Please make several calls and restart the test.'); finish(testRun); } } function onError(error) { reportError(testRun, 'The following error occurred: ' + error.message); } valueOf(testRun, callhistoryObj).shouldBeObject(); // Search for call history valueOf(testRun, function() { callhistoryObj.find(onSuccess, onError); }).shouldNotThrowException(); setTimeout( function() { finish(testRun); }, 10 ); } // Deletes a list of call history entries. this.remove_batch = function(testRun) { function onSuccess(results) { valueOf(testRun, results).shouldBeObject(); // delete found history valueOf(testRun, function() { callhistoryObj.removeBatch(results, null, onError); }).shouldNotThrowException(); } function onError(error) { reportError(testRun, 'This test requires at least one call in the phone\'s call history. Please make several calls and restart the test.'); reportError(testRun, 'The following error occurred: ' + error.message); finish(testRun); } valueOf(testRun, callhistoryObj).shouldBeObject(); // Search for call history valueOf(testRun, function() { callhistoryObj.find(onSuccess, onError); }).shouldNotThrowException(); // Give some time for execution setTimeout( function() { finish(testRun); }, 10 ); } // Deletes all call history. this.remove_all = function(testRun) { function onError(error) { reportError(testRun, 'The following error occurred: ' + error.message); } valueOf(testRun, callhistoryObj).shouldBeObject(); // Delete all call history valueOf(testRun, function() { callhistoryObj.removeAll(null, onError); }).shouldNotThrowException(); // Give some time for execution setTimeout( function() { finish(testRun); }, 10 ); } // Observing of callHistory changes. this.listeners = function(testRun) { var handle, onListenerCB = { onadded: function(newItems) { valueOf(testRun, newItems).shouldBeObject(); }, onchanged: function(changedItems) { valueOf(testRun, changedItems).shouldBeObject(); } }; valueOf(testRun, callhistoryObj).shouldBeObject(); try { // Add new listener valueOf(testRun, function() { handle = callhistoryObj.addChangeListener(onListenerCB); }).shouldNotThrowException(); valueOf(testRun, handle).shouldNotBeNull(); valueOf(testRun, handle).shouldBeNumber(); // Remove added listener valueOf(testRun, function() { callhistoryObj.removeChangeListener(handle); }).shouldNotThrowException(); } catch (error) { reportError(testRun, 'The following error occurred: ' + error.message); } // Give some time for execution setTimeout( function() { finish(testRun); }, 10 ); } }
tests/anvil/configSet/Resources/suites/tizen/call.js
/* * Appcelerator Titanium Mobile * Copyright (c) 2011-2012 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ // This test depends on call history already being present. If call history is empty, the test will // still succeed, but will not test much. Currently it is not possible to add calls programmatically. module.exports = new function() { var finish, valueOf, reportError; this.init = function(testUtils) { finish = testUtils.finish; valueOf = testUtils.valueOf; reportError = testUtils.reportError; } this.name = 'call'; this.tests = [ {name: 'call_history'}, {name: 'remove'}, {name: 'remove_batch'}, {name: 'remove_all'}, // {name: 'delete_recording'}, {name: 'listeners'} ] // Search for history of call this.call_history = function(testRun) { // Type of call var tFilter = Ti.Tizen.createAttributeFilter({ attributeName: 'type', matchFlag: 'EXACTLY', matchValue: 'TEL' }), // Sort output sortMode = Ti.Tizen.createSortMode({ attributeName: 'startTime', order: 'DESC' }), // From number numberFilter = Ti.Tizen.createAttributeFilter({ attributeName: 'remoteParties.remoteParty', matchFlag: 'EXACTLY', matchValue: '12345678' }), // Add filters iFilter = Ti.Tizen.createCompositeFilter({ type: 'INTERSECTION', filters: [ numberFilter, tFilter ] }), tizenHistory = Ti.Tizen.Callhistory; valueOf(testRun, tizenHistory).shouldBeObject(); valueOf(testRun, tFilter).shouldBeObject(); valueOf(testRun, sortMode).shouldBeObject(); valueOf(testRun, numberFilter).shouldBeObject(); valueOf(testRun, iFilter).shouldBeObject(); function onSuccess(results) { if(results.length <= 0){ reportError(testRun, "This test requires at least one call in the phone's call history. Please make several calls and restart the test."); finish(testRun); } valueOf(testRun, results).shouldNotBeUndefined(); valueOf(testRun, results).shouldBeObject(); for (var i in results) { valueOf(testRun, results[i].uid).shouldBeString(); valueOf(testRun, results[i].remoteParties).shouldBeArray(); valueOf(testRun, results[i].startTime).shouldBeObject(); valueOf(testRun, results[i].direction).shouldBeString(); valueOf(testRun, results[i].type).shouldBeString(); valueOf(testRun, results[i].toString()).shouldBe('[object TiTizenCallhistoryCallHistoryEntry]'); } } function onError(error) { reportError(testRun, 'The following error occurred: ' + error.message); } // Find call history valueOf(testRun, function() { tizenHistory.find(onSuccess, onError, tFilter, sortMode);}).shouldNotThrowException(); setTimeout( function() { finish(testRun); }, 10 ); } // Remove: deletes a call history entries. this.remove = function(testRun) { var tizenHistory = Ti.Tizen.Callhistory; function onSuccess(results) { valueOf(testRun, results).shouldNotBeUndefined(); valueOf(testRun, results).shouldBeObject(); if (results.length > 0) { // Delete call from call history valueOf(testRun, function() { tizenHistory.remove(results[0]); }).shouldNotThrowException(); }else{ reportError(testRun, "This test requires at least one call in the phone's call history. Please make several calls and restart the test."); finish(testRun); } } function onError(error) { reportError(testRun, 'The following error occurred: ' + error.message); } valueOf(testRun, tizenHistory).shouldBeObject(); // Search for call history valueOf(testRun, function() { tizenHistory.find(onSuccess, onError); }).shouldNotThrowException(); setTimeout( function() { finish(testRun); }, 10 ); } // Deletes a list of call history entries. this.remove_batch = function(testRun) { var tizenHistory = Ti.Tizen.Callhistory; function onSuccess(results) { valueOf(testRun, results).shouldBeObject(); // delete found history valueOf(testRun, function() { tizenHistory.removeBatch(results, null, onError); }).shouldNotThrowException(); } function onError(error) { reportError(testRun, "This test requires at least one call in the phone's call history. Please make several calls and restart the test."); reportError(testRun, 'The following error occurred: ' + error.message); finish(testRun); } valueOf(testRun, tizenHistory).shouldBeObject(); // Search for call history valueOf(testRun, function() { tizenHistory.find(onSuccess, onError); }).shouldNotThrowException(); // Give some time for execution setTimeout( function() { finish(testRun); }, 10 ); } // Deletes all call history. this.remove_all = function(testRun) { function onError(error) { reportError(testRun, 'The following error occurred: ' + error.message); } valueOf(testRun, Ti.Tizen.Callhistory).shouldBeObject(); // Delete all call history valueOf(testRun, function() { Ti.Tizen.Callhistory.removeAll(null, onError); }).shouldNotThrowException(); // Give some time for execution setTimeout( function() { finish(testRun); }, 10 ); } // // Deletes the recorded media associated to the call history item. // this.delete_recording = function(testRun) { // var tizenHistory = Ti.Tizen.Call.history, // // Filter for call.video // filter = Ti.Tizen.createAttributeFilter({ // attributeName: 'tags', // matchFlag: 'EXACTLY', // matchValue: 'call.video' // }); // function onSuccess(results) { // valueOf(testRun, results).shouldBeObject(); // (results.length > 0) && valueOf(testRun, function() { tizenHistory.deleteRecording(results[0], null, onError); }).shouldNotThrowException(); // } // function onError(error) { // reportError(testRun, 'The following error occurred: ' + error.message); // } // valueOf(testRun, tizenHistory).shouldBeObject(); // valueOf(testRun, filter).shouldBeObject(); // valueOf(testRun, function() { tizenHistory.find(onSuccess, onError, filter); }).shouldNotThrowException(); // // Give some time for execution // setTimeout( // function() { // finish(testRun); // }, // 10 // ); // } // Observing of callHistory changes. this.listeners = function(testRun) { var handle, tizenHistory = Ti.Tizen.Callhistory, onListenerCB = { onadded: function(newItems) { valueOf(testRun, newItems).shouldBeObject(); }, onchanged: function(changedItems) { valueOf(testRun, changedItems).shouldBeObject(); } }; valueOf(testRun, tizenHistory).shouldBeObject(); try { // Add new listener valueOf(testRun, function() { handle = tizenHistory.addChangeListener(onListenerCB); }).shouldNotThrowException(); valueOf(testRun, handle).shouldNotBeNull(); valueOf(testRun, handle).shouldBeNumber(); // Remove added listener valueOf(testRun, function() { tizenHistory.removeChangeListener(handle); }).shouldNotThrowException(); } catch (error) { reportError(testRun, 'The following error occurred: ' + error.message); } // Give some time for execution setTimeout( function() { finish(testRun); }, 10 ); } }
Fix anvil tests for callhistory according to new wrapper
tests/anvil/configSet/Resources/suites/tizen/call.js
Fix anvil tests for callhistory according to new wrapper
<ide><path>ests/anvil/configSet/Resources/suites/tizen/call.js <ide> module.exports = new function() { <ide> var finish, <ide> valueOf, <del> reportError; <add> reportError, <add> callhistoryObj, <add> tizenObj; <ide> <ide> this.init = function(testUtils) { <ide> finish = testUtils.finish; <ide> valueOf = testUtils.valueOf; <ide> reportError = testUtils.reportError; <add> callhistoryObj = require('Ti/Tizen/Callhistory'); <add> tizenObj = require('Ti/Tizen'); <ide> } <ide> <ide> this.name = 'call'; <ide> {name: 'remove'}, <ide> {name: 'remove_batch'}, <ide> {name: 'remove_all'}, <del> // {name: 'delete_recording'}, <ide> {name: 'listeners'} <ide> ] <ide> <ide> // Search for history of call <ide> this.call_history = function(testRun) { <ide> // Type of call <del> var tFilter = Ti.Tizen.createAttributeFilter({ <add> var tFilter = tizenObj.createAttributeFilter({ <ide> attributeName: 'type', <del> matchFlag: 'EXACTLY', <add> matchFlag: tizenObj.FILTER_MATCH_FLAG_EXACTLY, <ide> matchValue: 'TEL' <ide> }), <ide> // Sort output <del> sortMode = Ti.Tizen.createSortMode({ <add> sortMode = tizenObj.createSortMode({ <ide> attributeName: 'startTime', <del> order: 'DESC' <add> order: tizenObj.SORT_MODE_ORDER_DESC <ide> }), <ide> // From number <del> numberFilter = Ti.Tizen.createAttributeFilter({ <add> numberFilter = tizenObj.createAttributeFilter({ <ide> attributeName: 'remoteParties.remoteParty', <del> matchFlag: 'EXACTLY', <add> matchFlag: tizenObj.FILTER_MATCH_FLAG_EXACTLY, <ide> matchValue: '12345678' <ide> }), <ide> // Add filters <del> iFilter = Ti.Tizen.createCompositeFilter({ <del> type: 'INTERSECTION', <add> iFilter = tizenObj.createCompositeFilter({ <add> type: tizenObj.COMPOSITE_FILTER_TYPE_INTERSECTION, <ide> filters: [ <ide> numberFilter, <ide> tFilter <ide> ] <del> }), <del> tizenHistory = Ti.Tizen.Callhistory; <del> <del> valueOf(testRun, tizenHistory).shouldBeObject(); <add> }); <add> <add> valueOf(testRun, callhistoryObj).shouldBeObject(); <ide> valueOf(testRun, tFilter).shouldBeObject(); <ide> valueOf(testRun, sortMode).shouldBeObject(); <ide> valueOf(testRun, numberFilter).shouldBeObject(); <ide> valueOf(testRun, iFilter).shouldBeObject(); <ide> <ide> function onSuccess(results) { <del> if(results.length <= 0){ <del> reportError(testRun, "This test requires at least one call in the phone's call history. Please make several calls and restart the test."); <add> if (results.length <= 0) { <add> reportError(testRun, 'This test requires at least one call in the phone\'s call history. Please make several calls and restart the test.'); <ide> finish(testRun); <ide> } <ide> valueOf(testRun, results).shouldNotBeUndefined(); <ide> valueOf(testRun, results[i].startTime).shouldBeObject(); <ide> valueOf(testRun, results[i].direction).shouldBeString(); <ide> valueOf(testRun, results[i].type).shouldBeString(); <del> valueOf(testRun, results[i].toString()).shouldBe('[object TiTizenCallhistoryCallHistoryEntry]'); <add> valueOf(testRun, results[i].toString()).shouldBe('[object TizenCallhistoryCallHistoryEntry]'); <ide> } <ide> } <ide> <ide> } <ide> <ide> // Find call history <del> valueOf(testRun, function() { tizenHistory.find(onSuccess, onError, tFilter, sortMode);}).shouldNotThrowException(); <add> valueOf(testRun, function() { callhistoryObj.find(onSuccess, onError, tFilter, sortMode); }).shouldNotThrowException(); <ide> <ide> setTimeout( <ide> function() { <ide> <ide> // Remove: deletes a call history entries. <ide> this.remove = function(testRun) { <del> var tizenHistory = Ti.Tizen.Callhistory; <del> <ide> function onSuccess(results) { <ide> valueOf(testRun, results).shouldNotBeUndefined(); <ide> valueOf(testRun, results).shouldBeObject(); <ide> <ide> if (results.length > 0) { <ide> // Delete call from call history <del> valueOf(testRun, function() { tizenHistory.remove(results[0]); }).shouldNotThrowException(); <del> }else{ <del> reportError(testRun, "This test requires at least one call in the phone's call history. Please make several calls and restart the test."); <add> valueOf(testRun, function() { callhistoryObj.remove(results[0]); }).shouldNotThrowException(); <add> } else { <add> reportError(testRun, 'This test requires at least one call in the phone\'s call history. Please make several calls and restart the test.'); <ide> finish(testRun); <ide> } <ide> } <ide> reportError(testRun, 'The following error occurred: ' + error.message); <ide> } <ide> <del> valueOf(testRun, tizenHistory).shouldBeObject(); <add> valueOf(testRun, callhistoryObj).shouldBeObject(); <ide> <ide> // Search for call history <del> valueOf(testRun, function() { tizenHistory.find(onSuccess, onError); }).shouldNotThrowException(); <add> valueOf(testRun, function() { callhistoryObj.find(onSuccess, onError); }).shouldNotThrowException(); <ide> <ide> setTimeout( <ide> function() { <ide> <ide> // Deletes a list of call history entries. <ide> this.remove_batch = function(testRun) { <del> var tizenHistory = Ti.Tizen.Callhistory; <del> <ide> function onSuccess(results) { <ide> valueOf(testRun, results).shouldBeObject(); <ide> // delete found history <del> valueOf(testRun, function() { tizenHistory.removeBatch(results, null, onError); }).shouldNotThrowException(); <del> } <del> <del> function onError(error) { <del> reportError(testRun, "This test requires at least one call in the phone's call history. Please make several calls and restart the test."); <add> valueOf(testRun, function() { callhistoryObj.removeBatch(results, null, onError); }).shouldNotThrowException(); <add> } <add> <add> function onError(error) { <add> reportError(testRun, 'This test requires at least one call in the phone\'s call history. Please make several calls and restart the test.'); <ide> reportError(testRun, 'The following error occurred: ' + error.message); <ide> finish(testRun); <ide> } <ide> <del> valueOf(testRun, tizenHistory).shouldBeObject(); <add> valueOf(testRun, callhistoryObj).shouldBeObject(); <ide> <ide> // Search for call history <del> valueOf(testRun, function() { tizenHistory.find(onSuccess, onError); }).shouldNotThrowException(); <del> <add> valueOf(testRun, function() { callhistoryObj.find(onSuccess, onError); }).shouldNotThrowException(); <add> <ide> // Give some time for execution <ide> setTimeout( <ide> function() { <ide> reportError(testRun, 'The following error occurred: ' + error.message); <ide> } <ide> <del> valueOf(testRun, Ti.Tizen.Callhistory).shouldBeObject(); <add> valueOf(testRun, callhistoryObj).shouldBeObject(); <ide> <ide> // Delete all call history <del> valueOf(testRun, function() { Ti.Tizen.Callhistory.removeAll(null, onError); }).shouldNotThrowException(); <del> <add> valueOf(testRun, function() { callhistoryObj.removeAll(null, onError); }).shouldNotThrowException(); <add> <ide> // Give some time for execution <ide> setTimeout( <ide> function() { <ide> 10 <ide> ); <ide> } <del> <del> // // Deletes the recorded media associated to the call history item. <del> // this.delete_recording = function(testRun) { <del> // var tizenHistory = Ti.Tizen.Call.history, <del> // // Filter for call.video <del> // filter = Ti.Tizen.createAttributeFilter({ <del> // attributeName: 'tags', <del> // matchFlag: 'EXACTLY', <del> // matchValue: 'call.video' <del> // }); <del> <del> // function onSuccess(results) { <del> // valueOf(testRun, results).shouldBeObject(); <del> <del> // (results.length > 0) && valueOf(testRun, function() { tizenHistory.deleteRecording(results[0], null, onError); }).shouldNotThrowException(); <del> // } <del> <del> // function onError(error) { <del> // reportError(testRun, 'The following error occurred: ' + error.message); <del> // } <del> <del> // valueOf(testRun, tizenHistory).shouldBeObject(); <del> // valueOf(testRun, filter).shouldBeObject(); <del> // valueOf(testRun, function() { tizenHistory.find(onSuccess, onError, filter); }).shouldNotThrowException(); <del> <del> // // Give some time for execution <del> // setTimeout( <del> // function() { <del> // finish(testRun); <del> // }, <del> // 10 <del> // ); <del> // } <ide> <ide> // Observing of callHistory changes. <ide> this.listeners = function(testRun) { <ide> var handle, <del> tizenHistory = Ti.Tizen.Callhistory, <ide> onListenerCB = { <ide> onadded: function(newItems) { <ide> valueOf(testRun, newItems).shouldBeObject(); <ide> } <ide> }; <ide> <del> valueOf(testRun, tizenHistory).shouldBeObject(); <add> valueOf(testRun, callhistoryObj).shouldBeObject(); <ide> <ide> try { <ide> // Add new listener <del> valueOf(testRun, function() { handle = tizenHistory.addChangeListener(onListenerCB); }).shouldNotThrowException(); <add> valueOf(testRun, function() { handle = callhistoryObj.addChangeListener(onListenerCB); }).shouldNotThrowException(); <ide> valueOf(testRun, handle).shouldNotBeNull(); <ide> valueOf(testRun, handle).shouldBeNumber(); <ide> <ide> // Remove added listener <del> valueOf(testRun, function() { tizenHistory.removeChangeListener(handle); }).shouldNotThrowException(); <add> valueOf(testRun, function() { callhistoryObj.removeChangeListener(handle); }).shouldNotThrowException(); <ide> } catch (error) { <ide> reportError(testRun, 'The following error occurred: ' + error.message); <ide> }
Java
apache-2.0
f0a2b45787e0973130dc17b11492e16dcbbf0ec0
0
blindpirate/gradle,gradle/gradle,gstevey/gradle,gradle/gradle,lsmaira/gradle,robinverduijn/gradle,gradle/gradle,robinverduijn/gradle,gstevey/gradle,gstevey/gradle,blindpirate/gradle,robinverduijn/gradle,robinverduijn/gradle,blindpirate/gradle,gstevey/gradle,robinverduijn/gradle,lsmaira/gradle,gstevey/gradle,blindpirate/gradle,robinverduijn/gradle,blindpirate/gradle,robinverduijn/gradle,gstevey/gradle,gradle/gradle,lsmaira/gradle,gradle/gradle,blindpirate/gradle,lsmaira/gradle,blindpirate/gradle,blindpirate/gradle,lsmaira/gradle,lsmaira/gradle,robinverduijn/gradle,gradle/gradle,robinverduijn/gradle,robinverduijn/gradle,lsmaira/gradle,gradle/gradle,gradle/gradle,lsmaira/gradle,blindpirate/gradle,robinverduijn/gradle,gstevey/gradle,gradle/gradle,lsmaira/gradle,gradle/gradle,blindpirate/gradle,lsmaira/gradle,gstevey/gradle,gstevey/gradle
/* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle; import org.gradle.api.Incubating; import org.gradle.api.Nullable; import java.io.File; import java.util.List; /** * A request to execute some tasks, along with an optional project path context to provide information necessary to select the tasks * * @since 2.0 */ @Incubating public interface TaskExecutionRequest { /** * The arguments to use to select and optionally configure the tasks, as if provided on the command-line. * * @return task name. */ List<String> getArgs(); /** * Project path associated with this task request if any. * * @return project path or {@code null} to use the default project path. */ @Nullable String getProjectPath(); /** * The root folder of the build that this task was defined in. * * @return the root project folder or {@null} if the information is not available. */ @Nullable File getRootDir(); }
subprojects/core/src/main/java/org/gradle/TaskExecutionRequest.java
/* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle; import org.gradle.api.Incubating; import org.gradle.api.Nullable; import java.io.File; import java.util.List; /** * A request to execute some tasks, along with an optional project path context to provide information necessary to select the tasks * * @since 2.0 */ @Incubating public interface TaskExecutionRequest { /** * The arguments to use to select and optionally configure the tasks, as if provided on the command-line. * * @return task name. */ List<String> getArgs(); /** * Project path associated with this task request if any. * * @return project path or {@code null} to use the default project path. */ @Nullable String getProjectPath(); /** * The root folder of the build from where the task should be executed. * * @return the root project folder or {@null} if the information is not available. */ @Nullable File getRootDir(); }
Adjust javadoc +review REVIEW-6342
subprojects/core/src/main/java/org/gradle/TaskExecutionRequest.java
Adjust javadoc
<ide><path>ubprojects/core/src/main/java/org/gradle/TaskExecutionRequest.java <ide> @Nullable String getProjectPath(); <ide> <ide> /** <del> * The root folder of the build from where the task should be executed. <add> * The root folder of the build that this task was defined in. <ide> * <ide> * @return the root project folder or {@null} if the information is not available. <ide> */
Java
apache-2.0
6e9b6f5035d92efff14b9e8f3aa6adc096f064d4
0
oplinkoms/onos,oplinkoms/onos,gkatsikas/onos,kuujo/onos,opennetworkinglab/onos,opennetworkinglab/onos,kuujo/onos,gkatsikas/onos,oplinkoms/onos,opennetworkinglab/onos,kuujo/onos,gkatsikas/onos,kuujo/onos,gkatsikas/onos,oplinkoms/onos,kuujo/onos,oplinkoms/onos,opennetworkinglab/onos,opennetworkinglab/onos,opennetworkinglab/onos,gkatsikas/onos,oplinkoms/onos,gkatsikas/onos,oplinkoms/onos,kuujo/onos,kuujo/onos
/* * Copyright 2017-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.pipelines.fabric.pipeliner; import org.onosproject.net.DeviceId; import org.onosproject.net.driver.Driver; import org.onosproject.net.flow.DefaultFlowRule; import org.onosproject.net.flow.DefaultTrafficSelector; import org.onosproject.net.flow.DefaultTrafficTreatment; import org.onosproject.net.flow.TrafficSelector; import org.onosproject.net.flow.TrafficTreatment; import org.onosproject.net.flow.criteria.PiCriterion; import org.onosproject.net.flow.instructions.Instruction; import org.onosproject.net.flow.instructions.Instructions.OutputInstruction; import org.onosproject.net.flowobjective.DefaultNextObjective; import org.onosproject.net.flowobjective.NextObjective; import org.onosproject.net.flowobjective.Objective; import org.onosproject.net.flowobjective.ObjectiveError; import org.onosproject.net.group.DefaultGroupBucket; import org.onosproject.net.group.DefaultGroupDescription; import org.onosproject.net.group.GroupBucket; import org.onosproject.net.group.GroupBuckets; import org.onosproject.net.group.GroupDescription; import org.onosproject.net.pi.runtime.PiActionGroupId; import org.onosproject.net.pi.runtime.PiGroupKey; import org.slf4j.Logger; import java.util.List; import java.util.stream.Collectors; import static org.onosproject.pipelines.fabric.FabricConstants.ACT_PRF_NEXT_ECMP_SELECTOR_ID; import static org.onosproject.pipelines.fabric.FabricConstants.HF_FABRIC_METADATA_NEXT_ID_ID; import static org.onosproject.pipelines.fabric.FabricConstants.TBL_HASHED_ID; import static org.onosproject.pipelines.fabric.FabricConstants.TBL_SIMPLE_ID; import static org.slf4j.LoggerFactory.getLogger; /** * Handling next objective for fabric pipeliner. */ public class FabricNextPipeliner { private static final Logger log = getLogger(FabricNextPipeliner.class); private static final String NO_HASHED_TABLE = "noHashedTable"; protected DeviceId deviceId; protected Driver driver; public FabricNextPipeliner(DeviceId deviceId, Driver driver) { this.deviceId = deviceId; this.driver = driver; } public PipelinerTranslationResult next(NextObjective nextObjective) { PipelinerTranslationResult.Builder resultBuilder = PipelinerTranslationResult.builder(); switch (nextObjective.type()) { case SIMPLE: processSimpleNext(nextObjective, resultBuilder); break; case HASHED: processHashedNext(nextObjective, resultBuilder); break; default: log.warn("Unsupported next type {}", nextObjective); resultBuilder.setError(ObjectiveError.UNSUPPORTED); break; } return resultBuilder.build(); } private void processSimpleNext(NextObjective next, PipelinerTranslationResult.Builder resultBuilder) { if (next.next().size() > 1) { log.warn("Only one treatment in simple next objective"); resultBuilder.setError(ObjectiveError.BADPARAMS); return; } TrafficSelector selector = buildNextIdSelector(next.id()); TrafficTreatment treatment = next.next().iterator().next(); OutputInstruction outputInst = treatment.allInstructions() .stream() .filter(inst -> inst.type() == Instruction.Type.OUTPUT) .map(inst -> (OutputInstruction) inst) .findFirst() .orElse(null); if (outputInst == null) { log.warn("At least one output instruction in simple next objective"); resultBuilder.setError(ObjectiveError.BADPARAMS); return; } resultBuilder.addFlowRule(DefaultFlowRule.builder() .withSelector(selector) .withTreatment(treatment) .forTable(TBL_SIMPLE_ID) .makePermanent() .withPriority(next.priority()) .forDevice(deviceId) .fromApp(next.appId()) .build()); } private void processHashedNext(NextObjective nextObjective, PipelinerTranslationResult.Builder resultBuilder) { boolean noHashedTable = Boolean.parseBoolean(driver.getProperty(NO_HASHED_TABLE)); if (noHashedTable) { if (nextObjective.next().isEmpty()) { return; } // use first action if not support hashed group TrafficTreatment treatment = nextObjective.next().iterator().next(); NextObjective.Builder simpleNext = DefaultNextObjective.builder() .addTreatment(treatment) .withId(nextObjective.id()) .fromApp(nextObjective.appId()) .makePermanent() .withMeta(nextObjective.meta()) .withPriority(nextObjective.priority()) .withType(NextObjective.Type.SIMPLE); if (nextObjective.context().isPresent()) { processSimpleNext(simpleNext.add(nextObjective.context().get()), resultBuilder); } else { processSimpleNext(simpleNext.add(), resultBuilder); } return; } // create hash groups int groupId = nextObjective.id(); List<GroupBucket> bucketList = nextObjective.next().stream() .map(DefaultGroupBucket::createSelectGroupBucket) .collect(Collectors.toList()); if (bucketList.size() != nextObjective.next().size()) { // some action not converted // set error log.warn("Expected bucket size {}, got {}", nextObjective.next().size(), bucketList.size()); resultBuilder.setError(ObjectiveError.BADPARAMS); return; } GroupBuckets buckets = new GroupBuckets(bucketList); PiGroupKey groupKey = new PiGroupKey(TBL_HASHED_ID, ACT_PRF_NEXT_ECMP_SELECTOR_ID, groupId); resultBuilder.addGroup(new DefaultGroupDescription(deviceId, GroupDescription.Type.SELECT, buckets, groupKey, groupId, nextObjective.appId())); // flow // If operation is ADD_TO_EXIST or REMOVE_FROM_EXIST, means we modify // group buckets only, no changes for flow rule if (nextObjective.op() == Objective.Operation.ADD_TO_EXISTING || nextObjective.op() == Objective.Operation.REMOVE_FROM_EXISTING) { return; } TrafficSelector selector = buildNextIdSelector(nextObjective.id()); TrafficTreatment treatment = DefaultTrafficTreatment.builder() .piTableAction(PiActionGroupId.of(nextObjective.id())) .build(); resultBuilder.addFlowRule(DefaultFlowRule.builder() .withSelector(selector) .withTreatment(treatment) .forTable(TBL_HASHED_ID) .makePermanent() .withPriority(nextObjective.priority()) .forDevice(deviceId) .fromApp(nextObjective.appId()) .build()); } private TrafficSelector buildNextIdSelector(int nextId) { PiCriterion nextIdCriterion = PiCriterion.builder() .matchExact(HF_FABRIC_METADATA_NEXT_ID_ID, nextId) .build(); return DefaultTrafficSelector.builder() .matchPi(nextIdCriterion) .build(); } }
pipelines/fabric/src/main/java/org/onosproject/pipelines/fabric/pipeliner/FabricNextPipeliner.java
/* * Copyright 2017-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.pipelines.fabric.pipeliner; import org.onosproject.net.DeviceId; import org.onosproject.net.driver.Driver; import org.onosproject.net.flow.DefaultFlowRule; import org.onosproject.net.flow.DefaultTrafficSelector; import org.onosproject.net.flow.DefaultTrafficTreatment; import org.onosproject.net.flow.TrafficSelector; import org.onosproject.net.flow.TrafficTreatment; import org.onosproject.net.flow.criteria.PiCriterion; import org.onosproject.net.flow.instructions.Instruction; import org.onosproject.net.flow.instructions.Instructions.OutputInstruction; import org.onosproject.net.flowobjective.DefaultNextObjective; import org.onosproject.net.flowobjective.NextObjective; import org.onosproject.net.flowobjective.ObjectiveError; import org.onosproject.net.group.DefaultGroupBucket; import org.onosproject.net.group.DefaultGroupDescription; import org.onosproject.net.group.GroupBucket; import org.onosproject.net.group.GroupBuckets; import org.onosproject.net.group.GroupDescription; import org.onosproject.net.pi.runtime.PiActionGroupId; import org.onosproject.net.pi.runtime.PiGroupKey; import org.slf4j.Logger; import java.util.List; import java.util.stream.Collectors; import static org.onosproject.pipelines.fabric.FabricConstants.ACT_PRF_NEXT_ECMP_SELECTOR_ID; import static org.onosproject.pipelines.fabric.FabricConstants.HF_FABRIC_METADATA_NEXT_ID_ID; import static org.onosproject.pipelines.fabric.FabricConstants.TBL_HASHED_ID; import static org.onosproject.pipelines.fabric.FabricConstants.TBL_SIMPLE_ID; import static org.slf4j.LoggerFactory.getLogger; /** * Handling next objective for fabric pipeliner. */ public class FabricNextPipeliner { private static final Logger log = getLogger(FabricNextPipeliner.class); private static final String NO_HASHED_TABLE = "noHashedTable"; protected DeviceId deviceId; protected Driver driver; public FabricNextPipeliner(DeviceId deviceId, Driver driver) { this.deviceId = deviceId; this.driver = driver; } public PipelinerTranslationResult next(NextObjective nextObjective) { PipelinerTranslationResult.Builder resultBuilder = PipelinerTranslationResult.builder(); switch (nextObjective.type()) { case SIMPLE: processSimpleNext(nextObjective, resultBuilder); break; case HASHED: processHashedNext(nextObjective, resultBuilder); break; default: log.warn("Unsupported next type {}", nextObjective); resultBuilder.setError(ObjectiveError.UNSUPPORTED); break; } return resultBuilder.build(); } private void processSimpleNext(NextObjective next, PipelinerTranslationResult.Builder resultBuilder) { if (next.next().size() > 1) { log.warn("Only one treatment in simple next objective"); resultBuilder.setError(ObjectiveError.BADPARAMS); return; } TrafficSelector selector = buildNextIdSelector(next.id()); TrafficTreatment treatment = next.next().iterator().next(); OutputInstruction outputInst = treatment.allInstructions() .stream() .filter(inst -> inst.type() == Instruction.Type.OUTPUT) .map(inst -> (OutputInstruction) inst) .findFirst() .orElse(null); if (outputInst == null) { log.warn("At least one output instruction in simple next objective"); resultBuilder.setError(ObjectiveError.BADPARAMS); return; } resultBuilder.addFlowRule(DefaultFlowRule.builder() .withSelector(selector) .withTreatment(treatment) .forTable(TBL_SIMPLE_ID) .makePermanent() .withPriority(next.priority()) .forDevice(deviceId) .fromApp(next.appId()) .build()); } private void processHashedNext(NextObjective nextObjective, PipelinerTranslationResult.Builder resultBuilder) { boolean noHashedTable = Boolean.parseBoolean(driver.getProperty(NO_HASHED_TABLE)); if (noHashedTable) { if (nextObjective.next().isEmpty()) { return; } // use first action if not support hashed group TrafficTreatment treatment = nextObjective.next().iterator().next(); NextObjective.Builder simpleNext = DefaultNextObjective.builder() .addTreatment(treatment) .withId(nextObjective.id()) .fromApp(nextObjective.appId()) .makePermanent() .withMeta(nextObjective.meta()) .withPriority(nextObjective.priority()) .withType(NextObjective.Type.SIMPLE); if (nextObjective.context().isPresent()) { processSimpleNext(simpleNext.add(nextObjective.context().get()), resultBuilder); } else { processSimpleNext(simpleNext.add(), resultBuilder); } return; } // create hash groups int groupId = nextObjective.id(); List<GroupBucket> bucketList = nextObjective.next().stream() .map(DefaultGroupBucket::createSelectGroupBucket) .collect(Collectors.toList()); if (bucketList.size() != nextObjective.next().size()) { // some action not converted // set error log.warn("Expected bucket size {}, got {}", nextObjective.next().size(), bucketList.size()); resultBuilder.setError(ObjectiveError.BADPARAMS); return; } GroupBuckets buckets = new GroupBuckets(bucketList); PiGroupKey groupKey = new PiGroupKey(TBL_HASHED_ID, ACT_PRF_NEXT_ECMP_SELECTOR_ID, groupId); resultBuilder.addGroup(new DefaultGroupDescription(deviceId, GroupDescription.Type.SELECT, buckets, groupKey, groupId, nextObjective.appId())); // flow TrafficSelector selector = buildNextIdSelector(nextObjective.id()); TrafficTreatment treatment = DefaultTrafficTreatment.builder() .piTableAction(PiActionGroupId.of(nextObjective.id())) .build(); resultBuilder.addFlowRule(DefaultFlowRule.builder() .withSelector(selector) .withTreatment(treatment) .forTable(TBL_HASHED_ID) .makePermanent() .withPriority(nextObjective.priority()) .forDevice(deviceId) .fromApp(nextObjective.appId()) .build()); } private TrafficSelector buildNextIdSelector(int nextId) { PiCriterion nextIdCriterion = PiCriterion.builder() .matchExact(HF_FABRIC_METADATA_NEXT_ID_ID, nextId) .build(); return DefaultTrafficSelector.builder() .matchPi(nextIdCriterion) .build(); } }
[ONOS-7504] Skip adding or removing flows when operation is ADD_TO_EXIST or REMOVE_FROM_EXIST Change-Id: Ia45ae50ceb94423df19cc1916dd794e736b9af1b
pipelines/fabric/src/main/java/org/onosproject/pipelines/fabric/pipeliner/FabricNextPipeliner.java
[ONOS-7504] Skip adding or removing flows when operation is ADD_TO_EXIST or REMOVE_FROM_EXIST
<ide><path>ipelines/fabric/src/main/java/org/onosproject/pipelines/fabric/pipeliner/FabricNextPipeliner.java <ide> import org.onosproject.net.flow.instructions.Instructions.OutputInstruction; <ide> import org.onosproject.net.flowobjective.DefaultNextObjective; <ide> import org.onosproject.net.flowobjective.NextObjective; <add>import org.onosproject.net.flowobjective.Objective; <ide> import org.onosproject.net.flowobjective.ObjectiveError; <ide> import org.onosproject.net.group.DefaultGroupBucket; <ide> import org.onosproject.net.group.DefaultGroupDescription; <ide> nextObjective.appId())); <ide> <ide> // flow <add> // If operation is ADD_TO_EXIST or REMOVE_FROM_EXIST, means we modify <add> // group buckets only, no changes for flow rule <add> if (nextObjective.op() == Objective.Operation.ADD_TO_EXISTING || <add> nextObjective.op() == Objective.Operation.REMOVE_FROM_EXISTING) { <add> return; <add> } <ide> TrafficSelector selector = buildNextIdSelector(nextObjective.id()); <ide> TrafficTreatment treatment = DefaultTrafficTreatment.builder() <ide> .piTableAction(PiActionGroupId.of(nextObjective.id()))
JavaScript
agpl-3.0
54261197a239bf8183919f70df23c6d57ba9a990
0
matthewpipie/BlockScheduleHelperWWW,matthewpipie/BlockScheduleHelperWWW
var timeouts = []; var setUpSettings = { twelveHourTime: false, pushNotifications: false, dateformat: 0, daysperweek: 7, ready: false, day: false, pagecontainerbeforeshow: function() { }, deviceready: function() { setUpSettings.loadSettings(); setUpSettings.updateSettings(); $('#formsubmit').on('touchend', function(ev) {if (addmenu.checkOpen()) {return} ev.preventDefault(); setUpSettings.handleSubmit()}); $('#formdays').change(setUpSettings.verifyDay); $('#formtoday').change(setUpSettings.verifyToday); $('#formreset').on('touchend', function(ev) {if (addmenu.checkOpen()) {return} ev.preventDefault(); setUpSettings.confirmReset()}); $('#formreset2').on('touchend', function(ev) {if (addmenu.checkOpen()) {return} ev.preventDefault(); setUpSettings.confirmReset2()}); }, updateSettings: function() { if (!setUpSettings.ready) { setTimeout(setUpSettings.updateSettings, 10); return; } $("#formtime")[0].checked = setUpSettings.twelveHourTime; $("#formtime").flipswitch("refresh"); $("#formnotifications")[0].checked = setUpSettings.pushNotifications; $("#formnotifications").flipswitch("refresh"); $("#formselect").val(setUpSettings.dateformat).change(); $("#formdays").val(setUpSettings.daysperweek); dateConverter.currentDate = new Date(); dateConverter.getDay(); setTimeout(setUpSettings.checkDateRan, 10); }, verifyDay: function() { if (!$("#formdays").val() || $("#formdays").val() != parseInt($("#formdays").val())) { $("#formdays").val(7); } else if (parseInt($("#formdays").val()) < 1) { $("#formdays").val(1); } setUpSettings.verifyToday(); }, verifyToday: function() { var daysperweek = parseInt($("#formdays").val()); var currentDay = parseInt($("#formtoday").val()); if (!$("#formtoday").val() || $("#formtoday").val() != parseInt($("#formtoday").val())) { currentDay = 1; } if (currentDay > daysperweek) { currentDay %= daysperweek; } if (currentDay < 1) { currentDay = daysperweek; } $('#formtoday').val(currentDay); }, confirmReset: function() { navigator.notification.confirm("Are you sure you would like to delete your schedule? This can NOT be undone.", setUpSettings.handleReset, "Reset Schedule"); }, confirmReset2: function() { navigator.notification.confirm("Are you sure you would like to delete your schedule and all of your classes? This can NOT be undone.", setUpSettings.handleReset2, "Reset Everything"); }, handleReset: function(buttonIndex) { if (buttonIndex == 1) { localforage.setItem('schedule', undefined); localforage.setItem('globalSchedule', undefined); navigator.notification.alert("Schedule deleted."); } }, handleReset2: function(buttonIndex) { if (buttonIndex == 1) { localforage.setItem('schedule', undefined); localforage.setItem('globalSchedule', undefined); localforage.setItem('schoolClasses', undefined); navigator.notification.alert("Schedule and classes deleted."); } }, scheduleNextEventAndClear: function(notification, isInit) { if (isInit == undefined) { isInit = false; } //settimout for x minutes to wipe notifications //make next notification localforage.getItem('schoolClasses').then(function(schoolClasses) { localforage.getItem('schedule').then(function(schedule) { localforage.getItem('globalSchedule').then(function(globalSchedule) { localforage.getItem('daysperweek').then(function(daysperweek) { localforage.getItem('dateday').then(function(dateday) { if (schoolClasses == undefined) { schoolClasses = []; localforage.setItem('schoolClasses', schoolClasses); } if (schedule == undefined) { schedule = []; localforage.setItem('schedule', schedule); } if (globalSchedule == undefined) { globalSchedule = []; localforage.setItem('globalSchedule', globalSchedule); } if (daysperweek == undefined) { daysperweek = 7; localforage.setItem('daysperweek', daysperweek); } if (dateday == undefined) { dateday = {'date': new Date().toString(), 'day': 0}; localforage.setItem('dateday', dateday); } var now = new Date(); for (var i = 0; i < timeouts.length; i++) { clearTimeout(timeouts[i]); } day = setUpSettings.calculateDay(dateday, daysperweek, new Date()); if (schedule[day] == undefined) { schedule[day] = []; } var timeAndId = []; //{id: '5', starttime: 13546, endtime: 15493, isGlobal: false} for (var j = 0; j < schedule[day].length; j++) { var starttime = schedule[day][j]['starttime']; starttime = parseInt(starttime.substr(0, 2)) * 60 + parseInt(starttime.substr(3)); var endtime = schedule[day][j]['endtime']; endtime = parseInt(endtime.substr(0, 2)) * 60 + parseInt(endtime.substr(3)); timeAndId.push({'id': schedule[day][j]['id'], 'starttime': starttime, 'endtime': endtime, 'isGlobal': false}); } for (var i = 0; i < globalSchedule.length; i++) { var starttime = globalSchedule[i]['starttime']; starttime = parseInt(starttime.substr(0, 2)) * 60 + parseInt(starttime.substr(3)); var endtime = globalSchedule[i]['endtime']; endtime = parseInt(endtime.substr(0, 2)) * 60 + parseInt(endtime.substr(3)); timeAndId.push({'id': globalSchedule[i]['id'], 'starttime': starttime, 'endtime': endtime, 'isGlobal': true}); } var starttimeSorted = timeAndId.sort(function(a, b) {return parseInt(a['starttime'], 10) - parseInt(b['starttime'], 10);}) var endtimeSorted = timeAndId.sort(function(a, b) {return parseInt(a['endtime'], 10) - parseInt(b['endtime'], 10);}) var nowTime = now.getHours() * 60 + now.getMinutes(); var firstStartTime; var isRegular = true; var hasfound1 = false; var hasfound2 = false; var hasfound3 = false; var i; var j; for (i = nowTime; i < 1439; i++) { if (starttimeSorted.filter(function(a) {return a['starttime'] == i}).length) { if (!hasfound1) {firstStartTime = i; hasfound1 = true; continue;} else { hasfound2 = true; break; } } } if (!hasfound1) { isRegular = false; } if (isInit) { var results = starttimeSorted.filter(function(a) {return a['starttime'] < nowTime && a['endtime'] > nowTime}); if (firstStartTime - nowTime > 10 || results.length != 0) { //schedule aft i = firstStartTime; hasfound2 = true; } if (now.getDay() == 6 || now.getDay() == 0) { isRegular = false; } /* get closest ahead starttime and endtime before it if greater than 10 mins from now till next starttime AND isInit if less, if you are in a class AND isInit, schedule if not, skip one starttime and schedule then*/ } if (!hasfound2) { isRegular = false; } if (isInit && firstStartTime - nowTime > 10) { j = i - 10; hasfound3 = true; } else { for (j = i; j >= 0; j--) { if (endtimeSorted.filter(function(a) {return a['endtime'] == j}).length) { hasfound3 = true; firstEndTime = j; break; } } } if (!hasfound3) { isRegular = false; } var timeToClear; var timeToNotify; var classToNotify; var dateToNotify = new Date(); if (isRegular) { timeToClear = i; timeToNotify = j; if (timeToClear - timeToNotify > 10) { timeToNotify = timeToClear - 10; } classToNotify = starttimeSorted.filter(function(a) {return a['starttime'] == timeToClear})[0]; dateToNotify.setHours(0); dateToNotify.setSeconds(0); dateToNotify.setMilliseconds(0); dateToNotify.setMinutes(timeToNotify); } else { console.log('no bueno'); var newDate = new Date(); newDate.setHours(newDate.getHours() + 24); day = setUpSettings.calculateDay(dateday, daysperweek, newDate); var out = false; var k; for (k = 1; k < 29; k++) { console.log(day); console.log(newDate); if (schedule[day] == undefined) { schedule[day] = []; } if (schedule[day].length != 0 && newDate.getDay() < 6 && newDate.getDay() > 0) { console.log('we out fam'); out = true; break; } else { console.log('stuck in eternal poo'); newDate.setHours(newDate.getHours() + 24); day = setUpSettings.calculateDay(dateday, daysperweek, newDate); } } if (!out) { $("#formnotifications")[0].checked = false; $("#formnotifications").flipswitch("refresh"); navigator.notification.alert("Error: Please create a schedule first."); setUpSettings.handleSubmit(); return; } timeAndId = []; //{id: '5', starttime: 13546, endtime: 15493, isGlobal: false} for (var j = 0; j < schedule[day].length; j++) { var starttime = schedule[day][j]['starttime']; starttime = parseInt(starttime.substr(0, 2)) * 60 + parseInt(starttime.substr(3)); var endtime = schedule[day][j]['endtime']; endtime = parseInt(endtime.substr(0, 2)) * 60 + parseInt(endtime.substr(3)); timeAndId.push({'id': schedule[day][j]['id'], 'starttime': starttime, 'endtime': endtime, 'isGlobal': false}); } for (var i = 0; i < globalSchedule.length; i++) { var starttime = globalSchedule[i]['starttime']; starttime = parseInt(starttime.substr(0, 2)) * 60 + parseInt(starttime.substr(3)); var endtime = globalSchedule[i]['endtime']; endtime = parseInt(endtime.substr(0, 2)) * 60 + parseInt(endtime.substr(3)); timeAndId.push({'id': globalSchedule[i]['id'], 'starttime': starttime, 'endtime': endtime, 'isGlobal': true}); } starttimeSorted = timeAndId.sort(function(a, b) {return parseInt(a['starttime'], 10) - parseInt(b['starttime'], 10);}) console.log(starttimeSorted); if (starttimeSorted.length == 0) {return;} timeToClear = starttimeSorted[0]['starttime']; console.log(timeToClear); timeToNotify = timeToClear - 10; classToNotify = starttimeSorted[0]; dateToNotify = newDate; dateToNotify.setHours(0); dateToNotify.setSeconds(0); dateToNotify.setMilliseconds(0); dateToNotify.setMinutes(timeToNotify); nowTime = -(k * 1440) } if (classToNotify['isGlobal']) { classToNotify = globalSchedule.filter(function(a) {return a['id'] == classToNotify['id']})[0]; } else { classToNotify = schedule[day].filter(function(a) {return a['id'] == classToNotify['id']})[0]; } timeouts.push(setTimeout(function() {cordova.plugins.notification.local.clearAll();}, 1000 * 60 * (timeToClear - nowTime))); bgcolor = setUpSettings.findClass(schoolClasses, classToNotify['className'], 'bgcolor'); console.log(dateToNotify); scheduleObj = { id: 0, title: "Next class: " + setUpSettings.findClass(schoolClasses, classToNotify['className'], 'className') + (setUpSettings.findClass(schoolClasses, classToNotify['className'], 'room') == "" ? "" : " (" + setUpSettings.findClass(schoolClasses, classToNotify['className'], 'room') + ")"), text: "Starts in " + (timeToClear - timeToNotify).toString() + " minutes", at: dateToNotify, led: (bgcolor == null ? "FFFFFF" : bgcolor.substr(1)) }; console.log(scheduleObj); console.log(timeToClear); console.log(timeToClear - nowTime); /*if (thingo) { scheduleObj['sound'] = xyz }*/ cordova.plugins.notification.local.schedule(scheduleObj); if (isInit) { navigator.notification.alert("Notifications have been turned on."); } }); //if its past all endtimes, do tomorrow }); }); }); }); }, findClass: function(schoolClasses, schoolClassIDToFind, partToFind) { for (var i = 0; i < schoolClasses.length; i++) { if (schoolClasses[i]['id'] == schoolClassIDToFind) { return schoolClasses[i][partToFind]; } } }, calculateDay: function(dateday, daysperweek, dateToFind) { var daysBetween = 0; var setDateO = new Date(dateday['date']); var setDay = dateday['day']; if (setDateO <= dateToFind) { //set before datetofind, aka in the past daysBetween = (dateConverter.getBusinessDatesCount(setDateO, dateToFind) - 1); if (daysBetween == -1) {daysBetween = 0;} } else { daysBetween = -(dateConverter.getBusinessDatesCount(dateToFind, setDateO)); } daysBetween += setDay; daysBetween %= daysperweek; if (daysBetween < 0) { daysBetween += daysperweek; } return daysBetween; }, handleSubmit: function() { console.log('saving'); var twelveHourTime = $("#formtime")[0].checked; var pushNotifications = $("#formnotifications")[0].checked; var dateformat = $("#formselect").val(); var daysperweek = $("#formdays").val(); var currentDay = $("#formtoday").val(); localforage.setItem('twelveHourTime', twelveHourTime); localforage.setItem('pushNotifications', pushNotifications); localforage.setItem('dateformat', parseInt(dateformat)); localforage.setItem('daysperweek', parseInt(daysperweek)); localforage.setItem('currentDay', parseInt(currentDay)); dateConverter.setDateDay("", parseInt(currentDay) - 1); if (pushNotifications && !(setUpSettings.pushNotifications)) { //turned on notifications cordova.plugins.notification.local.cancelAll(function() { setUpSettings.scheduleNextEventAndClear(null, true); }); } else if (!(pushNotifications) && setUpSettings.pushNotifications) { //turned off notifications cordova.plugins.notification.local.cancelAll(function() { navigator.notification.alert("Notifications have been turned off."); }); } setUpSettings.twelveHourTime = twelveHourTime; setUpSettings.pushNotifications = pushNotifications; setUpSettings.dateformat = dateformat; setUpSettings.daysperweek = daysperweek; navigator.notification.alert("Settings saved."); }, loadSettings: function() { localforage.getItem('twelveHourTime').then(function(twelveHourTime) { if (twelveHourTime == undefined) { twelveHourTime = false; localforage.setItem('twelveHourTime', twelveHourTime); } localforage.getItem('pushNotifications').then(function(pushNotifications) { if (pushNotifications == undefined) { pushNotifications = false; localforage.setItem('pushNotifications', pushNotifications); } localforage.getItem('dateformat').then(function(dateformat) { if (dateformat == undefined) { dateformat = 0; localforage.setItem('dateformat', dateformat); } localforage.getItem('daysperweek').then(function(daysperweek) { if (daysperweek == undefined) { daysperweek = 7; localforage.setItem('daysperweek', daysperweek); } setUpSettings.twelveHourTime = twelveHourTime; setUpSettings.pushNotifications = pushNotifications; setUpSettings.dateformat = dateformat; setUpSettings.daysperweek = daysperweek; setUpSettings.ready = true; }); }); }); }); }, checkDateRan: function() { if (dateConverter.firstTime) { setTimeout(setUpSettings.checkDateRan, 10); return; } var toAdd = 1; if (new Date().getDay() == 6 || new Date().getDay() == 0) { toAdd = 2; } $("#formtoday").val(dateConverter.firstDay + toAdd); setUpSettings.verifyToday(); setUpSettings.day = dateConverter.firstDay; } }
js/setUpSettings.js
var timeouts = []; var setUpSettings = { twelveHourTime: false, pushNotifications: false, dateformat: 0, daysperweek: 7, ready: false, day: false, pagecontainerbeforeshow: function() { }, deviceready: function() { setUpSettings.loadSettings(); setUpSettings.updateSettings(); $('#formsubmit').on('touchend', function(ev) {if (addmenu.checkOpen()) {return} ev.preventDefault(); setUpSettings.handleSubmit()}); $('#formdays').change(setUpSettings.verifyDay); $('#formtoday').change(setUpSettings.verifyToday); $('#formreset').on('touchend', function(ev) {if (addmenu.checkOpen()) {return} ev.preventDefault(); setUpSettings.confirmReset()}); $('#formreset2').on('touchend', function(ev) {if (addmenu.checkOpen()) {return} ev.preventDefault(); setUpSettings.confirmReset2()}); }, updateSettings: function() { if (!setUpSettings.ready) { setTimeout(setUpSettings.updateSettings, 10); return; } $("#formtime")[0].checked = setUpSettings.twelveHourTime; $("#formtime").flipswitch("refresh"); $("#formnotifications")[0].checked = setUpSettings.pushNotifications; $("#formnotifications").flipswitch("refresh"); $("#formselect").val(setUpSettings.dateformat).change(); $("#formdays").val(setUpSettings.daysperweek); dateConverter.currentDate = new Date(); dateConverter.getDay(); setTimeout(setUpSettings.checkDateRan, 10); }, verifyDay: function() { if (!$("#formdays").val() || $("#formdays").val() != parseInt($("#formdays").val())) { $("#formdays").val(7); } else if (parseInt($("#formdays").val()) < 1) { $("#formdays").val(1); } setUpSettings.verifyToday(); }, verifyToday: function() { var daysperweek = parseInt($("#formdays").val()); var currentDay = parseInt($("#formtoday").val()); if (!$("#formtoday").val() || $("#formtoday").val() != parseInt($("#formtoday").val())) { currentDay = 1; } if (currentDay > daysperweek) { currentDay %= daysperweek; } if (currentDay < 1) { currentDay = daysperweek; } $('#formtoday').val(currentDay); }, confirmReset: function() { navigator.notification.confirm("Are you sure you would like to delete your schedule? This can NOT be undone.", setUpSettings.handleReset, "Reset Schedule"); }, confirmReset2: function() { navigator.notification.confirm("Are you sure you would like to delete your schedule and all of your classes? This can NOT be undone.", setUpSettings.handleReset2, "Reset Everything"); }, handleReset: function(buttonIndex) { if (buttonIndex == 1) { localforage.setItem('schedule', undefined); localforage.setItem('globalSchedule', undefined); navigator.notification.alert("Schedule deleted."); } }, handleReset2: function(buttonIndex) { if (buttonIndex == 1) { localforage.setItem('schedule', undefined); localforage.setItem('globalSchedule', undefined); localforage.setItem('schoolClasses', undefined); navigator.notification.alert("Schedule and classes deleted."); } }, scheduleNextEventAndClear: function(notification, isInit) { if (isInit == undefined) { isInit = false; } //settimout for x minutes to wipe notifications //make next notification localforage.getItem('schoolClasses').then(function(schoolClasses) { localforage.getItem('schedule').then(function(schedule) { localforage.getItem('globalSchedule').then(function(globalSchedule) { localforage.getItem('daysperweek').then(function(daysperweek) { localforage.getItem('dateday').then(function(dateday) { if (schoolClasses == undefined) { schoolClasses = []; localforage.setItem('schoolClasses', schoolClasses); } if (schedule == undefined) { schedule = []; localforage.setItem('schedule', schedule); } if (globalSchedule == undefined) { globalSchedule = []; localforage.setItem('globalSchedule', globalSchedule); } if (daysperweek == undefined) { daysperweek = 7; localforage.setItem('daysperweek', daysperweek); } if (dateday == undefined) { dateday = {'date': new Date().toString(), 'day': 0}; localforage.setItem('dateday', dateday); } var now = new Date(); for (var i = 0; i < timeouts.length; i++) { clearTimeout(timeouts[i]); } day = setUpSettings.calculateDay(dateday, daysperweek, new Date()); if (schedule[day] == undefined) { schedule[day] = []; } var timeAndId = []; //{id: '5', starttime: 13546, endtime: 15493, isGlobal: false} for (var j = 0; j < schedule[day].length; j++) { var starttime = schedule[day][j]['starttime']; starttime = parseInt(starttime.substr(0, 2)) * 60 + parseInt(starttime.substr(3)); var endtime = schedule[day][j]['endtime']; endtime = parseInt(endtime.substr(0, 2)) * 60 + parseInt(endtime.substr(3)); timeAndId.push({'id': schedule[day][j]['id'], 'starttime': starttime, 'endtime': endtime, 'isGlobal': false}); } for (var i = 0; i < globalSchedule.length; i++) { var starttime = globalSchedule[i]['starttime']; starttime = parseInt(starttime.substr(0, 2)) * 60 + parseInt(starttime.substr(3)); var endtime = globalSchedule[i]['endtime']; endtime = parseInt(endtime.substr(0, 2)) * 60 + parseInt(endtime.substr(3)); timeAndId.push({'id': globalSchedule[i]['id'], 'starttime': starttime, 'endtime': endtime, 'isGlobal': true}); } var starttimeSorted = timeAndId.sort(function(a, b) {return parseInt(a['starttime'], 10) - parseInt(b['starttime'], 10);}) var endtimeSorted = timeAndId.sort(function(a, b) {return parseInt(a['endtime'], 10) - parseInt(b['endtime'], 10);}) var nowTime = now.getHours() * 60 + now.getMinutes(); var firstStartTime; var isRegular = true; var hasfound1 = false; var hasfound2 = false; var hasfound3 = false; var i; var j; for (i = nowTime; i < 1439; i++) { if (starttimeSorted.filter(function(a) {return a['starttime'] == i}).length) { if (!hasfound1) {firstStartTime = i; hasfound1 = true; continue;} else { hasfound2 = true; break; } } } if (!hasfound1) { isRegular = false; } if (isInit) { var results = starttimeSorted.filter(function(a) {return a['starttime'] < nowTime && a['endtime'] > nowTime}); if (firstStartTime - nowTime > 10 || results.length != 0) { //schedule aft i = firstStartTime; hasfound2 = true; } if (now.getDay() == 6 || now.getDay() == 0) { isRegular = false; } /* get closest ahead starttime and endtime before it if greater than 10 mins from now till next starttime AND isInit if less, if you are in a class AND isInit, schedule if not, skip one starttime and schedule then*/ } if (!hasfound2) { isRegular = false; } if (isInit && firstStartTime - nowTime > 10) { j = i - 10; } else { for (j = i; j >= 0; j--) { if (endtimeSorted.filter(function(a) {return a['endtime'] == j}).length) { hasfound3 = true; firstEndTime = j; break; } } } if (!hasfound3) { isRegular = false; } var timeToClear; var timeToNotify; var classToNotify; var dateToNotify = new Date(); if (isRegular) { timeToClear = i; timeToNotify = j; if (timeToClear - timeToNotify > 10) { timeToNotify = timeToClear - 10; } classToNotify = starttimeSorted.filter(function(a) {return a['starttime'] == timeToClear})[0]; dateToNotify.setHours(0); dateToNotify.setSeconds(0); dateToNotify.setMilliseconds(0); dateToNotify.setMinutes(timeToNotify); } else { console.log('no bueno'); var newDate = new Date(); newDate.setHours(newDate.getHours() + 24); day = setUpSettings.calculateDay(dateday, daysperweek, newDate); var out = false; var k; for (k = 1; k < 29; k++) { console.log(day); console.log(newDate); if (schedule[day] == undefined) { schedule[day] = []; } if (schedule[day].length != 0 && newDate.getDay() < 6 && newDate.getDay() > 0) { console.log('we out fam'); out = true; break; } else { console.log('stuck in eternal poo'); newDate.setHours(newDate.getHours() + 24); day = setUpSettings.calculateDay(dateday, daysperweek, newDate); } } if (!out) { $("#formnotifications")[0].checked = false; $("#formnotifications").flipswitch("refresh"); navigator.notification.alert("Error: Please create a schedule first."); setUpSettings.handleSubmit(); return; } timeAndId = []; //{id: '5', starttime: 13546, endtime: 15493, isGlobal: false} for (var j = 0; j < schedule[day].length; j++) { var starttime = schedule[day][j]['starttime']; starttime = parseInt(starttime.substr(0, 2)) * 60 + parseInt(starttime.substr(3)); var endtime = schedule[day][j]['endtime']; endtime = parseInt(endtime.substr(0, 2)) * 60 + parseInt(endtime.substr(3)); timeAndId.push({'id': schedule[day][j]['id'], 'starttime': starttime, 'endtime': endtime, 'isGlobal': false}); } for (var i = 0; i < globalSchedule.length; i++) { var starttime = globalSchedule[i]['starttime']; starttime = parseInt(starttime.substr(0, 2)) * 60 + parseInt(starttime.substr(3)); var endtime = globalSchedule[i]['endtime']; endtime = parseInt(endtime.substr(0, 2)) * 60 + parseInt(endtime.substr(3)); timeAndId.push({'id': globalSchedule[i]['id'], 'starttime': starttime, 'endtime': endtime, 'isGlobal': true}); } starttimeSorted = timeAndId.sort(function(a, b) {return parseInt(a['starttime'], 10) - parseInt(b['starttime'], 10);}) console.log(starttimeSorted); if (starttimeSorted.length == 0) {return;} timeToClear = starttimeSorted[0]['starttime']; console.log(timeToClear); timeToNotify = timeToClear - 10; classToNotify = starttimeSorted[0]; dateToNotify = newDate; dateToNotify.setHours(0); dateToNotify.setSeconds(0); dateToNotify.setMilliseconds(0); dateToNotify.setMinutes(timeToNotify); nowTime = -(k * 1440) } if (classToNotify['isGlobal']) { classToNotify = globalSchedule.filter(function(a) {return a['id'] == classToNotify['id']})[0]; } else { classToNotify = schedule[day].filter(function(a) {return a['id'] == classToNotify['id']})[0]; } timeouts.push(setTimeout(function() {cordova.plugins.notification.local.clearAll();}, 1000 * 60 * (timeToClear - nowTime))); bgcolor = setUpSettings.findClass(schoolClasses, classToNotify['className'], 'bgcolor'); console.log(dateToNotify); scheduleObj = { id: 0, title: "Next class: " + setUpSettings.findClass(schoolClasses, classToNotify['className'], 'className') + (setUpSettings.findClass(schoolClasses, classToNotify['className'], 'room') == "" ? "" : " (" + setUpSettings.findClass(schoolClasses, classToNotify['className'], 'room') + ")"), text: "Starts in " + (timeToClear - timeToNotify).toString() + " minutes", at: dateToNotify, led: (bgcolor == null ? "FFFFFF" : bgcolor.substr(1)) }; console.log(scheduleObj); console.log(timeToClear); console.log(timeToClear - nowTime); /*if (thingo) { scheduleObj['sound'] = xyz }*/ cordova.plugins.notification.local.schedule(scheduleObj); if (isInit) { navigator.notification.alert("Notifications have been turned on."); } }); //if its past all endtimes, do tomorrow }); }); }); }); }, findClass: function(schoolClasses, schoolClassIDToFind, partToFind) { for (var i = 0; i < schoolClasses.length; i++) { if (schoolClasses[i]['id'] == schoolClassIDToFind) { return schoolClasses[i][partToFind]; } } }, calculateDay: function(dateday, daysperweek, dateToFind) { var daysBetween = 0; var setDateO = new Date(dateday['date']); var setDay = dateday['day']; if (setDateO <= dateToFind) { //set before datetofind, aka in the past daysBetween = (dateConverter.getBusinessDatesCount(setDateO, dateToFind) - 1); if (daysBetween == -1) {daysBetween = 0;} } else { daysBetween = -(dateConverter.getBusinessDatesCount(dateToFind, setDateO)); } daysBetween += setDay; daysBetween %= daysperweek; if (daysBetween < 0) { daysBetween += daysperweek; } return daysBetween; }, handleSubmit: function() { console.log('saving'); var twelveHourTime = $("#formtime")[0].checked; var pushNotifications = $("#formnotifications")[0].checked; var dateformat = $("#formselect").val(); var daysperweek = $("#formdays").val(); var currentDay = $("#formtoday").val(); localforage.setItem('twelveHourTime', twelveHourTime); localforage.setItem('pushNotifications', pushNotifications); localforage.setItem('dateformat', parseInt(dateformat)); localforage.setItem('daysperweek', parseInt(daysperweek)); localforage.setItem('currentDay', parseInt(currentDay)); dateConverter.setDateDay("", parseInt(currentDay) - 1); if (pushNotifications && !(setUpSettings.pushNotifications)) { //turned on notifications cordova.plugins.notification.local.cancelAll(function() { setUpSettings.scheduleNextEventAndClear(null, true); }); } else if (!(pushNotifications) && setUpSettings.pushNotifications) { //turned off notifications cordova.plugins.notification.local.cancelAll(function() { navigator.notification.alert("Notifications have been turned off."); }); } setUpSettings.twelveHourTime = twelveHourTime; setUpSettings.pushNotifications = pushNotifications; setUpSettings.dateformat = dateformat; setUpSettings.daysperweek = daysperweek; navigator.notification.alert("Settings saved."); }, loadSettings: function() { localforage.getItem('twelveHourTime').then(function(twelveHourTime) { if (twelveHourTime == undefined) { twelveHourTime = false; localforage.setItem('twelveHourTime', twelveHourTime); } localforage.getItem('pushNotifications').then(function(pushNotifications) { if (pushNotifications == undefined) { pushNotifications = false; localforage.setItem('pushNotifications', pushNotifications); } localforage.getItem('dateformat').then(function(dateformat) { if (dateformat == undefined) { dateformat = 0; localforage.setItem('dateformat', dateformat); } localforage.getItem('daysperweek').then(function(daysperweek) { if (daysperweek == undefined) { daysperweek = 7; localforage.setItem('daysperweek', daysperweek); } setUpSettings.twelveHourTime = twelveHourTime; setUpSettings.pushNotifications = pushNotifications; setUpSettings.dateformat = dateformat; setUpSettings.daysperweek = daysperweek; setUpSettings.ready = true; }); }); }); }); }, checkDateRan: function() { if (dateConverter.firstTime) { setTimeout(setUpSettings.checkDateRan, 10); return; } var toAdd = 1; if (new Date().getDay() == 6 || new Date().getDay() == 0) { toAdd = 2; } $("#formtoday").val(dateConverter.firstDay + toAdd); setUpSettings.verifyToday(); setUpSettings.day = dateConverter.firstDay; } }
2.1.0 FOR ACTUAL ACTUAL ACTUAL REAL ARGH BUGS PLS
js/setUpSettings.js
2.1.0 FOR ACTUAL ACTUAL ACTUAL REAL ARGH BUGS PLS
<ide><path>s/setUpSettings.js <ide> <ide> if (isInit && firstStartTime - nowTime > 10) { <ide> j = i - 10; <add> hasfound3 = true; <ide> } <ide> else { <ide> for (j = i; j >= 0; j--) {
Java
agpl-3.0
3e337b61dced73c2f224d5a975f7beb94df18818
0
CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,CompilerWorks/spliceengine,splicemachine/spliceengine,splicemachine/spliceengine
package org.apache.derby.impl.sql.execute.operations.joins; import com.google.common.collect.Maps; import com.splicemachine.derby.test.framework.*; import com.splicemachine.homeless.TestUtils; import org.apache.log4j.Logger; import org.junit.*; import org.junit.rules.RuleChain; import org.junit.rules.TestRule; import org.junit.runner.Description; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import static com.splicemachine.homeless.TestUtils.o; public class OuterJoinIT extends SpliceUnitTest { private static Logger LOG = Logger.getLogger(OuterJoinIT.class); private static final Map<String, String> tableMap = Maps.newHashMap(); public static final String CLASS_NAME = OuterJoinIT.class.getSimpleName().toUpperCase()+ "_2"; public static final String TABLE_NAME_1 = "A"; public static final String TABLE_NAME_2 = "CC"; public static final String TABLE_NAME_3 = "DD"; public static final String TABLE_NAME_4 = "D"; public static final String TABLE_NAME_5 = "E"; public static final String TABLE_NAME_6 = "F"; public static final String TABLE_NAME_7 = "G"; protected static DefaultedSpliceWatcher spliceClassWatcher = new DefaultedSpliceWatcher(CLASS_NAME); protected static SpliceSchemaWatcher spliceSchemaWatcher = new SpliceSchemaWatcher(CLASS_NAME); protected static SpliceTableWatcher spliceTableWatcher1 = new SpliceTableWatcher(TABLE_NAME_1, CLASS_NAME, "(si varchar(40),sa character varying(40),sc varchar(40),sd int,se float)"); protected static SpliceTableWatcher spliceTableWatcher2 = new SpliceTableWatcher(TABLE_NAME_2, CLASS_NAME, "(si varchar(40), sa varchar(40))"); protected static SpliceTableWatcher spliceTableWatcher3 = new SpliceTableWatcher(TABLE_NAME_3, CLASS_NAME, "(si varchar(40), sa varchar(40))"); protected static SpliceTableWatcher spliceTableWatcher4 = new SpliceTableWatcher(TABLE_NAME_4, CLASS_NAME, "(a varchar(20), b varchar(20), c varchar(10), d decimal, e varchar(15))"); protected static SpliceTableWatcher spliceTableWatcher5 = new SpliceTableWatcher(TABLE_NAME_5, CLASS_NAME, "(a varchar(20), b varchar(20), w decimal(4),e varchar(15))"); protected static SpliceTableWatcher spliceTableWatcher6 = new SpliceTableWatcher(TABLE_NAME_6, CLASS_NAME, "(a varchar(20), b varchar(20), c varchar(10), d decimal, e varchar(15))"); protected static SpliceTableWatcher spliceTableWatcher7 = new SpliceTableWatcher(TABLE_NAME_7, CLASS_NAME, "(a varchar(20), b varchar(20), w decimal(4),e varchar(15))"); @ClassRule public static TestRule chain = RuleChain.outerRule(spliceClassWatcher) .around(spliceSchemaWatcher) .around(spliceTableWatcher1) .around(spliceTableWatcher2) .around(spliceTableWatcher3) .around(spliceTableWatcher4) .around(spliceTableWatcher5) .around(spliceTableWatcher6) .around(spliceTableWatcher7) .around(new SpliceDataWatcher() { @Override protected void starting(Description description) { try { PreparedStatement ps = spliceClassWatcher.prepareStatement(format("insert into %s (si, sa, sc,sd,se) values (?,?,?,?,?)", TABLE_NAME_1)); for (int i = 0; i < 10; i++) { ps.setString(1, "" + i); ps.setString(2, "i"); ps.setString(3, "" + i * 10); ps.setInt(4, i); ps.setFloat(5, 10.0f * i); ps.executeUpdate(); } } catch (Exception e) { throw new RuntimeException(e); } finally { spliceClassWatcher.closeAll(); } } }).around(new SpliceDataWatcher() { @Override protected void starting(Description description) { try { Statement statement = spliceClassWatcher.getStatement(); statement.execute(String.format("insert into %s values ('p1','mxss','design',10000,'deale')", TABLE_NAME_4)); statement.execute(String.format("insert into %s values ('e2','alice',12,'deale')", TABLE_NAME_5)); statement.execute(String.format("insert into %s values ('e3','alice',12,'deale')", TABLE_NAME_5)); } catch (Exception e) { throw new RuntimeException(e); } finally { spliceClassWatcher.closeAll(); } } }).around(new SpliceDataWatcher() { @Override protected void starting(Description description) { try { insertData(TABLE_NAME_2, TABLE_NAME_3, spliceClassWatcher); } catch (Exception e) { throw new RuntimeException(e); } finally { spliceClassWatcher.closeAll(); } } }).around(TestUtils.createFileDataWatcher(spliceClassWatcher, "small_msdatasample/startup.sql", CLASS_NAME)) .around(TestUtils.createFileDataWatcher(spliceClassWatcher, "test_data/employee.sql", CLASS_NAME)) .around(TestUtils.createFileDataWatcher(spliceClassWatcher, "test_data/basic_join_dataset.sql", CLASS_NAME)); @Rule public SpliceWatcher methodWatcher = new DefaultedSpliceWatcher(CLASS_NAME); public static void insertData(String t1, String t2, SpliceWatcher spliceWatcher) throws Exception { PreparedStatement psC = spliceWatcher.prepareStatement("insert into " + t1 + " values (?,?)"); PreparedStatement psD = spliceWatcher.prepareStatement("insert into " + t2 + " values (?,?)"); for (int i = 0; i < 10; i++) { psC.setString(1, "" + i); psC.setString(2, "i"); psC.executeUpdate(); if (i != 9) { psD.setString(1, "" + i); psD.setString(2, "i"); psD.executeUpdate(); } } spliceWatcher.commit(); } // TESTS @Test public void testNestedLoopLeftOuterJoin() throws Exception { ResultSet rs = methodWatcher.executeQuery("select t1.EMPNAME, t1.CITY, t2.PTYPE from STAFF t1 left outer join PROJ t2 --DERBY-PROPERTIES joinStrategy=NESTEDLOOP \n" + " on t1.CITY = t2.CITY"); List<Map> results = TestUtils.resultSetToMaps(rs); Assert.assertEquals(11, results.size()); } @Test public void testScrollableVarcharLeftOuterJoinWithJoinStrategy() throws Exception { ResultSet rs = methodWatcher.executeQuery("select cc.si, dd.si from cc left outer join dd --DERBY-PROPERTIES joinStrategy=SORTMERGE \n on cc.si = dd.si"); int j = 0; while (rs.next()) { j++; Assert.assertNotNull(rs.getString(1)); if (!rs.getString(1).equals("9")) { Assert.assertNotNull(rs.getString(2)); Assert.assertEquals(rs.getString(1), rs.getString(2)); } else { Assert.assertNull(rs.getString(2)); } } Assert.assertEquals(10, j); } @Test public void testSinkableVarcharLeftOuterJoinWithJoinStrategy() throws Exception { ResultSet rs = methodWatcher.executeQuery("select cc.si, count(*) from cc left outer join dd --DERBY-PROPERTIES joinStrategy=SORTMERGE \n on cc.si = dd.si group by cc.si"); int j = 0; while (rs.next()) { j++; LOG.info(String.format("cc.sa=%s,count=%dd", rs.getString(1), rs.getInt(2))); // Assert.assertNotNull(rs.getString(1)); // if (!rs.getString(1).equals("9")) { // Assert.assertEquals(1l,rs.getLong(2)); // } } Assert.assertEquals(10, j); } @Test @Ignore("Bug 325") public void testScrollableVarcharRightOuterJoinWithJoinStrategy() throws Exception { ResultSet rs = methodWatcher.executeQuery("select cc.si, dd.si from cc right outer join dd --DERBY-PROPERTIES joinStrategy=SORTMERGE \n on cc.si = dd.si"); int j = 0; while (rs.next()) { j++; LOG.info("cc.si=" + rs.getString(1) + ",dd.si=" + rs.getString(2)); Assert.assertNotNull(rs.getString(2)); if (!rs.getString(2).equals("9")) { Assert.assertNotNull(rs.getString(1)); Assert.assertEquals(rs.getString(1), rs.getString(2)); } else { Assert.assertNull(rs.getString(1)); } } Assert.assertEquals(9, j); } @Test @Ignore("Bug 325") public void testSinkableVarcharRightOuterJoinWithJoinStrategy() throws Exception { ResultSet rs = methodWatcher.executeQuery("select cc.si, count(*) from cc right outer join dd --DERBY-PROPERTIES joinStrategy=SORTMERGE \n on cc.si = dd.si group by cc.si"); int j = 0; while (rs.next()) { j++; Assert.assertNotNull(rs.getString(1)); if (!rs.getString(1).equals("9")) { Assert.assertEquals(1l, rs.getLong(2)); } else { Assert.assertNotNull(null); } } Assert.assertEquals(9, j); } @Test public void testScrollableVarcharLeftOuterJoin() throws Exception { ResultSet rs = methodWatcher.executeQuery("select cc.si, dd.si from cc left outer join dd on cc.si = dd.si"); int j = 0; while (rs.next()) { j++; String left = rs.getString(1); String right = rs.getString(2); System.out.printf("left=%s, right=%s%n", left, right); Assert.assertNotNull("left side is null", left); if (!rs.getString(1).equals("9")) { Assert.assertNotNull("right side is null", right); Assert.assertEquals(left, right); } else { Assert.assertNull("right side is not null", rs.getString(2)); } } Assert.assertEquals(10, j); } @Test public void testSinkableVarcharLeftOuterJoin() throws Exception { ResultSet rs = methodWatcher.executeQuery("select cc.si, count(*) from cc left outer join dd on cc.si = dd.si group by cc.si"); int j = 0; while (rs.next()) { j++; Assert.assertNotNull(rs.getString(1)); if (!rs.getString(1).equals("9")) { Assert.assertEquals(1l, rs.getLong(2)); } } Assert.assertEquals(10, j); } @Test public void testScrollableVarcharRightOuterJoin() throws Exception { ResultSet rs = methodWatcher.executeQuery("select cc.si, dd.si from cc right outer join dd on cc.si = dd.si"); int j = 0; while (rs.next()) { j++; LOG.info("c.si=" + rs.getString(1) + ",d.si=" + rs.getString(2)); Assert.assertNotNull(rs.getString(2)); if (!rs.getString(2).equals("9")) { Assert.assertNotNull(rs.getString(1)); Assert.assertEquals(rs.getString(1), rs.getString(2)); } else { Assert.assertNull(rs.getString(1)); } } Assert.assertEquals(9, j); } @Test public void testSinkableVarcharRightOuterJoin() throws Exception { ResultSet rs = methodWatcher.executeQuery("select cc.si, count(*) from cc right outer join dd on cc.si = dd.si group by cc.si"); int j = 0; while (rs.next()) { j++; Assert.assertNotNull(rs.getString(1)); if (!rs.getString(1).equals("9")) { Assert.assertEquals(1l, rs.getLong(2)); } else { Assert.assertNotNull(null); } } Assert.assertEquals(9, j); } @Test public void testLeftOuterJoinWithIsNull() throws Exception { List<Object[]> expected = Collections.singletonList( o("E5") ); ResultSet rs = methodWatcher.executeQuery("select a.empnum from staff a left outer join works b on a.empnum = b.empnum where b.empnum is null"); List results = TestUtils.resultSetToArrays(rs); Assert.assertArrayEquals(expected.toArray(), results.toArray()); } @Test public void testLeftOuterWithLessThan() throws Exception { List<Object[]> expected = Arrays.asList( o("E2"), o("E4"), o("E5")); ResultSet rs = methodWatcher.executeQuery("select a.empnum from staff a left outer join staff b " + "on a.empnum < b.empnum and a.grade = b.grade " + "where b.grade is null order by a.empnum"); List results = TestUtils.resultSetToArrays(rs); Assert.assertArrayEquals(expected.toArray(), results.toArray()); } @Test public void testRepeatedLeftOuterWithLessThan() throws Exception { for(int i=0;i<100;i++){ System.out.println(i); testLeftOuterWithLessThan(); } } }
structured_derby/src/test/java/org/apache/derby/impl/sql/execute/operations/joins/OuterJoinIT.java
package org.apache.derby.impl.sql.execute.operations.joins; import com.google.common.collect.Maps; import com.splicemachine.derby.test.framework.*; import com.splicemachine.homeless.TestUtils; import org.apache.log4j.Logger; import org.junit.*; import org.junit.rules.RuleChain; import org.junit.rules.TestRule; import org.junit.runner.Description; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import static com.splicemachine.homeless.TestUtils.o; public class OuterJoinIT extends SpliceUnitTest { private static Logger LOG = Logger.getLogger(OuterJoinIT.class); private static final Map<String, String> tableMap = Maps.newHashMap(); public static final String CLASS_NAME = OuterJoinIT.class.getSimpleName().toUpperCase()+ "_2"; public static final String TABLE_NAME_1 = "A"; public static final String TABLE_NAME_2 = "CC"; public static final String TABLE_NAME_3 = "DD"; public static final String TABLE_NAME_4 = "D"; public static final String TABLE_NAME_5 = "E"; public static final String TABLE_NAME_6 = "F"; public static final String TABLE_NAME_7 = "G"; protected static DefaultedSpliceWatcher spliceClassWatcher = new DefaultedSpliceWatcher(CLASS_NAME); protected static SpliceSchemaWatcher spliceSchemaWatcher = new SpliceSchemaWatcher(CLASS_NAME); protected static SpliceTableWatcher spliceTableWatcher1 = new SpliceTableWatcher(TABLE_NAME_1, CLASS_NAME, "(si varchar(40),sa character varying(40),sc varchar(40),sd int,se float)"); protected static SpliceTableWatcher spliceTableWatcher2 = new SpliceTableWatcher(TABLE_NAME_2, CLASS_NAME, "(si varchar(40), sa varchar(40))"); protected static SpliceTableWatcher spliceTableWatcher3 = new SpliceTableWatcher(TABLE_NAME_3, CLASS_NAME, "(si varchar(40), sa varchar(40))"); protected static SpliceTableWatcher spliceTableWatcher4 = new SpliceTableWatcher(TABLE_NAME_4, CLASS_NAME, "(a varchar(20), b varchar(20), c varchar(10), d decimal, e varchar(15))"); protected static SpliceTableWatcher spliceTableWatcher5 = new SpliceTableWatcher(TABLE_NAME_5, CLASS_NAME, "(a varchar(20), b varchar(20), w decimal(4),e varchar(15))"); protected static SpliceTableWatcher spliceTableWatcher6 = new SpliceTableWatcher(TABLE_NAME_6, CLASS_NAME, "(a varchar(20), b varchar(20), c varchar(10), d decimal, e varchar(15))"); protected static SpliceTableWatcher spliceTableWatcher7 = new SpliceTableWatcher(TABLE_NAME_7, CLASS_NAME, "(a varchar(20), b varchar(20), w decimal(4),e varchar(15))"); @ClassRule public static TestRule chain = RuleChain.outerRule(spliceClassWatcher) .around(spliceSchemaWatcher) .around(spliceTableWatcher1) .around(spliceTableWatcher2) .around(spliceTableWatcher3) .around(spliceTableWatcher4) .around(spliceTableWatcher5) .around(spliceTableWatcher6) .around(spliceTableWatcher7) .around(new SpliceDataWatcher() { @Override protected void starting(Description description) { try { PreparedStatement ps = spliceClassWatcher.prepareStatement(format("insert into %s (si, sa, sc,sd,se) values (?,?,?,?,?)", TABLE_NAME_1)); for (int i = 0; i < 10; i++) { ps.setString(1, "" + i); ps.setString(2, "i"); ps.setString(3, "" + i * 10); ps.setInt(4, i); ps.setFloat(5, 10.0f * i); ps.executeUpdate(); } } catch (Exception e) { throw new RuntimeException(e); } finally { spliceClassWatcher.closeAll(); } } }).around(new SpliceDataWatcher() { @Override protected void starting(Description description) { try { Statement statement = spliceClassWatcher.getStatement(); statement.execute(String.format("insert into %s values ('p1','mxss','design',10000,'deale')", TABLE_NAME_4)); statement.execute(String.format("insert into %s values ('e2','alice',12,'deale')", TABLE_NAME_5)); statement.execute(String.format("insert into %s values ('e3','alice',12,'deale')", TABLE_NAME_5)); } catch (Exception e) { throw new RuntimeException(e); } finally { spliceClassWatcher.closeAll(); } } }).around(new SpliceDataWatcher() { @Override protected void starting(Description description) { try { insertData(TABLE_NAME_2, TABLE_NAME_3, spliceClassWatcher); } catch (Exception e) { throw new RuntimeException(e); } finally { spliceClassWatcher.closeAll(); } } }).around(TestUtils.createFileDataWatcher(spliceClassWatcher, "small_msdatasample/startup.sql", CLASS_NAME)) .around(TestUtils.createFileDataWatcher(spliceClassWatcher, "test_data/employee.sql", CLASS_NAME)) .around(TestUtils.createFileDataWatcher(spliceClassWatcher, "test_data/basic_join_dataset.sql", CLASS_NAME)); @Rule public SpliceWatcher methodWatcher = new DefaultedSpliceWatcher(CLASS_NAME); public static void insertData(String t1, String t2, SpliceWatcher spliceWatcher) throws Exception { PreparedStatement psC = spliceWatcher.prepareStatement("insert into " + t1 + " values (?,?)"); PreparedStatement psD = spliceWatcher.prepareStatement("insert into " + t2 + " values (?,?)"); for (int i = 0; i < 10; i++) { psC.setString(1, "" + i); psC.setString(2, "i"); psC.executeUpdate(); if (i != 9) { psD.setString(1, "" + i); psD.setString(2, "i"); psD.executeUpdate(); } } spliceWatcher.commit(); } // TESTS @Test public void testNestedLoopLeftOuterJoin() throws Exception { ResultSet rs = methodWatcher.executeQuery("select t1.EMPNAME, t1.CITY, t2.PTYPE from STAFF t1 left outer join PROJ t2 --DERBY-PROPERTIES joinStrategy=NESTEDLOOP \n" + " on t1.CITY = t2.CITY"); List<Map> results = TestUtils.resultSetToMaps(rs); Assert.assertEquals(11, results.size()); } @Test public void testScrollableVarcharLeftOuterJoinWithJoinStrategy() throws Exception { ResultSet rs = methodWatcher.executeQuery("select cc.si, dd.si from cc left outer join dd --DERBY-PROPERTIES joinStrategy=SORTMERGE \n on cc.si = dd.si"); int j = 0; while (rs.next()) { j++; Assert.assertNotNull(rs.getString(1)); if (!rs.getString(1).equals("9")) { Assert.assertNotNull(rs.getString(2)); Assert.assertEquals(rs.getString(1), rs.getString(2)); } else { Assert.assertNull(rs.getString(2)); } } Assert.assertEquals(10, j); } @Test public void testSinkableVarcharLeftOuterJoinWithJoinStrategy() throws Exception { ResultSet rs = methodWatcher.executeQuery("select cc.si, count(*) from cc left outer join dd --DERBY-PROPERTIES joinStrategy=SORTMERGE \n on cc.si = dd.si group by cc.si"); int j = 0; while (rs.next()) { j++; LOG.info(String.format("cc.sa=%s,count=%dd", rs.getString(1), rs.getInt(2))); // Assert.assertNotNull(rs.getString(1)); // if (!rs.getString(1).equals("9")) { // Assert.assertEquals(1l,rs.getLong(2)); // } } Assert.assertEquals(10, j); } @Test @Ignore("Bug 325") public void testScrollableVarcharRightOuterJoinWithJoinStrategy() throws Exception { ResultSet rs = methodWatcher.executeQuery("select cc.si, dd.si from cc right outer join dd --DERBY-PROPERTIES joinStrategy=SORTMERGE \n on cc.si = dd.si"); int j = 0; while (rs.next()) { j++; LOG.info("cc.si=" + rs.getString(1) + ",dd.si=" + rs.getString(2)); Assert.assertNotNull(rs.getString(2)); if (!rs.getString(2).equals("9")) { Assert.assertNotNull(rs.getString(1)); Assert.assertEquals(rs.getString(1), rs.getString(2)); } else { Assert.assertNull(rs.getString(1)); } } Assert.assertEquals(9, j); } @Test @Ignore("Bug 325") public void testSinkableVarcharRightOuterJoinWithJoinStrategy() throws Exception { ResultSet rs = methodWatcher.executeQuery("select cc.si, count(*) from cc right outer join dd --DERBY-PROPERTIES joinStrategy=SORTMERGE \n on cc.si = dd.si group by cc.si"); int j = 0; while (rs.next()) { j++; Assert.assertNotNull(rs.getString(1)); if (!rs.getString(1).equals("9")) { Assert.assertEquals(1l, rs.getLong(2)); } else { Assert.assertNotNull(null); } } Assert.assertEquals(9, j); } @Test public void testScrollableVarcharLeftOuterJoin() throws Exception { ResultSet rs = methodWatcher.executeQuery("select cc.si, dd.si from cc left outer join dd on cc.si = dd.si"); int j = 0; while (rs.next()) { j++; String left = rs.getString(1); String right = rs.getString(2); System.out.printf("left=%s, right=%s%n", left, right); Assert.assertNotNull("left side is null", left); if (!rs.getString(1).equals("9")) { Assert.assertNotNull("right side is null", right); Assert.assertEquals(left, right); } else { Assert.assertNull("right side is not null", rs.getString(2)); } } Assert.assertEquals(10, j); } @Test public void testSinkableVarcharLeftOuterJoin() throws Exception { ResultSet rs = methodWatcher.executeQuery("select cc.si, count(*) from cc left outer join dd on cc.si = dd.si group by cc.si"); int j = 0; while (rs.next()) { j++; Assert.assertNotNull(rs.getString(1)); if (!rs.getString(1).equals("9")) { Assert.assertEquals(1l, rs.getLong(2)); } } Assert.assertEquals(10, j); } @Test public void testScrollableVarcharRightOuterJoin() throws Exception { ResultSet rs = methodWatcher.executeQuery("select cc.si, dd.si from cc right outer join dd on cc.si = dd.si"); int j = 0; while (rs.next()) { j++; LOG.info("c.si=" + rs.getString(1) + ",d.si=" + rs.getString(2)); Assert.assertNotNull(rs.getString(2)); if (!rs.getString(2).equals("9")) { Assert.assertNotNull(rs.getString(1)); Assert.assertEquals(rs.getString(1), rs.getString(2)); } else { Assert.assertNull(rs.getString(1)); } } Assert.assertEquals(9, j); } @Test public void testSinkableVarcharRightOuterJoin() throws Exception { ResultSet rs = methodWatcher.executeQuery("select cc.si, count(*) from cc right outer join dd on cc.si = dd.si group by cc.si"); int j = 0; while (rs.next()) { j++; Assert.assertNotNull(rs.getString(1)); if (!rs.getString(1).equals("9")) { Assert.assertEquals(1l, rs.getLong(2)); } else { Assert.assertNotNull(null); } } Assert.assertEquals(9, j); } @Test public void testLeftOuterJoinWithIsNull() throws Exception { List<Object[]> expected = Collections.singletonList( o("E5") ); ResultSet rs = methodWatcher.executeQuery("select a.empnum from staff a left outer join works b on a.empnum = b.empnum where b.empnum is null"); List results = TestUtils.resultSetToArrays(rs); Assert.assertArrayEquals(expected.toArray(), results.toArray()); } @Test public void testLeftOuterWithLessThan() throws Exception { List<Object[]> expected = Arrays.asList( o("E2"), o("E4"), o("E5")); ResultSet rs = methodWatcher.executeQuery("select a.empnum from staff a left outer join staff b " + "on a.empnum < b.empnum and a.grade = b.grade " + "where b.grade is null order by a.empnum"); List results = TestUtils.resultSetToArrays(rs); Assert.assertArrayEquals(expected.toArray(), results.toArray()); } }
Adding a repitition test to outer joins
structured_derby/src/test/java/org/apache/derby/impl/sql/execute/operations/joins/OuterJoinIT.java
Adding a repitition test to outer joins
<ide><path>tructured_derby/src/test/java/org/apache/derby/impl/sql/execute/operations/joins/OuterJoinIT.java <ide> List results = TestUtils.resultSetToArrays(rs); <ide> <ide> Assert.assertArrayEquals(expected.toArray(), results.toArray()); <del> <del> } <del> <add> } <add> <add> @Test <add> public void testRepeatedLeftOuterWithLessThan() throws Exception { <add> for(int i=0;i<100;i++){ <add> System.out.println(i); <add> testLeftOuterWithLessThan(); <add> } <add> } <ide> } <ide>
Java
apache-2.0
04c3458834ada6cdf5a4a0fd47f30fa9a414bc83
0
GerritCodeReview/gerrit,jackminicloud/test,makholm/gerrit-ceremony,joshuawilson/merrit,hdost/gerrit,Overruler/gerrit,TonyChai24/test,Distrotech/gerrit,anminhsu/gerrit,Team-OctOS/host_gerrit,midnightradio/gerrit,duboisf/gerrit,MerritCR/merrit,gracefullife/gerrit,teamblueridge/gerrit,GerritCodeReview/gerrit,Seinlin/gerrit,pkdevbox/gerrit,renchaorevee/gerrit,Saulis/gerrit,sudosurootdev/gerrit,gracefullife/gerrit,thesamet/gerrit,basilgor/gerrit,atdt/gerrit,Saulis/gerrit,jackminicloud/test,thesamet/gerrit,TonyChai24/test,rtyley/mini-git-server,gerrit-review/gerrit,keerath/gerrit_newssh,Saulis/gerrit,ashang/aaron-gerrit,m1kah/gerrit-contributions,Seinlin/gerrit,ashang/aaron-gerrit,Team-OctOS/host_gerrit,jeblair/gerrit,TonyChai24/test,joshuawilson/merrit,anminhsu/gerrit,Team-OctOS/host_gerrit,supriyantomaftuh/gerrit,netroby/gerrit,skurfuerst/gerrit,duboisf/gerrit,renchaorevee/gerrit,zommarin/gerrit,keerath/gerrit_newssh,Saulis/gerrit,Saulis/gerrit,Seinlin/gerrit,ckamm/gerrit,Distrotech/gerrit,keerath/gerrit_newssh,teamblueridge/gerrit,hdost/gerrit,GerritCodeReview/gerrit,MerritCR/merrit,skurfuerst/gerrit,netroby/gerrit,zommarin/gerrit,ckamm/gerrit,dwhipstock/gerrit,MerritCR/merrit,pkdevbox/gerrit,MerritCR/merrit,WANdisco/gerrit,teamblueridge/gerrit,dwhipstock/gerrit,1yvT0s/gerrit,bootstraponline-archive/gerrit-mirror,dwhipstock/gerrit,pkdevbox/gerrit,sudosurootdev/gerrit,bpollack/gerrit,ashang/aaron-gerrit,gcoders/gerrit,GerritCodeReview/gerrit,austinchic/Gerrit,supriyantomaftuh/gerrit,quyixia/gerrit,jackminicloud/test,gcoders/gerrit,renchaorevee/gerrit,dwhipstock/gerrit,quyixia/gerrit,MerritCR/merrit,dwhipstock/gerrit,atdt/gerrit,dwhipstock/gerrit,teamblueridge/gerrit,netroby/gerrit,teamblueridge/gerrit,joshuawilson/merrit,ckamm/gerrit,netroby/gerrit,gerrit-review/gerrit,gracefullife/gerrit,GerritCodeReview/gerrit,joshuawilson/merrit,atdt/gerrit,anminhsu/gerrit,gracefullife/gerrit,jackminicloud/test,1yvT0s/gerrit,ashang/aaron-gerrit,qtproject/qtqa-gerrit,skurfuerst/gerrit,netroby/gerrit,gcoders/gerrit,MerritCR/merrit,Team-OctOS/host_gerrit,gcoders/gerrit,supriyantomaftuh/gerrit,Seinlin/gerrit,renchaorevee/gerrit,bpollack/gerrit,qtproject/qtqa-gerrit,keerath/gerrit_newssh,basilgor/gerrit,basilgor/gerrit,qtproject/qtqa-gerrit,Distrotech/gerrit,makholm/gerrit-ceremony,basilgor/gerrit,hdost/gerrit,WANdisco/gerrit,hdost/gerrit,supriyantomaftuh/gerrit,pkdevbox/gerrit,thinkernel/gerrit,qtproject/qtqa-gerrit,catrope/gerrit,midnightradio/gerrit,quyixia/gerrit,atdt/gerrit,quyixia/gerrit,evanchueng/gerrit,quyixia/gerrit,pkdevbox/gerrit,gerrit-review/gerrit,TonyChai24/test,cjh1/gerrit,basilgor/gerrit,GerritCodeReview/gerrit,thinkernel/gerrit,thesamet/gerrit,skurfuerst/gerrit,supriyantomaftuh/gerrit,evanchueng/gerrit,Distrotech/gerrit,quyixia/gerrit,gracefullife/gerrit,joshuawilson/merrit,austinchic/Gerrit,CandyShop/gerrit,qtproject/qtqa-gerrit,WANdisco/gerrit,atdt/gerrit,CandyShop/gerrit,ashang/aaron-gerrit,supriyantomaftuh/gerrit,bpollack/gerrit,jeblair/gerrit,thinkernel/gerrit,gcoders/gerrit,jeblair/gerrit,Distrotech/gerrit,duboisf/gerrit,sudosurootdev/gerrit,cjh1/gerrit,evanchueng/gerrit,keerath/gerrit_newssh,dwhipstock/gerrit,1yvT0s/gerrit,joshuawilson/merrit,Overruler/gerrit,jackminicloud/test,bootstraponline-archive/gerrit-mirror,gerrit-review/gerrit,WANdisco/gerrit,WANdisco/gerrit,midnightradio/gerrit,Seinlin/gerrit,m1kah/gerrit-contributions,TonyChai24/test,Team-OctOS/host_gerrit,CandyShop/gerrit,CandyShop/gerrit,midnightradio/gerrit,WANdisco/gerrit,renchaorevee/gerrit,m1kah/gerrit-contributions,thesamet/gerrit,rtyley/mini-git-server,anminhsu/gerrit,bootstraponline-archive/gerrit-mirror,netroby/gerrit,netroby/gerrit,bpollack/gerrit,hdost/gerrit,joshuawilson/merrit,Team-OctOS/host_gerrit,MerritCR/merrit,thinkernel/gerrit,qtproject/qtqa-gerrit,pkdevbox/gerrit,Seinlin/gerrit,cjh1/gerrit,jackminicloud/test,GerritCodeReview/gerrit,zommarin/gerrit,zommarin/gerrit,gerrit-review/gerrit,anminhsu/gerrit,pkdevbox/gerrit,joshuawilson/merrit,bootstraponline-archive/gerrit-mirror,ckamm/gerrit,anminhsu/gerrit,1yvT0s/gerrit,gerrit-review/gerrit,MerritCR/merrit,zommarin/gerrit,ckamm/gerrit,cjh1/gerrit,catrope/gerrit,evanchueng/gerrit,bootstraponline-archive/gerrit-mirror,thesamet/gerrit,thinkernel/gerrit,Distrotech/gerrit,renchaorevee/gerrit,bootstraponline-archive/gerrit-mirror,bpollack/gerrit,1yvT0s/gerrit,austinchic/Gerrit,quyixia/gerrit,CandyShop/gerrit,Overruler/gerrit,Distrotech/gerrit,thesamet/gerrit,hdost/gerrit,thinkernel/gerrit,gerrit-review/gerrit,evanchueng/gerrit,hdost/gerrit,supriyantomaftuh/gerrit,catrope/gerrit,thesamet/gerrit,midnightradio/gerrit,makholm/gerrit-ceremony,TonyChai24/test,sudosurootdev/gerrit,anminhsu/gerrit,austinchic/Gerrit,gcoders/gerrit,thinkernel/gerrit,duboisf/gerrit,Overruler/gerrit,GerritCodeReview/gerrit,Saulis/gerrit,jeblair/gerrit,catrope/gerrit,midnightradio/gerrit,makholm/gerrit-ceremony,qtproject/qtqa-gerrit,Overruler/gerrit,Overruler/gerrit,Team-OctOS/host_gerrit,Seinlin/gerrit,TonyChai24/test,jackminicloud/test,m1kah/gerrit-contributions,gcoders/gerrit,renchaorevee/gerrit,bpollack/gerrit,WANdisco/gerrit,sudosurootdev/gerrit
// Copyright (C) 2008 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.client.account; import com.google.gerrit.client.ErrorDialog; import com.google.gerrit.client.Gerrit; import com.google.gerrit.client.rpc.GerritCallback; import com.google.gerrit.client.ui.FancyFlexTable; import com.google.gerrit.client.ui.SmallHeading; import com.google.gerrit.common.data.SshHostKey; import com.google.gerrit.common.errors.InvalidSshKeyException; import com.google.gerrit.reviewdb.AccountSshKey; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Element; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter; import com.google.gwtexpui.clippy.client.CopyableLabel; import com.google.gwtexpui.globalkey.client.NpTextArea; import com.google.gwtjsonrpc.client.RemoteJsonException; import com.google.gwtjsonrpc.client.VoidResult; import java.util.Collections; import java.util.HashSet; import java.util.List; class SshPanel extends Composite { private static boolean loadedApplet; private static Element applet; private static String appletErrorInvalidKey; private static String appletErrorSecurity; private SshKeyTable keys; private Button showAddKeyBlock; private Panel addKeyBlock; private Button closeAddKeyBlock; private Button clearNew; private Button addNew; private Button browse; private Timer appletLoadTimer; private NpTextArea addTxt; private Button deleteKey; private Panel serverKeys; SshPanel() { final FlowPanel body = new FlowPanel(); body.add(new UsernamePanel()); showAddKeyBlock = new Button(Util.C.buttonShowAddSshKey()); showAddKeyBlock.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { showAddKeyBlock(true); } }); keys = new SshKeyTable(); body.add(keys); { final FlowPanel fp = new FlowPanel(); deleteKey = new Button(Util.C.buttonDeleteSshKey()); deleteKey.setEnabled(false); deleteKey.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { keys.deleteChecked(); } }); fp.add(deleteKey); fp.add(showAddKeyBlock); body.add(fp); } addKeyBlock = new VerticalPanel(); addKeyBlock.setVisible(false); addKeyBlock.setStyleName(Gerrit.RESOURCES.css().addSshKeyPanel()); addKeyBlock.add(new SmallHeading(Util.C.addSshKeyPanelHeader())); addKeyBlock.add(new HTML(Util.C.addSshKeyHelp())); addTxt = new NpTextArea(); addTxt.setVisibleLines(12); addTxt.setCharacterWidth(80); DOM.setElementPropertyBoolean(addTxt.getElement(), "spellcheck", false); addKeyBlock.add(addTxt); final HorizontalPanel buttons = new HorizontalPanel(); addKeyBlock.add(buttons); clearNew = new Button(Util.C.buttonClearSshKeyInput()); clearNew.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { addTxt.setText(""); addTxt.setFocus(true); } }); buttons.add(clearNew); browse = new Button(Util.C.buttonOpenSshKey()); browse.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { doBrowse(); } }); browse.setVisible(!loadedApplet || applet != null); buttons.add(browse); addNew = new Button(Util.C.buttonAddSshKey()); addNew.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { doAddNew(); } }); buttons.add(addNew); closeAddKeyBlock = new Button(Util.C.buttonCloseAddSshKey()); closeAddKeyBlock.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { showAddKeyBlock(false); } }); buttons.add(closeAddKeyBlock); buttons.setCellWidth(closeAddKeyBlock, "100%"); buttons.setCellHorizontalAlignment(closeAddKeyBlock, HasHorizontalAlignment.ALIGN_RIGHT); body.add(addKeyBlock); serverKeys = new FlowPanel(); body.add(serverKeys); initWidget(body); } void setKeyTableVisible(final boolean on) { keys.setVisible(on); deleteKey.setVisible(on); closeAddKeyBlock.setVisible(on); } void doBrowse() { browse.setEnabled(false); if (!loadedApplet) { applet = DOM.createElement("applet"); applet.setAttribute("code", "com.google.gerrit.keyapplet.ReadPublicKey.class"); applet.setAttribute("archive", GWT.getModuleBaseURL() + AccountResources.I.keyapplet_jar().getText()); applet.setAttribute("mayscript", "true"); applet.setAttribute("width", "0"); applet.setAttribute("height", "0"); RootPanel.getBodyElement().appendChild(applet); loadedApplet = true; // We have to defer to allow the event loop time to setup that // new applet tag we just created above, and actually load the // applet into the runtime. // appletLoadTimer = new Timer() { private int attempts; @Override public void run() { if (isAppletRunning(applet)) { appletLoadTimer = null; cancel(); doBrowse(); } else if (30000 / 200 < attempts++) { appletLoadTimer = null; cancel(); noBrowse(); } } }; appletLoadTimer.scheduleRepeating(200); return; } if (applet == null || !isAppletRunning(applet)) { // If the applet element is null, the applet was determined // to have failed to load, and we are dead. Hide the button. // noBrowse(); return; } String txt; try { txt = openPublicKey(applet); } catch (RuntimeException re) { // If this call fails, the applet is dead. It is most likely // not loading due to Java support being disabled. // noBrowse(); return; } if (txt == null) { txt = ""; } browse.setEnabled(true); if (appletErrorInvalidKey == null) { appletErrorInvalidKey = getErrorInvalidKey(applet); appletErrorSecurity = getErrorSecurity(applet); } if (appletErrorInvalidKey.equals(txt)) { new ErrorDialog(Util.C.invalidSshKeyError()).center(); return; } if (appletErrorSecurity.equals(txt)) { new ErrorDialog(Util.C.invalidSshKeyError()).center(); return; } addTxt.setText(txt); addNew.setFocus(true); } private void noBrowse() { if (applet != null) { applet.getParentElement().removeChild(applet); applet = null; } browse.setVisible(false); new ErrorDialog(Util.C.sshJavaAppletNotAvailable()).center(); } private static native boolean isAppletRunning(Element keyapp) /*-{ return keyapp['openPublicKey'] ? true : false }-*/; private static native String openPublicKey(Element keyapp) /*-{ var r = keyapp.openPublicKey(); return r == null ? null : ''+r; }-*/; private static native String getErrorInvalidKey(Element keyapp) /*-{ return ''+keyapp.getErrorInvalidKey(); }-*/; private static native String getErrorSecurity(Element keyapp) /*-{ return ''+keyapp.getErrorSecurity(); }-*/; void doAddNew() { final String txt = addTxt.getText(); if (txt != null && txt.length() > 0) { addNew.setEnabled(false); Util.ACCOUNT_SEC.addSshKey(txt, new GerritCallback<AccountSshKey>() { public void onSuccess(final AccountSshKey result) { addNew.setEnabled(true); addTxt.setText(""); keys.addOneKey(result); if (!keys.isVisible()) { showAddKeyBlock(false); setKeyTableVisible(true); keys.updateDeleteButton(); } } @Override public void onFailure(final Throwable caught) { addNew.setEnabled(true); if (isInvalidSshKey(caught)) { new ErrorDialog(Util.C.invalidSshKeyError()).center(); } else { super.onFailure(caught); } } private boolean isInvalidSshKey(final Throwable caught) { if (caught instanceof InvalidSshKeyException) { return true; } return caught instanceof RemoteJsonException && InvalidSshKeyException.MESSAGE.equals(caught.getMessage()); } }); } } @Override protected void onLoad() { super.onLoad(); Util.ACCOUNT_SEC.mySshKeys(new GerritCallback<List<AccountSshKey>>() { public void onSuccess(final List<AccountSshKey> result) { keys.display(result); if (result.isEmpty() && keys.isVisible()) { showAddKeyBlock(true); } } }); Gerrit.SYSTEM_SVC.daemonHostKeys(new GerritCallback<List<SshHostKey>>() { public void onSuccess(final List<SshHostKey> result) { serverKeys.clear(); for (final SshHostKey keyInfo : result) { serverKeys.add(new SshHostKeyPanel(keyInfo)); } } }); } @Override protected void onUnload() { if (appletLoadTimer != null) { appletLoadTimer.cancel(); appletLoadTimer = null; } super.onUnload(); } private void showAddKeyBlock(final boolean show) { showAddKeyBlock.setVisible(!show); addKeyBlock.setVisible(show); } private class SshKeyTable extends FancyFlexTable<AccountSshKey> { private ValueChangeHandler<Boolean> updateDeleteHandler; SshKeyTable() { table.setWidth(""); table.setText(0, 2, Util.C.sshKeyStatus()); table.setText(0, 3, Util.C.sshKeyAlgorithm()); table.setText(0, 4, Util.C.sshKeyKey()); table.setText(0, 5, Util.C.sshKeyComment()); final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.addStyleName(0, 1, Gerrit.RESOURCES.css().iconHeader()); fmt.addStyleName(0, 2, Gerrit.RESOURCES.css().dataHeader()); fmt.addStyleName(0, 3, Gerrit.RESOURCES.css().dataHeader()); fmt.addStyleName(0, 4, Gerrit.RESOURCES.css().dataHeader()); fmt.addStyleName(0, 5, Gerrit.RESOURCES.css().dataHeader()); updateDeleteHandler = new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { updateDeleteButton(); } }; } void deleteChecked() { final HashSet<AccountSshKey.Id> ids = new HashSet<AccountSshKey.Id>(); for (int row = 1; row < table.getRowCount(); row++) { final AccountSshKey k = getRowItem(row); if (k != null && ((CheckBox) table.getWidget(row, 1)).getValue()) { ids.add(k.getKey()); } } if (ids.isEmpty()) { updateDeleteButton(); } else { Util.ACCOUNT_SEC.deleteSshKeys(ids, new GerritCallback<VoidResult>() { public void onSuccess(final VoidResult result) { for (int row = 1; row < table.getRowCount();) { final AccountSshKey k = getRowItem(row); if (k != null && ids.contains(k.getKey())) { table.removeRow(row); } else { row++; } } if (table.getRowCount() == 1) { display(Collections.<AccountSshKey> emptyList()); } else { updateDeleteButton(); } } }); } } void display(final List<AccountSshKey> result) { if (result.isEmpty()) { setKeyTableVisible(false); showAddKeyBlock(true); } else { while (1 < table.getRowCount()) table.removeRow(table.getRowCount() - 1); for (final AccountSshKey k : result) { addOneKey(k); } setKeyTableVisible(true); deleteKey.setEnabled(false); } } void addOneKey(final AccountSshKey k) { final FlexCellFormatter fmt = table.getFlexCellFormatter(); final int row = table.getRowCount(); table.insertRow(row); applyDataRowStyle(row); final CheckBox sel = new CheckBox(); sel.addValueChangeHandler(updateDeleteHandler); table.setWidget(row, 1, sel); if (k.isValid()) { table.setText(row, 2, ""); fmt.removeStyleName(row, 2, // Gerrit.RESOURCES.css().sshKeyPanelInvalid()); } else { table.setText(row, 2, Util.C.sshKeyInvalid()); fmt.addStyleName(row, 2, Gerrit.RESOURCES.css().sshKeyPanelInvalid()); } table.setText(row, 3, k.getAlgorithm()); CopyableLabel keyLabel = new CopyableLabel(k.getEncodedKey()); keyLabel.setPreviewText(elide(k.getEncodedKey(), 40)); table.setWidget(row, 4, keyLabel); table.setText(row, 5, k.getComment()); fmt.addStyleName(row, 1, Gerrit.RESOURCES.css().iconCell()); fmt.addStyleName(row, 4, Gerrit.RESOURCES.css().sshKeyPanelEncodedKey()); for (int c = 2; c <= 5; c++) { fmt.addStyleName(row, c, Gerrit.RESOURCES.css().dataCell()); } setRowItem(row, k); } void updateDeleteButton() { boolean on = false; for (int row = 1; row < table.getRowCount(); row++) { CheckBox sel = (CheckBox) table.getWidget(row, 1); if (sel.getValue()) { on = true; break; } } deleteKey.setEnabled(on); } } static String elide(final String s, final int len) { if (s == null || s.length() < len || len <= 10) { return s; } return s.substring(0, len - 10) + "..." + s.substring(s.length() - 10); } }
gerrit-gwtui/src/main/java/com/google/gerrit/client/account/SshPanel.java
// Copyright (C) 2008 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.client.account; import com.google.gerrit.client.ErrorDialog; import com.google.gerrit.client.Gerrit; import com.google.gerrit.client.rpc.GerritCallback; import com.google.gerrit.client.ui.FancyFlexTable; import com.google.gerrit.client.ui.SmallHeading; import com.google.gerrit.common.data.SshHostKey; import com.google.gerrit.common.errors.InvalidSshKeyException; import com.google.gerrit.reviewdb.AccountSshKey; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Element; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.event.logical.shared.ValueChangeEvent; import com.google.gwt.event.logical.shared.ValueChangeHandler; import com.google.gwt.user.client.DOM; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.InlineLabel; import com.google.gwt.user.client.ui.Panel; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter; import com.google.gwtexpui.clippy.client.CopyableLabel; import com.google.gwtexpui.globalkey.client.NpTextArea; import com.google.gwtjsonrpc.client.RemoteJsonException; import com.google.gwtjsonrpc.client.VoidResult; import java.util.Collections; import java.util.HashSet; import java.util.List; class SshPanel extends Composite { private static boolean loadedApplet; private static Element applet; private static String appletErrorInvalidKey; private static String appletErrorSecurity; private SshKeyTable keys; private Button showAddKeyBlock; private Panel addKeyBlock; private Button closeAddKeyBlock; private Button clearNew; private Button addNew; private Button browse; private Timer appletLoadTimer; private NpTextArea addTxt; private Button deleteKey; private Panel serverKeys; SshPanel() { final FlowPanel body = new FlowPanel(); body.add(new UsernamePanel()); showAddKeyBlock = new Button(Util.C.buttonShowAddSshKey()); showAddKeyBlock.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { showAddKeyBlock(true); } }); keys = new SshKeyTable(); body.add(keys); { final FlowPanel fp = new FlowPanel(); deleteKey = new Button(Util.C.buttonDeleteSshKey()); deleteKey.setEnabled(false); deleteKey.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { keys.deleteChecked(); } }); fp.add(deleteKey); fp.add(showAddKeyBlock); body.add(fp); } addKeyBlock = new VerticalPanel(); addKeyBlock.setVisible(false); addKeyBlock.setStyleName(Gerrit.RESOURCES.css().addSshKeyPanel()); addKeyBlock.add(new SmallHeading(Util.C.addSshKeyPanelHeader())); addKeyBlock.add(new HTML(Util.C.addSshKeyHelp())); addTxt = new NpTextArea(); addTxt.setVisibleLines(12); addTxt.setCharacterWidth(80); DOM.setElementPropertyBoolean(addTxt.getElement(), "spellcheck", false); addKeyBlock.add(addTxt); final HorizontalPanel buttons = new HorizontalPanel(); addKeyBlock.add(buttons); clearNew = new Button(Util.C.buttonClearSshKeyInput()); clearNew.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { addTxt.setText(""); addTxt.setFocus(true); } }); buttons.add(clearNew); browse = new Button(Util.C.buttonOpenSshKey()); browse.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { doBrowse(); } }); browse.setVisible(!loadedApplet || applet != null); buttons.add(browse); addNew = new Button(Util.C.buttonAddSshKey()); addNew.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { doAddNew(); } }); buttons.add(addNew); closeAddKeyBlock = new Button(Util.C.buttonCloseAddSshKey()); closeAddKeyBlock.addClickHandler(new ClickHandler() { @Override public void onClick(final ClickEvent event) { showAddKeyBlock(false); } }); buttons.add(closeAddKeyBlock); buttons.setCellWidth(closeAddKeyBlock, "100%"); buttons.setCellHorizontalAlignment(closeAddKeyBlock, HasHorizontalAlignment.ALIGN_RIGHT); body.add(addKeyBlock); serverKeys = new FlowPanel(); body.add(serverKeys); initWidget(body); } void setKeyTableVisible(final boolean on) { keys.setVisible(on); deleteKey.setVisible(on); closeAddKeyBlock.setVisible(on); } void doBrowse() { browse.setEnabled(false); if (!loadedApplet) { applet = DOM.createElement("applet"); applet.setAttribute("code", "com.google.gerrit.keyapplet.ReadPublicKey.class"); applet.setAttribute("archive", GWT.getModuleBaseURL() + AccountResources.I.keyapplet_jar().getText()); applet.setAttribute("mayscript", "true"); applet.setAttribute("width", "0"); applet.setAttribute("height", "0"); RootPanel.getBodyElement().appendChild(applet); loadedApplet = true; // We have to defer to allow the event loop time to setup that // new applet tag we just created above, and actually load the // applet into the runtime. // appletLoadTimer = new Timer() { private int attempts; @Override public void run() { if (isAppletRunning(applet)) { appletLoadTimer = null; cancel(); doBrowse(); } else if (30000 / 200 < attempts++) { appletLoadTimer = null; cancel(); noBrowse(); } } }; appletLoadTimer.scheduleRepeating(200); return; } if (applet == null || !isAppletRunning(applet)) { // If the applet element is null, the applet was determined // to have failed to load, and we are dead. Hide the button. // noBrowse(); return; } String txt; try { txt = openPublicKey(applet); } catch (RuntimeException re) { // If this call fails, the applet is dead. It is most likely // not loading due to Java support being disabled. // noBrowse(); return; } if (txt == null) { txt = ""; } browse.setEnabled(true); if (appletErrorInvalidKey == null) { appletErrorInvalidKey = getErrorInvalidKey(applet); appletErrorSecurity = getErrorSecurity(applet); } if (appletErrorInvalidKey.equals(txt)) { new ErrorDialog(Util.C.invalidSshKeyError()).center(); return; } if (appletErrorSecurity.equals(txt)) { new ErrorDialog(Util.C.invalidSshKeyError()).center(); return; } addTxt.setText(txt); addNew.setFocus(true); } private void noBrowse() { if (applet != null) { applet.getParentElement().removeChild(applet); applet = null; } browse.setVisible(false); new ErrorDialog(Util.C.sshJavaAppletNotAvailable()).center(); } private static native boolean isAppletRunning(Element keyapp) /*-{ return keyapp['openPublicKey'] ? true : false }-*/; private static native String openPublicKey(Element keyapp) /*-{ var r = keyapp.openPublicKey(); return r == null ? null : ''+r; }-*/; private static native String getErrorInvalidKey(Element keyapp) /*-{ return ''+keyapp.getErrorInvalidKey(); }-*/; private static native String getErrorSecurity(Element keyapp) /*-{ return ''+keyapp.getErrorSecurity(); }-*/; void doAddNew() { final String txt = addTxt.getText(); if (txt != null && txt.length() > 0) { addNew.setEnabled(false); Util.ACCOUNT_SEC.addSshKey(txt, new GerritCallback<AccountSshKey>() { public void onSuccess(final AccountSshKey result) { addNew.setEnabled(true); addTxt.setText(""); keys.addOneKey(result); if (!keys.isVisible()) { showAddKeyBlock(false); setKeyTableVisible(true); keys.updateDeleteButton(); } } @Override public void onFailure(final Throwable caught) { addNew.setEnabled(true); if (isInvalidSshKey(caught)) { new ErrorDialog(Util.C.invalidSshKeyError()).center(); } else { super.onFailure(caught); } } private boolean isInvalidSshKey(final Throwable caught) { if (caught instanceof InvalidSshKeyException) { return true; } return caught instanceof RemoteJsonException && InvalidSshKeyException.MESSAGE.equals(caught.getMessage()); } }); } } @Override protected void onLoad() { super.onLoad(); Util.ACCOUNT_SEC.mySshKeys(new GerritCallback<List<AccountSshKey>>() { public void onSuccess(final List<AccountSshKey> result) { keys.display(result); if (result.isEmpty() && keys.isVisible()) { showAddKeyBlock(true); } } }); Gerrit.SYSTEM_SVC.daemonHostKeys(new GerritCallback<List<SshHostKey>>() { public void onSuccess(final List<SshHostKey> result) { serverKeys.clear(); for (final SshHostKey keyInfo : result) { serverKeys.add(new SshHostKeyPanel(keyInfo)); } } }); } @Override protected void onUnload() { if (appletLoadTimer != null) { appletLoadTimer.cancel(); appletLoadTimer = null; } super.onUnload(); } private void showAddKeyBlock(final boolean show) { showAddKeyBlock.setVisible(!show); addKeyBlock.setVisible(show); } private class SshKeyTable extends FancyFlexTable<AccountSshKey> { private ValueChangeHandler<Boolean> updateDeleteHandler; SshKeyTable() { table.setWidth(""); table.setText(0, 2, Util.C.sshKeyStatus()); table.setText(0, 3, Util.C.sshKeyAlgorithm()); table.setText(0, 4, Util.C.sshKeyKey()); table.setText(0, 5, Util.C.sshKeyComment()); final FlexCellFormatter fmt = table.getFlexCellFormatter(); fmt.addStyleName(0, 1, Gerrit.RESOURCES.css().iconHeader()); fmt.addStyleName(0, 2, Gerrit.RESOURCES.css().dataHeader()); fmt.addStyleName(0, 3, Gerrit.RESOURCES.css().dataHeader()); fmt.addStyleName(0, 4, Gerrit.RESOURCES.css().dataHeader()); fmt.addStyleName(0, 5, Gerrit.RESOURCES.css().dataHeader()); updateDeleteHandler = new ValueChangeHandler<Boolean>() { @Override public void onValueChange(ValueChangeEvent<Boolean> event) { updateDeleteButton(); } }; } void deleteChecked() { final HashSet<AccountSshKey.Id> ids = new HashSet<AccountSshKey.Id>(); for (int row = 1; row < table.getRowCount(); row++) { final AccountSshKey k = getRowItem(row); if (k != null && ((CheckBox) table.getWidget(row, 1)).getValue()) { ids.add(k.getKey()); } } if (ids.isEmpty()) { updateDeleteButton(); } else { Util.ACCOUNT_SEC.deleteSshKeys(ids, new GerritCallback<VoidResult>() { public void onSuccess(final VoidResult result) { for (int row = 1; row < table.getRowCount();) { final AccountSshKey k = getRowItem(row); if (k != null && ids.contains(k.getKey())) { table.removeRow(row); } else { row++; } } if (table.getRowCount() == 1) { display(Collections.<AccountSshKey> emptyList()); } else { updateDeleteButton(); } } }); } } void display(final List<AccountSshKey> result) { if (result.isEmpty()) { setKeyTableVisible(false); showAddKeyBlock(true); } else { while (1 < table.getRowCount()) table.removeRow(table.getRowCount() - 1); for (final AccountSshKey k : result) { addOneKey(k); } setKeyTableVisible(true); deleteKey.setEnabled(false); } } void addOneKey(final AccountSshKey k) { final FlexCellFormatter fmt = table.getFlexCellFormatter(); final int row = table.getRowCount(); table.insertRow(row); applyDataRowStyle(row); final CheckBox sel = new CheckBox(); sel.addValueChangeHandler(updateDeleteHandler); table.setWidget(row, 1, sel); if (k.isValid()) { table.setText(row, 2, ""); fmt.removeStyleName(row, 2, // Gerrit.RESOURCES.css().sshKeyPanelInvalid()); } else { table.setText(row, 2, Util.C.sshKeyInvalid()); fmt.addStyleName(row, 2, Gerrit.RESOURCES.css().sshKeyPanelInvalid()); } table.setText(row, 3, k.getAlgorithm()); CopyableLabel keyLabel = new CopyableLabel(k.getEncodedKey()); keyLabel.setPreviewText(elide(k.getEncodedKey(), 40)); table.setWidget(row, 4, keyLabel); table.setText(row, 5, k.getComment()); fmt.addStyleName(row, 1, Gerrit.RESOURCES.css().iconCell()); fmt.addStyleName(row, 4, Gerrit.RESOURCES.css().sshKeyPanelEncodedKey()); for (int c = 2; c <= 5; c++) { fmt.addStyleName(row, c, Gerrit.RESOURCES.css().dataCell()); } setRowItem(row, k); } void updateDeleteButton() { boolean on = false; for (int row = 1; row < table.getRowCount(); row++) { CheckBox sel = (CheckBox) table.getWidget(row, 1); if (sel.getValue()) { on = true; break; } } deleteKey.setEnabled(on); } } static String elide(final String s, final int len) { if (s == null || s.length() < len || len <= 10) { return s; } return s.substring(0, len - 10) + "..." + s.substring(s.length() - 10); } }
Remove unused import in SshPanel Change-Id: I8e32f3137fefb9b04dffa28ea14f6bd399190803 Signed-off-by: Shawn O. Pearce <[email protected]>
gerrit-gwtui/src/main/java/com/google/gerrit/client/account/SshPanel.java
Remove unused import in SshPanel
<ide><path>errit-gwtui/src/main/java/com/google/gerrit/client/account/SshPanel.java <ide> import com.google.gwt.user.client.ui.HTML; <ide> import com.google.gwt.user.client.ui.HasHorizontalAlignment; <ide> import com.google.gwt.user.client.ui.HorizontalPanel; <del>import com.google.gwt.user.client.ui.InlineLabel; <ide> import com.google.gwt.user.client.ui.Panel; <ide> import com.google.gwt.user.client.ui.RootPanel; <ide> import com.google.gwt.user.client.ui.VerticalPanel;
JavaScript
mit
d6b6da4534b286cf9bf86e8e4621924f282fcb24
0
pl12133/pl12133.github.io,pl12133/pl12133.github.io
/* eslint-disable no-unused-vars*/ import React, { Component } from 'react'; /* eslint-enable no-unused-vars*/ import { Grid, Row, Col, Jumbotron } from 'react-bootstrap'; import ScrimOverlay from 'components/ScrimOverlay/'; // Width is adjusted by -30px for bootstrap grid mergins const DemoVideo = ({overlayHeader, overlayText, href, videoSrc, fallbackImageSrc}) => ( <a href={href} style={ { display: 'block' } }> <ScrimOverlay header={overlayHeader} text={overlayText} style={ { width: 'calc(100% - 30px)' } } /> <video style={ { width: '100%' } } autoPlay loop poster={fallbackImageSrc} > <source src={videoSrc} type='video/webm' /> </video> </a> ); const JumboHeader = ({children}) => ( <Jumbotron style={ { paddingLeft: '10px', borderRadius: '2em', boxShadow: '10px 5px 5px #888888', margin: '0 15px' } } > <h2>{children}</h2> </Jumbotron> ); const containerStyles = { position: 'relative', display: 'inline-block', width: '30%', height: 'auto', marginTop: '2%' }; const Projects = () => ( <Grid> <Row> <Col xs={12}> <JumboHeader> {'A few things I\'ve been working on'} </JumboHeader> </Col> </Row> <Row style={ { marginTop: '1%' } }> <Col xs={6} md={4}> <DemoVideo overlayHeader={'React Solitaire'} overlayText={'A game of Solitaire written in React with Redux'} href={"https://pl12133.github.io/react-solitaire"} videoSrc={'dist/solitaire-demo.webm'} fallbackImageSrc={'dist/solitaire-demo.png'} /> </Col> <Col xs={6} md={4}> <DemoVideo overlayHeader={'watch-collection'} overlayText={'A personal watch collection'} href={'https://pl12133.github.io/watch-collection'} videoSrc={'dist/watch-collection-demo.webm'} fallbackImageSrc={'dist/watch-collection-demo.png'} /> </Col> <Col xs={6} md={4}> <DemoVideo overlayHeader={'node-twitch-clipper'} overlayText={'A module for creating clips from Twitch.tv VODs'} href={'https://pl12133.github.io/node-twitch-clipper-demo'} videoSrc={''} fallbackImageSrc={'dist/twitch-clipper-demo.png'} /> </Col> </Row> </Grid> ); export default Projects;
src/containers/Projects/index.js
/* eslint-disable no-unused-vars*/ import React, { Component } from 'react'; /* eslint-enable no-unused-vars*/ import { Grid, Row, Col, Jumbotron } from 'react-bootstrap'; import ScrimOverlay from 'components/ScrimOverlay/'; // Width is adjusted by -30px for bootstrap grid mergins const DemoVideo = ({overlayText, href, videoSrc, fallbackImageSrc}) => ( <a href={href} style={ { display: 'block' } }> <ScrimOverlay text={overlayText} style={ { width: 'calc(100% - 30px)' } } /> <video style={ { width: '100%' } } autoPlay loop poster={fallbackImageSrc} > <source src={videoSrc} type='video/webm' /> </video> </a> ); const JumboHeader = ({children}) => ( <Jumbotron style={ { paddingLeft: '10px', borderRadius: '2em', boxShadow: '10px 5px 5px #888888', margin: '0 15px' } } > <h2>{children}</h2> </Jumbotron> ); const containerStyles = { position: 'relative', display: 'inline-block', width: '30%', height: 'auto', marginTop: '2%' }; const Projects = () => ( <Grid> <Row> <Col xs={12}> <JumboHeader> {'A few things I\'ve been working on'} </JumboHeader> </Col> </Row> <Row style={ { marginTop: '1%' } }> <Col xs={6} md={4}> <DemoVideo overlayText={'React Solitaire'} href={"https://pl12133.github.io/react-solitaire"} videoSrc={'dist/solitaire-demo.webm'} fallbackImageSrc={'dist/solitaire-demo.png'} /> </Col> <Col xs={6} md={4}> <DemoVideo overlayText={'watch-collection'} href={'https://pl12133.github.io/watch-collection'} videoSrc={'dist/watch-collection-demo.webm'} fallbackImageSrc={'dist/watch-collection-demo.png'} /> </Col> <Col xs={6} md={4}> <DemoVideo overlayText={'node-twitch-clipper'} href={'https://pl12133.github.io/node-twitch-clipper-demo'} videoSrc={''} fallbackImageSrc={'dist/twitch-clipper-demo.png'} /> </Col> </Row> </Grid> ); export default Projects;
Add description text for projects
src/containers/Projects/index.js
Add description text for projects
<ide><path>rc/containers/Projects/index.js <ide> import ScrimOverlay from 'components/ScrimOverlay/'; <ide> <ide> // Width is adjusted by -30px for bootstrap grid mergins <del>const DemoVideo = ({overlayText, href, videoSrc, fallbackImageSrc}) => ( <add>const DemoVideo = ({overlayHeader, overlayText, href, videoSrc, fallbackImageSrc}) => ( <ide> <a href={href} style={ { display: 'block' } }> <ide> <ScrimOverlay <add> header={overlayHeader} <ide> text={overlayText} <ide> style={ { width: 'calc(100% - 30px)' } } <ide> /> <ide> <Row style={ { marginTop: '1%' } }> <ide> <Col xs={6} md={4}> <ide> <DemoVideo <del> overlayText={'React Solitaire'} <add> overlayHeader={'React Solitaire'} <add> overlayText={'A game of Solitaire written in React with Redux'} <ide> href={"https://pl12133.github.io/react-solitaire"} <ide> videoSrc={'dist/solitaire-demo.webm'} <ide> fallbackImageSrc={'dist/solitaire-demo.png'} <ide> </Col> <ide> <Col xs={6} md={4}> <ide> <DemoVideo <del> overlayText={'watch-collection'} <add> overlayHeader={'watch-collection'} <add> overlayText={'A personal watch collection'} <ide> href={'https://pl12133.github.io/watch-collection'} <ide> videoSrc={'dist/watch-collection-demo.webm'} <ide> fallbackImageSrc={'dist/watch-collection-demo.png'} <ide> </Col> <ide> <Col xs={6} md={4}> <ide> <DemoVideo <del> overlayText={'node-twitch-clipper'} <add> overlayHeader={'node-twitch-clipper'} <add> overlayText={'A module for creating clips from Twitch.tv VODs'} <ide> href={'https://pl12133.github.io/node-twitch-clipper-demo'} <ide> videoSrc={''} <ide> fallbackImageSrc={'dist/twitch-clipper-demo.png'}
JavaScript
mit
93a77c5819f7b9544253130c33800672264fb495
0
burib/jiraCards
var request = require('request'), fs = require('fs'), swig = require('swig'), config = require('./config.json'), host = config.host, restPath = config.restPath || "/rest/api/latest/issue/", userName = config.username, password = config.password, url = "https://" + userName + ":" + password + "@" + host + restPath, tickets = config.ticketKeys, cards = [], numberOfRequests = 0; tickets.forEach(function (value) { request({ url: url + value, strictSSL: false, json: true }, function (error, response, body) { if (!error && response.statusCode == 200) { cards.push({ key: body.key, issueType: body.fields.issuetype.name, title: body.fields.summary, estimation: toDaysAndHours(body.fields.timetracking.originalEstimateSeconds), description: body.fields.description, assignee: { name: body.fields.assignee.displayName, avatar: body.fields.assignee.avatarUrls["48x48"] } }); } else { console.log(error); } if (tickets.length - 1 <= numberOfRequests++) { createCards(cards); console.log("\n"); console.log(cards.length + '/' + tickets.length + ' JIRA tickets has been successfully requested through JIRA REST API.'); } }); }); function createCards(cards) { function renderTemplate() { return swig.renderFile('jiracard_template.html', { cards: cards }); } function createCardsHtml() { fs.writeFile("public/index.html", renderTemplate(), function (err) { if (err) { console.log(err); } else { console.log(cards.length + " JIRA cards generated."); } console.log("\n"); }); } createCardsHtml(); } function toDaysAndHours(seconds) { var _seconds = seconds ? seconds : 0; var numdays = Math.floor(_seconds / 28800), numhours = Math.floor((_seconds % 28800) / 3600), time = numhours !== 0 ? (numdays + " d " + numhours + " h") : numdays + " d"; return _seconds != 0 ? time : ''; }
index.js
var request = require('request'), fs = require('fs'), swig = require('swig'), config = require('./config.json'), host = config.host, restPath = config.restPath || "/rest/api/latest/issue/", userName = config.username, password = config.password, url = "https://" + userName + ":" + password + "@" + host + restPath, tickets = config.ticketKeys, cards = [], numberOfRequests = 0; tickets.forEach(function (value) { console.log(url + value); request({ url: url + value, strictSSL: false, json: true }, function (error, response, body) { if (!error && response.statusCode == 200) { cards.push({ key: body.key, issueType: body.fields.issuetype.name, title: body.fields.summary, estimation: toDaysAndHours(body.fields.timetracking.originalEstimateSeconds), description: body.fields.description, assignee: { name: body.fields.assignee.displayName, avatar: body.fields.assignee.avatarUrls["48x48"] } }); } else { console.log(error); } if (tickets.length - 1 <= numberOfRequests++) { createCards(cards); console.log("\n"); console.log(cards.length + '/' + tickets.length + ' JIRA tickets has been successfully requested through JIRA REST API.'); } }); }); function createCards(cards) { function renderTemplate() { return swig.renderFile('jiracard_template.html', { cards: cards }); } function createCardsHtml() { fs.writeFile("public/index.html", renderTemplate(), function (err) { if (err) { console.log(err); } else { console.log(cards.length + " JIRA cards generated."); } console.log("\n"); }); } createCardsHtml(); } function toDaysAndHours(seconds) { var _seconds = seconds ? seconds : 0; var numdays = Math.floor(_seconds / 28800), numhours = Math.floor((_seconds % 28800) / 3600), time = numhours !== 0 ? (numdays + " d " + numhours + " h") : numdays + " d"; return _seconds != 0 ? time : ''; }
remove console.log
index.js
remove console.log
<ide><path>ndex.js <ide> numberOfRequests = 0; <ide> <ide> tickets.forEach(function (value) { <del> console.log(url + value); <ide> request({ <ide> url: url + value, <ide> strictSSL: false,
Java
agpl-3.0
665784a5132190c1bb4c7bca03129816c57f2621
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
8196b36e-2e60-11e5-9284-b827eb9e62be
hello.java
8191392a-2e60-11e5-9284-b827eb9e62be
8196b36e-2e60-11e5-9284-b827eb9e62be
hello.java
8196b36e-2e60-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>8191392a-2e60-11e5-9284-b827eb9e62be <add>8196b36e-2e60-11e5-9284-b827eb9e62be
Java
mit
ad9b5acc0e7c9a9159be4ab884560eb01d5141f0
0
jurgendl/swing-easy,jurgendl/swing-easy,jurgendl/swing-easy
package org.swingeasy; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Frame; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import java.util.regex.Pattern; import javax.swing.DropMode; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.JWindow; import javax.swing.ScrollPaneConstants; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import org.apache.commons.lang.StringUtils; import org.swingeasy.EComponentPopupMenu.ReadableComponent; import org.swingeasy.system.SystemSettings; import org.swingeasy.table.editor.BooleanTableCellEditor; import org.swingeasy.table.editor.ColorTableCellEditor; import org.swingeasy.table.editor.DateTableCellEditor; import org.swingeasy.table.editor.NumberTableCellEditor; import org.swingeasy.table.renderer.BooleanTableCellRenderer; import org.swingeasy.table.renderer.ByteArrayTableCellRenderer; import org.swingeasy.table.renderer.ColorTableCellRenderer; import org.swingeasy.table.renderer.DateTableCellRenderer; import org.swingeasy.table.renderer.NumberTableCellRenderer; import ca.odell.glazedlists.BasicEventList; import ca.odell.glazedlists.EventList; import ca.odell.glazedlists.FilterList; import ca.odell.glazedlists.GlazedLists; import ca.odell.glazedlists.ListSelection; import ca.odell.glazedlists.SortedList; import ca.odell.glazedlists.gui.AbstractTableComparatorChooser; import ca.odell.glazedlists.gui.TableFormat; import ca.odell.glazedlists.matchers.AbstractMatcherEditor; import ca.odell.glazedlists.matchers.Matcher; import ca.odell.glazedlists.swing.DefaultEventSelectionModel; import ca.odell.glazedlists.swing.DefaultEventTableModel; import ca.odell.glazedlists.swing.EventTableColumnModel; import ca.odell.glazedlists.swing.SortableRenderer; import ca.odell.glazedlists.swing.TableComparatorChooser; /** * @author Jurgen * * @see http://www.chka.de/swing/table/faq.html */ public class ETable<T> extends JTable implements ETableI<T>, Reorderable, Iterable<ETableRecord<T>>, ReadableComponent { protected class EFiltering { /** * JDOC */ protected class FilterPopup extends JWindow { /** * JDOC */ protected class RecordMatcher implements Matcher<ETableRecord<T>> { protected final Map<Integer, Pattern> filters = new HashMap<Integer, Pattern>(); protected RecordMatcher(int column, String text) { if (text != null) { this.filters.put(column, Pattern.compile(text, Pattern.CASE_INSENSITIVE)); } } protected RecordMatcher(Map<Integer, String> popupFilters) { for (Map.Entry<Integer, String> entry : popupFilters.entrySet()) { if (entry.getValue() != null) { this.filters.put(entry.getKey(), Pattern.compile(entry.getValue(), Pattern.CASE_INSENSITIVE)); } } } /** * @see ca.odell.glazedlists.matchers.Matcher#matches(java.lang.Object) */ @Override public boolean matches(ETableRecord<T> item) { for (Map.Entry<Integer, Pattern> entry : this.filters.entrySet()) { String value = item.getStringValue(entry.getKey()); if (!entry.getValue().matcher(value).find()) { return false; } } return true; } } private static final long serialVersionUID = 5033445579635687866L; protected JTextField popupTextfield = new JTextField(); protected int popupForColumn = -1; protected Map<Integer, String> popupFilters = new HashMap<Integer, String>(); protected FilterPopup(Frame frame) { super(frame); this.popupTextfield.setBackground(new Color(246, 243, 149)); this.getContentPane().add(this.popupTextfield, BorderLayout.CENTER); this.popupTextfield.setFocusTraversalKeysEnabled(false); this.popupTextfield.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { FilterPopup.this.setVisible(false); } }); this.popupTextfield.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { // preview filtering System.out.println("preview filter " + FilterPopup.this.popupTextfield.getText()); //$NON-NLS-1$ ETable.this.filtering.matcherEditor.fire(new RecordMatcher(FilterPopup.this.popupForColumn, FilterPopup.this.popupTextfield.getText())); } else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { // revert filtering, close System.out.println("revert filter"); //$NON-NLS-1$ ETable.this.filtering.matcherEditor.fire(new RecordMatcher(FilterPopup.this.popupForColumn, FilterPopup.this.popupFilters .get(FilterPopup.this.popupForColumn))); FilterPopup.this.setVisible(false); } else if (e.getKeyCode() == KeyEvent.VK_TAB) { // commit filtering FilterPopup.this.popupFilters.put(FilterPopup.this.popupForColumn, FilterPopup.this.popupTextfield.getText()); System.out.println("filter " + FilterPopup.this.popupFilters); //$NON-NLS-1$ ETable.this.filtering.matcherEditor.fire(new RecordMatcher(FilterPopup.this.popupFilters)); FilterPopup.this.setVisible(false); } else { // } } }); } /** * JDOC * * @param p */ protected void activate(Point p) { this.popupForColumn = ETable.this.getTableHeader().columnAtPoint(p); String filter = this.popupFilters.get(this.popupForColumn); this.popupTextfield.setText(filter); Rectangle headerRect = ETable.this.getTableHeader().getHeaderRect(this.popupForColumn); Point pt = ETable.this.getLocationOnScreen(); pt.translate(headerRect.x - 1, -headerRect.height - 1); this.setLocation(pt); this.setSize(headerRect.width, headerRect.height); this.toFront(); this.setVisible(true); this.requestFocusInWindow(); this.popupTextfield.requestFocusInWindow(); } /** * JDOC */ public void clear() { this.popupFilters.clear(); this.popupForColumn = -1; } } /** * JDOC */ protected class FilterPopupActivate extends MouseAdapter { /** * * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent) */ @Override public void mouseClicked(MouseEvent e) { ETable.this.filtering.mouseClicked(e); } } protected RecordMatcherEditor<T> matcherEditor; protected FilterList<ETableRecord<T>> filteredRecords; protected FilterPopup filterPopup; protected EventList<ETableRecord<T>> source; protected EFiltering(EventList<ETableRecord<T>> source, AbstractMatcherEditor<ETableRecord<T>> matcher) { this.source = source; if (matcher != null) { // we do matching ourselves this.filteredRecords = new FilterList<ETableRecord<T>>(source, matcher); return; } if (!ETable.this.cfg.isFilterable()) { return; } // default matching this.matcherEditor = new RecordMatcherEditor<T>(); this.filteredRecords = new FilterList<ETableRecord<T>>(source, this.matcherEditor); } protected void clear() { if (!ETable.this.cfg.isFilterable()) { return; } this.getFilterPopup().clear(); } protected FilterPopup getFilterPopup() { if (!ETable.this.cfg.isFilterable()) { return null; } if (this.filterPopup == null) { this.filterPopup = new FilterPopup(ETable.this.getFrame(ETable.this)); } return this.filterPopup; } protected EventList<ETableRecord<T>> getRecords() { if (this.filteredRecords == null) { return this.source; } return this.filteredRecords; } protected void install() { if (!ETable.this.cfg.isFilterable()) { return; } ETable.this.getTableHeader().addMouseListener(new FilterPopupActivate()); } protected void mouseClicked(MouseEvent e) { if (!ETable.this.cfg.isFilterable()) { return; } if ((e.getClickCount() == 1) && (e.getButton() == MouseEvent.BUTTON3)) { this.getFilterPopup().activate(e.getPoint()); } } } protected class ESorting { protected TableComparatorChooser<ETableRecord<T>> tableSorter; protected SortedList<ETableRecord<T>> sortedRecords; protected EventList<ETableRecord<T>> source; protected ESorting(EventList<ETableRecord<T>> source) { this.source = source; if (!ETable.this.cfg.isSortable()) { return; } this.sortedRecords = new SortedList<ETableRecord<T>>(source, null); } protected void dispose() { if (!ETable.this.cfg.isSortable()) { return; } this.tableSorter.dispose(); } protected EventList<ETableRecord<T>> getRecords() { if (!ETable.this.cfg.isSortable()) { return this.source; } return this.sortedRecords; } protected void install() { if (!ETable.this.cfg.isSortable()) { return; } this.tableSorter = TableComparatorChooser.install(ETable.this, this.sortedRecords, AbstractTableComparatorChooser.MULTIPLE_COLUMN_MOUSE_WITH_UNDO, ETable.this.tableFormat); } protected void sort(int col) { if (!ETable.this.cfg.isSortable()) { return; } this.tableSorter.clearComparator(); this.tableSorter.appendComparator(col, 0, false); } protected void unsort() { if (!ETable.this.cfg.isSortable()) { return; } this.tableSorter.clearComparator(); } } public class ETableModel extends DefaultEventTableModel<ETableRecord<T>> { private static final long serialVersionUID = -8936359559294414836L; protected ETableModel(EventList<ETableRecord<T>> source, TableFormat<? super ETableRecord<T>> tableFormat) { super(source, tableFormat); } /** * * @see javax.swing.table.AbstractTableModel#fireTableCellUpdated(int, int) */ @Override public void fireTableCellUpdated(int row, int column) { super.fireTableCellUpdated(row, column); }; /** * * @see ca.odell.glazedlists.swing.EventTableModel#getColumnClass(int) */ @Override public Class<?> getColumnClass(int columnIndex) { Class<?> clas = ETable.this.tableFormat.getColumnClass(columnIndex); // System.out.println("ETableModel.getColumnClass(" + columnIndex + ")=" + clas); return clas; } } public static abstract class Filter<T> extends RecordMatcherEditor<T> implements Matcher<ETableRecord<T>> { public void fire() { this.fire(this); } } /** * JDOC */ protected static class RecordMatcherEditor<T> extends AbstractMatcherEditor<ETableRecord<T>> { protected void fire(Matcher<ETableRecord<T>> matcher) { this.fireChanged(matcher); } } /** * @see http://publicobject.com/glazedlistsdeveloper/ */ protected class VerticalHeaderRenderer extends VerticalTableHeaderCellRenderer implements SortableRenderer { private static final long serialVersionUID = 2995810245364522046L; protected Icon sortIcon = null; protected final static double DEGREE_90 = (90.0 * Math.PI) / 180.0; protected Map<Icon, Icon> rotatedIconsCache = new HashMap<Icon, Icon>(); /** * Creates a rotated version of the input image. * * @param c The component to get properties useful for painting, e.g. the foreground or background color. * @param icon the image to be rotated. * @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we will mod it with 360 before using it. * * @return the image after rotating. * * @see http://www.jidesoft.com/blog/2008/02/29/rotate-an-icon-in-java/ */ protected ImageIcon createRotatedImage(Component c, Icon icon, double rotatedAngle) { // convert rotatedAngle to a value from 0 to 360 double originalAngle = rotatedAngle % 360; if ((rotatedAngle != 0) && (originalAngle == 0)) { originalAngle = 360.0; } // convert originalAngle to a value from 0 to 90 double angle = originalAngle % 90; if ((originalAngle != 0.0) && (angle == 0.0)) { angle = 90.0; } double radian = Math.toRadians(angle); int iw = icon.getIconWidth(); int ih = icon.getIconHeight(); int w; int h; if (((originalAngle >= 0) && (originalAngle <= 90)) || ((originalAngle > 180) && (originalAngle <= 270))) { w = (int) ((iw * Math.sin(VerticalHeaderRenderer.DEGREE_90 - radian)) + (ih * Math.sin(radian))); h = (int) ((iw * Math.sin(radian)) + (ih * Math.sin(VerticalHeaderRenderer.DEGREE_90 - radian))); } else { w = (int) ((ih * Math.sin(VerticalHeaderRenderer.DEGREE_90 - radian)) + (iw * Math.sin(radian))); h = (int) ((ih * Math.sin(radian)) + (iw * Math.sin(VerticalHeaderRenderer.DEGREE_90 - radian))); } BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics g = image.getGraphics(); Graphics2D g2d = (Graphics2D) g.create(); // calculate the center of the icon. int cx = iw / 2; int cy = ih / 2; // move the graphics center point to the center of the icon. g2d.translate(w / 2, h / 2); // rotate the graphcis about the center point of the icon g2d.rotate(Math.toRadians(originalAngle)); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); icon.paintIcon(c, g2d, -cx, -cy); g2d.dispose(); return new ImageIcon(image); } /** * * @see org.swingeasy.VerticalTableHeaderCellRenderer#getIcon(javax.swing.JTable, int) */ @Override protected Icon getIcon(JTable table, int column) { return this.sortIcon; } /** * * @see ca.odell.glazedlists.swing.SortableRenderer#setSortIcon(javax.swing.Icon) */ @Override public void setSortIcon(Icon sortIcon) { if (sortIcon != null) { Icon found = this.rotatedIconsCache.get(sortIcon); if (found == null) { found = this.createRotatedImage(this, sortIcon, 90.0); this.rotatedIconsCache.put(sortIcon, found); } this.sortIcon = found; } else { this.sortIcon = null; } } } private static final long serialVersionUID = 6515690492295488815L; protected final EventList<ETableRecord<T>> records; protected final DefaultEventTableModel<ETableRecord<T>> tableModel; protected final DefaultEventSelectionModel<ETableRecord<T>> tableSelectionModel; protected final EFiltering filtering; protected final ESorting sorting; protected final ETableConfig cfg; protected ETableHeaders<T> tableFormat; protected static final String TABLE_RENDERERS_DIR = "org.swingeasy.table.renderer"; protected static final String TABLE_EDITORS_DIR = "org.swingeasy.table.editor"; /** * use other constructors instead */ protected ETable() { this.filtering = null; this.sorting = null; this.cfg = null; this.records = null; this.tableModel = null; this.tableSelectionModel = null; } public ETable(ETableConfig configuration) { this(configuration, null); } public ETable(ETableConfig configuration, Filter<T> matcher) { this.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON3) { ETable.this.selectCell(new Point(e.getX(), e.getY())); } } }); this.cfg = configuration; this.cfg.lock(); if (this.cfg.isVertical()) { this.getTableHeader().setDefaultRenderer(new VerticalHeaderRenderer()); } if (this.cfg.isDraggable()) { this.setDragEnabled(true); this.setDropMode(DropMode.INSERT_ROWS); this.setTransferHandler(new TableRowTransferHandler(this)); } this.setColumnModel(new EventTableColumnModel<TableColumn>(new BasicEventList<TableColumn>())); this.records = (this.cfg.isThreadSafe() ? GlazedLists.threadSafeList(new BasicEventList<ETableRecord<T>>()) : new BasicEventList<ETableRecord<T>>()); this.sorting = new ESorting(this.records); this.tableFormat = new ETableHeaders<T>(); this.filtering = new EFiltering(this.sorting.getRecords(), matcher); this.tableModel = new ETableModel(this.filtering.getRecords(), this.tableFormat); this.setModel(this.tableModel); this.tableSelectionModel = new DefaultEventSelectionModel<ETableRecord<T>>(this.filtering.getRecords()); this.tableSelectionModel.setSelectionMode(ListSelection.MULTIPLE_INTERVAL_SELECTION_DEFENSIVE); this.setColumnSelectionAllowed(true); this.setRowSelectionAllowed(true); this.setSelectionModel(this.tableSelectionModel); this.sorting.install(); this.filtering.install(); this.getTableHeader().setReorderingAllowed(this.cfg.isReorderable()); this.getTableHeader().setResizingAllowed(this.cfg.isResizable()); UIUtils.registerLocaleChangeListener((EComponentI) this); if (this.cfg.isDefaultPopupMenu()) { this.installPopupMenuAction(EComponentPopupMenu.installPopupMenu(this)); } } /** * * @see org.swingeasy.ETableI#addRecord(org.swingeasy.ETableRecord) */ @Override public void addRecord(final ETableRecord<T> record) { this.records.add(record); } /** * * @see org.swingeasy.ETableI#addRecords(java.util.Collection) */ @Override public void addRecords(final Collection<ETableRecord<T>> r) { this.records.addAll(r); } /** * add rowheader to scrollpane, 4 digit number */ public void addRowHeader(JScrollPane scrollpane) { this.addRowHeader(scrollpane, 4); } /** * add rowheader to scrollpane */ public void addRowHeader(JScrollPane scrollpane, int cw) { RowNumberTable rowTable = this.getRowHeader(cw); scrollpane.setRowHeaderView(rowTable); scrollpane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, rowTable.getTableHeader()); } /** * * @see org.swingeasy.ETableI#clear() */ @Override public void clear() { this.tableSelectionModel.clearSelection(); this.records.clear(); this.sorting.dispose(); this.tableModel.setTableFormat(new ETableHeaders<T>()); this.filtering.clear(); } /** * * @see org.swingeasy.EComponentPopupMenu.ReadableComponent#copy(java.awt.event.ActionEvent) */ @Override public void copy(ActionEvent e) { StringBuilder sb = new StringBuilder(); for (Object cell : this.getSelectedCells()) { sb.append(String.valueOf(cell)).append(SystemSettings.getNewline()); } EComponentPopupMenu.copyToClipboard(sb.toString()); } /** * * @see javax.swing.JTable#createDefaultEditors() */ @SuppressWarnings("unchecked") @Override protected void createDefaultEditors() { super.createDefaultEditors(); this.defaultEditorsByColumnClass.put(Boolean.class, new javax.swing.UIDefaults.ProxyLazyValue(BooleanTableCellEditor.class.getName())); this.defaultEditorsByColumnClass.put(Date.class, new javax.swing.UIDefaults.ProxyLazyValue(DateTableCellEditor.class.getName())); this.defaultEditorsByColumnClass.put(Color.class, new javax.swing.UIDefaults.ProxyLazyValue(ColorTableCellEditor.class.getName())); this.defaultEditorsByColumnClass.put(Number.class, new javax.swing.UIDefaults.ProxyLazyValue(NumberTableCellEditor.class.getName())); } /** * * @see javax.swing.JTable#createDefaultRenderers() */ @SuppressWarnings("unchecked") @Override protected void createDefaultRenderers() { super.createDefaultRenderers(); this.defaultRenderersByColumnClass.put(Boolean.class, new javax.swing.UIDefaults.ProxyLazyValue(BooleanTableCellRenderer.class.getName())); this.defaultRenderersByColumnClass.put(Date.class, new javax.swing.UIDefaults.ProxyLazyValue(DateTableCellRenderer.class.getName())); this.defaultRenderersByColumnClass.put(Color.class, new javax.swing.UIDefaults.ProxyLazyValue(ColorTableCellRenderer.class.getName())); this.defaultRenderersByColumnClass.put(Number.class, new javax.swing.UIDefaults.ProxyLazyValue(NumberTableCellRenderer.class.getName())); this.defaultRenderersByColumnClass.put(Float.class, new javax.swing.UIDefaults.ProxyLazyValue(NumberTableCellRenderer.class.getName())); this.defaultRenderersByColumnClass.put(Double.class, new javax.swing.UIDefaults.ProxyLazyValue(NumberTableCellRenderer.class.getName())); this.defaultRenderersByColumnClass.put(byte[].class, new javax.swing.UIDefaults.ProxyLazyValue(ByteArrayTableCellRenderer.class.getName())); this.defaultRenderersByColumnClass.put(Byte[].class, new javax.swing.UIDefaults.ProxyLazyValue(ByteArrayTableCellRenderer.class.getName())); } /** * * @see javax.swing.JTable#createDefaultTableHeader() */ @Override protected JTableHeader createDefaultTableHeader() { JTableHeader jTableHeader = new JTableHeader(this.columnModel) { private static final long serialVersionUID = -378778832166135907L; @Override public String getToolTipText(MouseEvent e) { Point p = e.getPoint(); int index = this.columnModel.getColumnIndexAtX(p.x); if (index == -1) { return null; } String headerValue = String.valueOf(ETable.this.getSimpleThreadSafeInterface().getColumnValueAtVisualColumn(index)); if (ETable.this.cfg.isFilterable()) { String filter = ETable.this.filtering.getFilterPopup().popupFilters.get(index); if ((filter != null) && (filter.trim().length() > 0)) { headerValue += "<br/>" + "filter: '" + filter + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } else { headerValue += "<br/>" + "no filter"; //$NON-NLS-1$ //$NON-NLS-2$ } headerValue += "<br/><br/>right click to edit filter<br/>enter to preview filter<br/>tab to accept filter"; //$NON-NLS-1$ } return "<html><body>" + headerValue + "</body></html>"; //$NON-NLS-1$ //$NON-NLS-2$ } }; return jTableHeader; } /** * @see javax.swing.JTable#getCellRenderer(int, int) */ @Override public TableCellRenderer getCellRenderer(int row, int column) { return super.getCellRenderer(row, column); } /** * @see javax.swing.JTable#getColumnClass(int) */ @Override public Class<?> getColumnClass(int columnIndex) { Class<?> clas = super.getColumnClass(columnIndex); // System.out.println("ETableHeaders.getColumnClass(" + columnIndex + ")=" + clas); return clas; } /** * * @see org.swingeasy.ETableI#getColumnValueAtVisualColumn(int) */ @Override public Object getColumnValueAtVisualColumn(int i) { return this.getColumnModel().getColumn(i).getHeaderValue(); } /** * * @see javax.swing.JTable#getDefaultEditor(java.lang.Class) */ @Override public TableCellEditor getDefaultEditor(Class<?> columnClass) { TableCellEditor de = super.getDefaultEditor(columnClass); if (de instanceof EComponentI) { UIUtils.registerLocaleChangeListener(EComponentI.class.cast(de)); // } else if (de instanceof Component) { // UIUtils.registerLocaleChangeListener(Component.class.cast(de)); } return de; } /** * * @see javax.swing.JTable#getDefaultRenderer(java.lang.Class) */ @Override public TableCellRenderer getDefaultRenderer(Class<?> columnClass) { TableCellRenderer dr = super.getDefaultRenderer(columnClass); if (dr instanceof EComponentI) { UIUtils.registerLocaleChangeListener(EComponentI.class.cast(dr)); // } else if (dr instanceof Component) { // UIUtils.registerLocaleChangeListener(Component.class.cast(dr)); } return dr; } /** * JDOC * * @param comp * @return */ protected Frame getFrame(Component comp) { if (comp == null) { comp = this; } if (comp.getParent() instanceof Frame) { return (Frame) comp.getParent(); } return this.getFrame(comp.getParent()); } /** * * @see org.swingeasy.ETableI#getHeadernames() */ @Override public List<String> getHeadernames() { List<String> columnNames = this.tableFormat.getColumnNames(); return columnNames; } /** * gets tableFormat * * @return Returns the tableFormat. */ public ETableHeaders<T> getHeaders() { return this.tableFormat; } /** * * @see org.swingeasy.HasParentComponent#getParentComponent() */ @Override public JComponent getParentComponent() { return this; } /** * * @see org.swingeasy.ETableI#getRecordAtVisualRow(int) */ @Override public ETableRecord<T> getRecordAtVisualRow(int i) { return this.filtering.getRecords().get(i); } /** * * @see org.swingeasy.ETableI#getRecords() */ @Override public List<ETableRecord<T>> getRecords() { return this.filtering.getRecords(); } /** * @see #getRowHeader() */ public RowNumberTable getRowHeader() { return this.getRowHeader(4); } /** * gets row header that can be added to the RowHeaderView of a {@link JScrollPane} or can be docked WEST in a {@link BorderLayout} */ public RowNumberTable getRowHeader(int cw) { return new RowNumberTable(this, cw); } /** * * @see org.swingeasy.ETableI#getSelectedCell() */ @SuppressWarnings("unchecked") @Override public T getSelectedCell() { ETableRecord<T> record = this.getSelectedRecord(); if (record == null) { return null; } return (T) record.get(this.getSelectedColumn()); } /** * * @see org.swingeasy.ETableI#getSelectedCells() */ @Override public List<Object> getSelectedCells() { List<Object> cells = new ArrayList<Object>(); for (ETableRecord<T> record : this.getSelectedRecords()) { cells.add(record.get(this.getSelectedColumn())); } return cells; } /** * * @see org.swingeasy.ETableI#getSelectedRecord() */ @Override public ETableRecord<T> getSelectedRecord() { EventList<ETableRecord<T>> selected = this.tableSelectionModel.getSelected(); return selected.size() == 0 ? null : selected.iterator().next(); } /** * * @see org.swingeasy.ETableI#getSelectedRecords() */ @Override public List<ETableRecord<T>> getSelectedRecords() { return this.tableSelectionModel.getSelected(); } /** * JDOC * * @return */ @SuppressWarnings("unchecked") public ETable<T> getSimpleThreadSafeInterface() { try { return EventThreadSafeWrapper.getSimpleThreadSafeInterface(ETable.class, this, ETableI.class); } catch (Exception ex) { System.err.println(ex); return this; // no javassist } } /** * JDOC */ protected void installPopupMenuAction(JPopupMenu menu) { menu.addSeparator(); @SuppressWarnings({ "unchecked", "rawtypes" }) ServiceLoader<ETableExporter<T>> exporterService = (ServiceLoader) ServiceLoader.load(ETableExporter.class); Iterator<ETableExporter<T>> iterator = exporterService.iterator(); while (iterator.hasNext()) { try { ETableExporter<T> exporter = iterator.next(); ETableExporterAction<T> action = new ETableExporterAction<T>(exporter, this); menu.add(action); } catch (ServiceConfigurationError ex) { ex.printStackTrace(System.err); } } } /** * * @see javax.swing.JTable#isCellEditable(int, int) */ @Override public boolean isCellEditable(int row, int column) { return this.cfg.isEditable() && super.isCellEditable(row, column); } /** * threadsafe unmodifiable iterator * * @see java.lang.Iterable#iterator() */ @Override public Iterator<ETableRecord<T>> iterator() { return Collections.unmodifiableCollection(this.getRecords()).iterator(); } /** * * @see org.swingeasy.ETableI#packColumn(int) */ @Override public void packColumn(int vColIndex) { this.packColumn(vColIndex, 4); } /** * Sets the preferred width of the visible column specified by vColIndex. The column will be just wide enough to show the column head and the * widest cell in the column. margin pixels are added to the left and right (resulting in an additional width of 2*margin pixels). * * @param table * @param vColIndex * @param margin */ @Override public void packColumn(int vColIndex, int margin) { TableColumnModel colModel = this.getColumnModel(); TableColumn col = colModel.getColumn(vColIndex); int width = 0; // Get width of column header TableCellRenderer renderer = col.getHeaderRenderer(); if (renderer == null) { renderer = this.getTableHeader().getDefaultRenderer(); } Component comp = renderer.getTableCellRendererComponent(this, col.getHeaderValue(), false, false, 0, 0); width = comp.getPreferredSize().width; // Get maximum width of column data for (int r = 0; r < this.getRowCount(); r++) { renderer = this.getCellRenderer(r, vColIndex); comp = renderer.getTableCellRendererComponent(this, this.getValueAt(r, vColIndex), false, false, r, vColIndex); width = Math.max(width, comp.getPreferredSize().width); } // Add margin width += 2 * margin; // Set the width col.setPreferredWidth(width); col.setWidth(width); col.setMaxWidth(width); } /** * * @see javax.swing.JTable#prepareRenderer(javax.swing.table.TableCellRenderer, int, int) */ @Override public Component prepareRenderer(TableCellRenderer renderer, int rowIndex, int vColIndex) { Component c = this.super_prepareRenderer(renderer, rowIndex, vColIndex); if (c instanceof JLabel) { String text = JLabel.class.cast(c).getText(); JLabel.class.cast(c).setToolTipText(StringUtils.isNotBlank(text) ? text : null); } return c; } /** * * @see org.swingeasy.ETableI#removeAllRecords() */ @Override public void removeAllRecords() { this.records.clear(); } /** * * @see org.swingeasy.ETableI#removeRecord(org.swingeasy.ETableRecord) */ @Override public void removeRecord(final ETableRecord<T> record) { this.records.remove(record); } /** * * @see org.swingeasy.ETableI#removeRecordAtVisualRow(int) */ @Override public void removeRecordAtVisualRow(final int i) { this.records.remove(this.sorting.getRecords().get(i)); } /** * remove rowheader */ public void removeRowHeader(JScrollPane scrollpane) { if (scrollpane.getRowHeader().getView() instanceof RowNumberTable) { scrollpane.getRowHeader().removeAll(); scrollpane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, new JComponent() { private static final long serialVersionUID = 1L; }); } } /** * * @see org.swingeasy.Reorderable#reorder(int, int) */ @Override public void reorder(int fromIndex, int toIndex) { ETableRecord<T> record = this.getRecordAtVisualRow(fromIndex); this.removeRecord(record); this.records.add(toIndex, record); } /** * * @see org.swingeasy.ETableI#scrollToVisibleRecord(org.swingeasy.ETableRecord) */ @Override public void scrollToVisibleRecord(ETableRecord<T> record) { if (!this.isDisplayable()) { throw new IllegalArgumentException("can only be used when table is displayable (visible)"); //$NON-NLS-1$ } int index = this.filtering.getRecords().indexOf(record); Rectangle cellbounds = this.getCellRect(index, index, true); this.scrollRectToVisible(cellbounds); } /** * * @see org.swingeasy.ETableI#selectCell(java.awt.Point) */ @Override public void selectCell(Point p) { int r = this.rowAtPoint(p); if (r == -1) { return; } int c = this.columnAtPoint(p); if (c == -1) { return; } // if already selected: do nothing (this keeps multiple selection when current cell is part of it for (int sr : this.getSelectedRows()) { if (sr == r) { for (int sc : this.getSelectedColumns()) { if (sc == c) { return; } } } } this.setColumnSelectionInterval(c, c); this.setRowSelectionInterval(r, r); } /** * * @see org.swingeasy.ETableI#setHeaders(org.swingeasy.ETableHeaders) */ @Override public void setHeaders(final ETableHeaders<T> headers) { // we do not want null here, use an empty header object instead if (headers == null) { throw new NullPointerException(); } this.tableFormat = headers; this.sorting.dispose(); this.tableModel.setTableFormat(headers); this.sorting.install(); } /** * * @see org.swingeasy.ETableI#setLocale(java.util.Locale) */ @Override public void setLocale(Locale l) { super.setLocale(l); this.repaint(); } /** * * @see org.swingeasy.ETableI#sort(int) */ @Override public void sort(final int col) { this.sorting.sort(col); } /** * @see #getSimpleThreadSafeInterface() */ public ETable<T> stsi() { return this.getSimpleThreadSafeInterface(); } /** * @see #getSimpleThreadSafeInterface() */ public ETable<T> STSI() { return this.getSimpleThreadSafeInterface(); } /** * calls original renderer * * @param renderer * @param rowIndex * @param vColIndex * @return */ protected Component super_prepareRenderer(TableCellRenderer renderer, int rowIndex, int vColIndex) { return super.prepareRenderer(renderer, rowIndex, vColIndex); } /** * * @see org.swingeasy.ETableI#unsort() */ @Override public void unsort() { this.sorting.unsort(); } }
src/main/java/org/swingeasy/ETable.java
package org.swingeasy; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Frame; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import java.util.regex.Pattern; import javax.swing.DropMode; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.JWindow; import javax.swing.ScrollPaneConstants; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import org.apache.commons.lang.StringUtils; import org.swingeasy.EComponentPopupMenu.ReadableComponent; import org.swingeasy.system.SystemSettings; import org.swingeasy.table.editor.BooleanTableCellEditor; import org.swingeasy.table.editor.ColorTableCellEditor; import org.swingeasy.table.editor.DateTableCellEditor; import org.swingeasy.table.editor.NumberTableCellEditor; import org.swingeasy.table.renderer.BooleanTableCellRenderer; import org.swingeasy.table.renderer.ByteArrayTableCellRenderer; import org.swingeasy.table.renderer.ColorTableCellRenderer; import org.swingeasy.table.renderer.DateTableCellRenderer; import org.swingeasy.table.renderer.NumberTableCellRenderer; import ca.odell.glazedlists.BasicEventList; import ca.odell.glazedlists.EventList; import ca.odell.glazedlists.FilterList; import ca.odell.glazedlists.GlazedLists; import ca.odell.glazedlists.ListSelection; import ca.odell.glazedlists.SortedList; import ca.odell.glazedlists.gui.AbstractTableComparatorChooser; import ca.odell.glazedlists.gui.TableFormat; import ca.odell.glazedlists.matchers.AbstractMatcherEditor; import ca.odell.glazedlists.matchers.Matcher; import ca.odell.glazedlists.swing.DefaultEventSelectionModel; import ca.odell.glazedlists.swing.DefaultEventTableModel; import ca.odell.glazedlists.swing.EventTableColumnModel; import ca.odell.glazedlists.swing.SortableRenderer; import ca.odell.glazedlists.swing.TableComparatorChooser; /** * @author Jurgen * * @see http://www.chka.de/swing/table/faq.html */ public class ETable<T> extends JTable implements ETableI<T>, Reorderable, Iterable<ETableRecord<T>>, ReadableComponent { protected class EFiltering { /** * JDOC */ protected class FilterPopup extends JWindow { /** * JDOC */ protected class RecordMatcher implements Matcher<ETableRecord<T>> { protected final Map<Integer, Pattern> filters = new HashMap<Integer, Pattern>(); protected RecordMatcher(int column, String text) { if (text != null) { this.filters.put(column, Pattern.compile(text, Pattern.CASE_INSENSITIVE)); } } protected RecordMatcher(Map<Integer, String> popupFilters) { for (Map.Entry<Integer, String> entry : popupFilters.entrySet()) { if (entry.getValue() != null) { this.filters.put(entry.getKey(), Pattern.compile(entry.getValue(), Pattern.CASE_INSENSITIVE)); } } } /** * @see ca.odell.glazedlists.matchers.Matcher#matches(java.lang.Object) */ @Override public boolean matches(ETableRecord<T> item) { for (Map.Entry<Integer, Pattern> entry : this.filters.entrySet()) { String value = item.getStringValue(entry.getKey()); if (!entry.getValue().matcher(value).find()) { return false; } } return true; } } private static final long serialVersionUID = 5033445579635687866L; protected JTextField popupTextfield = new JTextField(); protected int popupForColumn = -1; protected Map<Integer, String> popupFilters = new HashMap<Integer, String>(); protected FilterPopup(Frame frame) { super(frame); this.popupTextfield.setBackground(new Color(246, 243, 149)); this.getContentPane().add(this.popupTextfield, BorderLayout.CENTER); this.popupTextfield.setFocusTraversalKeysEnabled(false); this.popupTextfield.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { FilterPopup.this.setVisible(false); } }); this.popupTextfield.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { // preview filtering System.out.println("preview filter " + FilterPopup.this.popupTextfield.getText()); //$NON-NLS-1$ ETable.this.filtering.matcherEditor.fire(new RecordMatcher(FilterPopup.this.popupForColumn, FilterPopup.this.popupTextfield.getText())); } else if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { // revert filtering, close System.out.println("revert filter"); //$NON-NLS-1$ ETable.this.filtering.matcherEditor.fire(new RecordMatcher(FilterPopup.this.popupForColumn, FilterPopup.this.popupFilters .get(FilterPopup.this.popupForColumn))); FilterPopup.this.setVisible(false); } else if (e.getKeyCode() == KeyEvent.VK_TAB) { // commit filtering FilterPopup.this.popupFilters.put(FilterPopup.this.popupForColumn, FilterPopup.this.popupTextfield.getText()); System.out.println("filter " + FilterPopup.this.popupFilters); //$NON-NLS-1$ ETable.this.filtering.matcherEditor.fire(new RecordMatcher(FilterPopup.this.popupFilters)); FilterPopup.this.setVisible(false); } else { // } } }); } /** * JDOC * * @param p */ protected void activate(Point p) { this.popupForColumn = ETable.this.getTableHeader().columnAtPoint(p); String filter = this.popupFilters.get(this.popupForColumn); this.popupTextfield.setText(filter); Rectangle headerRect = ETable.this.getTableHeader().getHeaderRect(this.popupForColumn); Point pt = ETable.this.getLocationOnScreen(); pt.translate(headerRect.x - 1, -headerRect.height - 1); this.setLocation(pt); this.setSize(headerRect.width, headerRect.height); this.toFront(); this.setVisible(true); this.requestFocusInWindow(); this.popupTextfield.requestFocusInWindow(); } /** * JDOC */ public void clear() { this.popupFilters.clear(); this.popupForColumn = -1; } } /** * JDOC */ protected class FilterPopupActivate extends MouseAdapter { /** * * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent) */ @Override public void mouseClicked(MouseEvent e) { ETable.this.filtering.mouseClicked(e); } } protected RecordMatcherEditor<T> matcherEditor; protected FilterList<ETableRecord<T>> filteredRecords; protected FilterPopup filterPopup; protected EventList<ETableRecord<T>> source; protected EFiltering(EventList<ETableRecord<T>> source, AbstractMatcherEditor<ETableRecord<T>> matcher) { this.source = source; if (matcher != null) { // we do matching ourselves this.filteredRecords = new FilterList<ETableRecord<T>>(source, matcher); return; } if (!ETable.this.cfg.isFilterable()) { return; } // default matching this.matcherEditor = new RecordMatcherEditor<T>(); this.filteredRecords = new FilterList<ETableRecord<T>>(source, this.matcherEditor); } protected void clear() { if (!ETable.this.cfg.isFilterable()) { return; } this.getFilterPopup().clear(); } protected FilterPopup getFilterPopup() { if (!ETable.this.cfg.isFilterable()) { return null; } if (this.filterPopup == null) { this.filterPopup = new FilterPopup(ETable.this.getFrame(ETable.this)); } return this.filterPopup; } protected EventList<ETableRecord<T>> getRecords() { if (this.filteredRecords == null) { return this.source; } return this.filteredRecords; } protected void install() { if (!ETable.this.cfg.isFilterable()) { return; } ETable.this.getTableHeader().addMouseListener(new FilterPopupActivate()); } protected void mouseClicked(MouseEvent e) { if (!ETable.this.cfg.isFilterable()) { return; } if ((e.getClickCount() == 1) && (e.getButton() == MouseEvent.BUTTON3)) { this.getFilterPopup().activate(e.getPoint()); } } } protected class ESorting { protected TableComparatorChooser<ETableRecord<T>> tableSorter; protected SortedList<ETableRecord<T>> sortedRecords; protected EventList<ETableRecord<T>> source; protected ESorting(EventList<ETableRecord<T>> source) { this.source = source; if (!ETable.this.cfg.isSortable()) { return; } this.sortedRecords = new SortedList<ETableRecord<T>>(source, null); } protected void dispose() { if (!ETable.this.cfg.isSortable()) { return; } this.tableSorter.dispose(); } protected EventList<ETableRecord<T>> getRecords() { if (!ETable.this.cfg.isSortable()) { return this.source; } return this.sortedRecords; } protected void install() { if (!ETable.this.cfg.isSortable()) { return; } this.tableSorter = TableComparatorChooser.install(ETable.this, this.sortedRecords, AbstractTableComparatorChooser.MULTIPLE_COLUMN_MOUSE_WITH_UNDO, ETable.this.tableFormat); } protected void sort(int col) { if (!ETable.this.cfg.isSortable()) { return; } this.tableSorter.clearComparator(); this.tableSorter.appendComparator(col, 0, false); } protected void unsort() { if (!ETable.this.cfg.isSortable()) { return; } this.tableSorter.clearComparator(); } } public class ETableModel extends DefaultEventTableModel<ETableRecord<T>> { private static final long serialVersionUID = -8936359559294414836L; protected ETableModel(EventList<ETableRecord<T>> source, TableFormat<? super ETableRecord<T>> tableFormat) { super(source, tableFormat); } /** * * @see javax.swing.table.AbstractTableModel#fireTableCellUpdated(int, int) */ @Override public void fireTableCellUpdated(int row, int column) { super.fireTableCellUpdated(row, column); }; /** * * @see ca.odell.glazedlists.swing.EventTableModel#getColumnClass(int) */ @Override public Class<?> getColumnClass(int columnIndex) { Class<?> clas = ETable.this.tableFormat.getColumnClass(columnIndex); // System.out.println("ETableModel.getColumnClass(" + columnIndex + ")=" + clas); return clas; } } public static abstract class Filter<T> extends RecordMatcherEditor<T> implements Matcher<ETableRecord<T>> { public void fire() { this.fire(this); } } /** * JDOC */ protected static class RecordMatcherEditor<T> extends AbstractMatcherEditor<ETableRecord<T>> { protected void fire(Matcher<ETableRecord<T>> matcher) { this.fireChanged(matcher); } } /** * @see http://publicobject.com/glazedlistsdeveloper/ */ protected class VerticalHeaderRenderer extends VerticalTableHeaderCellRenderer implements SortableRenderer { private static final long serialVersionUID = 2995810245364522046L; protected Icon sortIcon = null; protected final static double DEGREE_90 = (90.0 * Math.PI) / 180.0; protected Map<Icon, Icon> rotatedIconsCache = new HashMap<Icon, Icon>(); /** * Creates a rotated version of the input image. * * @param c The component to get properties useful for painting, e.g. the foreground or background color. * @param icon the image to be rotated. * @param rotatedAngle the rotated angle, in degree, clockwise. It could be any double but we will mod it with 360 before using it. * * @return the image after rotating. * * @see http://www.jidesoft.com/blog/2008/02/29/rotate-an-icon-in-java/ */ protected ImageIcon createRotatedImage(Component c, Icon icon, double rotatedAngle) { // convert rotatedAngle to a value from 0 to 360 double originalAngle = rotatedAngle % 360; if ((rotatedAngle != 0) && (originalAngle == 0)) { originalAngle = 360.0; } // convert originalAngle to a value from 0 to 90 double angle = originalAngle % 90; if ((originalAngle != 0.0) && (angle == 0.0)) { angle = 90.0; } double radian = Math.toRadians(angle); int iw = icon.getIconWidth(); int ih = icon.getIconHeight(); int w; int h; if (((originalAngle >= 0) && (originalAngle <= 90)) || ((originalAngle > 180) && (originalAngle <= 270))) { w = (int) ((iw * Math.sin(VerticalHeaderRenderer.DEGREE_90 - radian)) + (ih * Math.sin(radian))); h = (int) ((iw * Math.sin(radian)) + (ih * Math.sin(VerticalHeaderRenderer.DEGREE_90 - radian))); } else { w = (int) ((ih * Math.sin(VerticalHeaderRenderer.DEGREE_90 - radian)) + (iw * Math.sin(radian))); h = (int) ((ih * Math.sin(radian)) + (iw * Math.sin(VerticalHeaderRenderer.DEGREE_90 - radian))); } BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics g = image.getGraphics(); Graphics2D g2d = (Graphics2D) g.create(); // calculate the center of the icon. int cx = iw / 2; int cy = ih / 2; // move the graphics center point to the center of the icon. g2d.translate(w / 2, h / 2); // rotate the graphcis about the center point of the icon g2d.rotate(Math.toRadians(originalAngle)); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC); icon.paintIcon(c, g2d, -cx, -cy); g2d.dispose(); return new ImageIcon(image); } /** * * @see org.swingeasy.VerticalTableHeaderCellRenderer#getIcon(javax.swing.JTable, int) */ @Override protected Icon getIcon(JTable table, int column) { return this.sortIcon; } /** * * @see ca.odell.glazedlists.swing.SortableRenderer#setSortIcon(javax.swing.Icon) */ @Override public void setSortIcon(Icon sortIcon) { if (sortIcon != null) { Icon found = this.rotatedIconsCache.get(sortIcon); if (found == null) { found = this.createRotatedImage(this, sortIcon, 90.0); this.rotatedIconsCache.put(sortIcon, found); } this.sortIcon = found; } else { this.sortIcon = null; } } } private static final long serialVersionUID = 6515690492295488815L; protected final EventList<ETableRecord<T>> records; protected final DefaultEventTableModel<ETableRecord<T>> tableModel; protected final DefaultEventSelectionModel<ETableRecord<T>> tableSelectionModel; protected final EFiltering filtering; protected final ESorting sorting; protected final ETableConfig cfg; protected ETableHeaders<T> tableFormat; protected static final String TABLE_RENDERERS_DIR = "org.swingeasy.table.renderer"; protected static final String TABLE_EDITORS_DIR = "org.swingeasy.table.editor"; /** * use other constructors instead */ protected ETable() { this.filtering = null; this.sorting = null; this.cfg = null; this.records = null; this.tableModel = null; this.tableSelectionModel = null; } public ETable(ETableConfig configuration) { this(configuration, null); } public ETable(ETableConfig configuration, Filter<T> matcher) { this.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON3) { ETable.this.selectCell(new Point(e.getX(), e.getY())); } } }); this.cfg = configuration; this.cfg.lock(); if (this.cfg.isVertical()) { this.getTableHeader().setDefaultRenderer(new VerticalHeaderRenderer()); } if (this.cfg.isDraggable()) { this.setDragEnabled(true); this.setDropMode(DropMode.INSERT_ROWS); this.setTransferHandler(new TableRowTransferHandler(this)); } this.setColumnModel(new EventTableColumnModel<TableColumn>(new BasicEventList<TableColumn>())); this.records = (this.cfg.isThreadSafe() ? GlazedLists.threadSafeList(new BasicEventList<ETableRecord<T>>()) : new BasicEventList<ETableRecord<T>>()); this.sorting = new ESorting(this.records); this.tableFormat = new ETableHeaders<T>(); this.filtering = new EFiltering(this.sorting.getRecords(), matcher); this.tableModel = new ETableModel(this.filtering.getRecords(), this.tableFormat); this.setModel(this.tableModel); this.tableSelectionModel = new DefaultEventSelectionModel<ETableRecord<T>>(this.records); this.tableSelectionModel.setSelectionMode(ListSelection.MULTIPLE_INTERVAL_SELECTION_DEFENSIVE); this.setColumnSelectionAllowed(true); this.setRowSelectionAllowed(true); this.setSelectionModel(this.tableSelectionModel); this.sorting.install(); this.filtering.install(); this.getTableHeader().setReorderingAllowed(this.cfg.isReorderable()); this.getTableHeader().setResizingAllowed(this.cfg.isResizable()); UIUtils.registerLocaleChangeListener((EComponentI) this); if (this.cfg.isDefaultPopupMenu()) { this.installPopupMenuAction(EComponentPopupMenu.installPopupMenu(this)); } } /** * * @see org.swingeasy.ETableI#addRecord(org.swingeasy.ETableRecord) */ @Override public void addRecord(final ETableRecord<T> record) { this.records.add(record); } /** * * @see org.swingeasy.ETableI#addRecords(java.util.Collection) */ @Override public void addRecords(final Collection<ETableRecord<T>> r) { this.records.addAll(r); } /** * add rowheader to scrollpane, 4 digit number */ public void addRowHeader(JScrollPane scrollpane) { this.addRowHeader(scrollpane, 4); } /** * add rowheader to scrollpane */ public void addRowHeader(JScrollPane scrollpane, int cw) { RowNumberTable rowTable = this.getRowHeader(cw); scrollpane.setRowHeaderView(rowTable); scrollpane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, rowTable.getTableHeader()); } /** * * @see org.swingeasy.ETableI#clear() */ @Override public void clear() { this.tableSelectionModel.clearSelection(); this.records.clear(); this.sorting.dispose(); this.tableModel.setTableFormat(new ETableHeaders<T>()); this.filtering.clear(); } /** * * @see org.swingeasy.EComponentPopupMenu.ReadableComponent#copy(java.awt.event.ActionEvent) */ @Override public void copy(ActionEvent e) { StringBuilder sb = new StringBuilder(); for (Object cell : this.getSelectedCells()) { sb.append(String.valueOf(cell)).append(SystemSettings.getNewline()); } EComponentPopupMenu.copyToClipboard(sb.toString()); } /** * * @see javax.swing.JTable#createDefaultEditors() */ @SuppressWarnings("unchecked") @Override protected void createDefaultEditors() { super.createDefaultEditors(); this.defaultEditorsByColumnClass.put(Boolean.class, new javax.swing.UIDefaults.ProxyLazyValue(BooleanTableCellEditor.class.getName())); this.defaultEditorsByColumnClass.put(Date.class, new javax.swing.UIDefaults.ProxyLazyValue(DateTableCellEditor.class.getName())); this.defaultEditorsByColumnClass.put(Color.class, new javax.swing.UIDefaults.ProxyLazyValue(ColorTableCellEditor.class.getName())); this.defaultEditorsByColumnClass.put(Number.class, new javax.swing.UIDefaults.ProxyLazyValue(NumberTableCellEditor.class.getName())); } /** * * @see javax.swing.JTable#createDefaultRenderers() */ @SuppressWarnings("unchecked") @Override protected void createDefaultRenderers() { super.createDefaultRenderers(); this.defaultRenderersByColumnClass.put(Boolean.class, new javax.swing.UIDefaults.ProxyLazyValue(BooleanTableCellRenderer.class.getName())); this.defaultRenderersByColumnClass.put(Date.class, new javax.swing.UIDefaults.ProxyLazyValue(DateTableCellRenderer.class.getName())); this.defaultRenderersByColumnClass.put(Color.class, new javax.swing.UIDefaults.ProxyLazyValue(ColorTableCellRenderer.class.getName())); this.defaultRenderersByColumnClass.put(Number.class, new javax.swing.UIDefaults.ProxyLazyValue(NumberTableCellRenderer.class.getName())); this.defaultRenderersByColumnClass.put(Float.class, new javax.swing.UIDefaults.ProxyLazyValue(NumberTableCellRenderer.class.getName())); this.defaultRenderersByColumnClass.put(Double.class, new javax.swing.UIDefaults.ProxyLazyValue(NumberTableCellRenderer.class.getName())); this.defaultRenderersByColumnClass.put(byte[].class, new javax.swing.UIDefaults.ProxyLazyValue(ByteArrayTableCellRenderer.class.getName())); this.defaultRenderersByColumnClass.put(Byte[].class, new javax.swing.UIDefaults.ProxyLazyValue(ByteArrayTableCellRenderer.class.getName())); } /** * * @see javax.swing.JTable#createDefaultTableHeader() */ @Override protected JTableHeader createDefaultTableHeader() { JTableHeader jTableHeader = new JTableHeader(this.columnModel) { private static final long serialVersionUID = -378778832166135907L; @Override public String getToolTipText(MouseEvent e) { Point p = e.getPoint(); int index = this.columnModel.getColumnIndexAtX(p.x); if (index == -1) { return null; } String headerValue = String.valueOf(ETable.this.getSimpleThreadSafeInterface().getColumnValueAtVisualColumn(index)); if (ETable.this.cfg.isFilterable()) { String filter = ETable.this.filtering.getFilterPopup().popupFilters.get(index); if ((filter != null) && (filter.trim().length() > 0)) { headerValue += "<br/>" + "filter: '" + filter + "'"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } else { headerValue += "<br/>" + "no filter"; //$NON-NLS-1$ //$NON-NLS-2$ } headerValue += "<br/><br/>right click to edit filter<br/>enter to preview filter<br/>tab to accept filter"; //$NON-NLS-1$ } return "<html><body>" + headerValue + "</body></html>"; //$NON-NLS-1$ //$NON-NLS-2$ } }; return jTableHeader; } /** * @see javax.swing.JTable#getCellRenderer(int, int) */ @Override public TableCellRenderer getCellRenderer(int row, int column) { return super.getCellRenderer(row, column); } /** * @see javax.swing.JTable#getColumnClass(int) */ @Override public Class<?> getColumnClass(int columnIndex) { Class<?> clas = super.getColumnClass(columnIndex); // System.out.println("ETableHeaders.getColumnClass(" + columnIndex + ")=" + clas); return clas; } /** * * @see org.swingeasy.ETableI#getColumnValueAtVisualColumn(int) */ @Override public Object getColumnValueAtVisualColumn(int i) { return this.getColumnModel().getColumn(i).getHeaderValue(); } /** * * @see javax.swing.JTable#getDefaultEditor(java.lang.Class) */ @Override public TableCellEditor getDefaultEditor(Class<?> columnClass) { TableCellEditor de = super.getDefaultEditor(columnClass); if (de instanceof EComponentI) { UIUtils.registerLocaleChangeListener(EComponentI.class.cast(de)); // } else if (de instanceof Component) { // UIUtils.registerLocaleChangeListener(Component.class.cast(de)); } return de; } /** * * @see javax.swing.JTable#getDefaultRenderer(java.lang.Class) */ @Override public TableCellRenderer getDefaultRenderer(Class<?> columnClass) { TableCellRenderer dr = super.getDefaultRenderer(columnClass); if (dr instanceof EComponentI) { UIUtils.registerLocaleChangeListener(EComponentI.class.cast(dr)); // } else if (dr instanceof Component) { // UIUtils.registerLocaleChangeListener(Component.class.cast(dr)); } return dr; } /** * JDOC * * @param comp * @return */ protected Frame getFrame(Component comp) { if (comp == null) { comp = this; } if (comp.getParent() instanceof Frame) { return (Frame) comp.getParent(); } return this.getFrame(comp.getParent()); } /** * * @see org.swingeasy.ETableI#getHeadernames() */ @Override public List<String> getHeadernames() { List<String> columnNames = this.tableFormat.getColumnNames(); return columnNames; } /** * gets tableFormat * * @return Returns the tableFormat. */ public ETableHeaders<T> getHeaders() { return this.tableFormat; } /** * * @see org.swingeasy.HasParentComponent#getParentComponent() */ @Override public JComponent getParentComponent() { return this; } /** * * @see org.swingeasy.ETableI#getRecordAtVisualRow(int) */ @Override public ETableRecord<T> getRecordAtVisualRow(int i) { return this.filtering.getRecords().get(i); } /** * * @see org.swingeasy.ETableI#getRecords() */ @Override public List<ETableRecord<T>> getRecords() { return this.filtering.getRecords(); } /** * @see #getRowHeader() */ public RowNumberTable getRowHeader() { return this.getRowHeader(4); } /** * gets row header that can be added to the RowHeaderView of a {@link JScrollPane} or can be docked WEST in a {@link BorderLayout} */ public RowNumberTable getRowHeader(int cw) { return new RowNumberTable(this, cw); } /** * * @see org.swingeasy.ETableI#getSelectedCell() */ @SuppressWarnings("unchecked") @Override public T getSelectedCell() { ETableRecord<T> record = this.getSelectedRecord(); if (record == null) { return null; } return (T) record.get(this.getSelectedColumn()); } /** * * @see org.swingeasy.ETableI#getSelectedCells() */ @Override public List<Object> getSelectedCells() { List<Object> cells = new ArrayList<Object>(); for (ETableRecord<T> record : this.getSelectedRecords()) { cells.add(record.get(this.getSelectedColumn())); } return cells; } /** * * @see org.swingeasy.ETableI#getSelectedRecord() */ @Override public ETableRecord<T> getSelectedRecord() { EventList<ETableRecord<T>> selected = this.tableSelectionModel.getSelected(); return selected.size() == 0 ? null : selected.iterator().next(); } /** * * @see org.swingeasy.ETableI#getSelectedRecords() */ @Override public List<ETableRecord<T>> getSelectedRecords() { return this.tableSelectionModel.getSelected(); } /** * JDOC * * @return */ @SuppressWarnings("unchecked") public ETable<T> getSimpleThreadSafeInterface() { try { return EventThreadSafeWrapper.getSimpleThreadSafeInterface(ETable.class, this, ETableI.class); } catch (Exception ex) { System.err.println(ex); return this; // no javassist } } /** * JDOC */ protected void installPopupMenuAction(JPopupMenu menu) { menu.addSeparator(); @SuppressWarnings({ "unchecked", "rawtypes" }) ServiceLoader<ETableExporter<T>> exporterService = (ServiceLoader) ServiceLoader.load(ETableExporter.class); Iterator<ETableExporter<T>> iterator = exporterService.iterator(); while (iterator.hasNext()) { try { ETableExporter<T> exporter = iterator.next(); ETableExporterAction<T> action = new ETableExporterAction<T>(exporter, this); menu.add(action); } catch (ServiceConfigurationError ex) { ex.printStackTrace(System.err); } } } /** * * @see javax.swing.JTable#isCellEditable(int, int) */ @Override public boolean isCellEditable(int row, int column) { return this.cfg.isEditable() && super.isCellEditable(row, column); } /** * threadsafe unmodifiable iterator * * @see java.lang.Iterable#iterator() */ @Override public Iterator<ETableRecord<T>> iterator() { return Collections.unmodifiableCollection(this.getRecords()).iterator(); } /** * * @see org.swingeasy.ETableI#packColumn(int) */ @Override public void packColumn(int vColIndex) { this.packColumn(vColIndex, 4); } /** * Sets the preferred width of the visible column specified by vColIndex. The column will be just wide enough to show the column head and the * widest cell in the column. margin pixels are added to the left and right (resulting in an additional width of 2*margin pixels). * * @param table * @param vColIndex * @param margin */ @Override public void packColumn(int vColIndex, int margin) { TableColumnModel colModel = this.getColumnModel(); TableColumn col = colModel.getColumn(vColIndex); int width = 0; // Get width of column header TableCellRenderer renderer = col.getHeaderRenderer(); if (renderer == null) { renderer = this.getTableHeader().getDefaultRenderer(); } Component comp = renderer.getTableCellRendererComponent(this, col.getHeaderValue(), false, false, 0, 0); width = comp.getPreferredSize().width; // Get maximum width of column data for (int r = 0; r < this.getRowCount(); r++) { renderer = this.getCellRenderer(r, vColIndex); comp = renderer.getTableCellRendererComponent(this, this.getValueAt(r, vColIndex), false, false, r, vColIndex); width = Math.max(width, comp.getPreferredSize().width); } // Add margin width += 2 * margin; // Set the width col.setPreferredWidth(width); col.setWidth(width); col.setMaxWidth(width); } /** * * @see javax.swing.JTable#prepareRenderer(javax.swing.table.TableCellRenderer, int, int) */ @Override public Component prepareRenderer(TableCellRenderer renderer, int rowIndex, int vColIndex) { Component c = this.super_prepareRenderer(renderer, rowIndex, vColIndex); if (c instanceof JLabel) { String text = JLabel.class.cast(c).getText(); JLabel.class.cast(c).setToolTipText(StringUtils.isNotBlank(text) ? text : null); } return c; } /** * * @see org.swingeasy.ETableI#removeAllRecords() */ @Override public void removeAllRecords() { this.records.clear(); } /** * * @see org.swingeasy.ETableI#removeRecord(org.swingeasy.ETableRecord) */ @Override public void removeRecord(final ETableRecord<T> record) { this.records.remove(record); } /** * * @see org.swingeasy.ETableI#removeRecordAtVisualRow(int) */ @Override public void removeRecordAtVisualRow(final int i) { this.records.remove(this.sorting.getRecords().get(i)); } /** * remove rowheader */ public void removeRowHeader(JScrollPane scrollpane) { if (scrollpane.getRowHeader().getView() instanceof RowNumberTable) { scrollpane.getRowHeader().removeAll(); scrollpane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, new JComponent() { private static final long serialVersionUID = 1L; }); } } /** * * @see org.swingeasy.Reorderable#reorder(int, int) */ @Override public void reorder(int fromIndex, int toIndex) { ETableRecord<T> record = this.getRecordAtVisualRow(fromIndex); this.removeRecord(record); this.records.add(toIndex, record); } /** * * @see org.swingeasy.ETableI#scrollToVisibleRecord(org.swingeasy.ETableRecord) */ @Override public void scrollToVisibleRecord(ETableRecord<T> record) { if (!this.isDisplayable()) { throw new IllegalArgumentException("can only be used when table is displayable (visible)"); //$NON-NLS-1$ } int index = this.filtering.getRecords().indexOf(record); Rectangle cellbounds = this.getCellRect(index, index, true); this.scrollRectToVisible(cellbounds); } /** * * @see org.swingeasy.ETableI#selectCell(java.awt.Point) */ @Override public void selectCell(Point p) { int r = this.rowAtPoint(p); if (r == -1) { return; } int c = this.columnAtPoint(p); if (c == -1) { return; } // if already selected: do nothing (this keeps multiple selection when current cell is part of it for (int sr : this.getSelectedRows()) { if (sr == r) { for (int sc : this.getSelectedColumns()) { if (sc == c) { return; } } } } this.setColumnSelectionInterval(c, c); this.setRowSelectionInterval(r, r); } /** * * @see org.swingeasy.ETableI#setHeaders(org.swingeasy.ETableHeaders) */ @Override public void setHeaders(final ETableHeaders<T> headers) { // we do not want null here, use an empty header object instead if (headers == null) { throw new NullPointerException(); } this.tableFormat = headers; this.sorting.dispose(); this.tableModel.setTableFormat(headers); this.sorting.install(); } /** * * @see org.swingeasy.ETableI#setLocale(java.util.Locale) */ @Override public void setLocale(Locale l) { super.setLocale(l); this.repaint(); } /** * * @see org.swingeasy.ETableI#sort(int) */ @Override public void sort(final int col) { this.sorting.sort(col); } /** * @see #getSimpleThreadSafeInterface() */ public ETable<T> stsi() { return this.getSimpleThreadSafeInterface(); } /** * @see #getSimpleThreadSafeInterface() */ public ETable<T> STSI() { return this.getSimpleThreadSafeInterface(); } /** * calls original renderer * * @param renderer * @param rowIndex * @param vColIndex * @return */ protected Component super_prepareRenderer(TableCellRenderer renderer, int rowIndex, int vColIndex) { return super.prepareRenderer(renderer, rowIndex, vColIndex); } /** * * @see org.swingeasy.ETableI#unsort() */ @Override public void unsort() { this.sorting.unsort(); } }
bugfix: ETable: selection model when sorting
src/main/java/org/swingeasy/ETable.java
bugfix: ETable: selection model when sorting
<ide><path>rc/main/java/org/swingeasy/ETable.java <ide> this.filtering = new EFiltering(this.sorting.getRecords(), matcher); <ide> this.tableModel = new ETableModel(this.filtering.getRecords(), this.tableFormat); <ide> this.setModel(this.tableModel); <del> this.tableSelectionModel = new DefaultEventSelectionModel<ETableRecord<T>>(this.records); <add> this.tableSelectionModel = new DefaultEventSelectionModel<ETableRecord<T>>(this.filtering.getRecords()); <ide> this.tableSelectionModel.setSelectionMode(ListSelection.MULTIPLE_INTERVAL_SELECTION_DEFENSIVE); <ide> this.setColumnSelectionAllowed(true); <ide> this.setRowSelectionAllowed(true);
Java
apache-2.0
30a249a662ff49fcf8789849349f7154ff9741a9
0
OpenGamma/Strata,ChinaQuants/Strata,jmptrader/Strata
/** * Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.report.framework.expression; import static com.opengamma.strata.collect.Guavate.toImmutableList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.IntStream; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.opengamma.strata.basics.index.IborIndex; import com.opengamma.strata.collect.result.FailureReason; import com.opengamma.strata.collect.result.Result; import com.opengamma.strata.engine.config.Measure; import com.opengamma.strata.finance.rate.fra.Fra; import com.opengamma.strata.finance.rate.fra.FraTrade; import com.opengamma.strata.report.ReportCalculationResults; /** * Evaluates a path describing a value to be shown in a trade report. * <p> * For example, if the expression is '{@code Product.index.name}' and the results contain {@link FraTrade} instances * the following calls will be made for each trade in the results: * <ul> * <li>{@code FraTrade.getProduct()} returning a {@link Fra}</li> * <li>{@code Fra.getIndex()} returning an {@link IborIndex}</li> * <li>{@code IborIndex.getName()} returning the index name</li> * </ul> * The result of evaluating the expression is the index name. */ public class ValuePathEvaluator { /** The separator used in the value path. */ private static final String PATH_SEPARATOR = "\\."; private static final ImmutableList<TokenEvaluator<?>> EVALUATORS = ImmutableList.of( new CurrencyAmountTokenEvaluator(), new MapTokenEvaluator(), new CurveCurrencyParameterSensitivitiesTokenEvaluator(), new CurveCurrencyParameterSensitivityTokenEvaluator(), new TradeTokenEvaluator(), new BeanTokenEvaluator(), new IterableTokenEvaluator()); //------------------------------------------------------------------------- /** * Gets the measure encoded in a value path, if present. * * @param valuePath the value path * @return the measure, if present */ public static Optional<Measure> measure(String valuePath) { try { List<String> tokens = tokenize(valuePath); ValueRootType rootType = ValueRootType.parseToken(tokens.get(0)); if (rootType != ValueRootType.MEASURES || tokens.size() < 2) { return Optional.empty(); } Measure measure = Measure.of(tokens.get(1)); return Optional.of(measure); } catch (Exception ex) { return Optional.empty(); } } /** * Evaluates a value path against a set of results, returning the resolved result for each trade. * * @param valuePath the value path * @param results the calculation results * @return the list of resolved results for each trade */ public static List<Result<?>> evaluate(String valuePath, ReportCalculationResults results) { List<String> tokens = tokenize(valuePath); if (tokens.size() < 1) { return Collections.nCopies( results.getTrades().size(), Result.failure(FailureReason.INVALID_INPUT, "Column expressions must not be empty")); } int rowCount = results.getCalculationResults().getRowCount(); return IntStream.range(0, rowCount) .mapToObj(rowIndex -> evaluate(tokens, RootEvaluator.INSTANCE, new ResultsRow(results, rowIndex))) .collect(toImmutableList()); } // Tokens always has at least one token private static <T> Result<?> evaluate(List<String> tokens, TokenEvaluator<T> evaluator, T target) { EvaluationResult evaluationResult = evaluator.evaluate(target, tokens.get(0), tokens.subList(1, tokens.size())); if (evaluationResult.isComplete()) { return evaluationResult.getResult(); } Object value = evaluationResult.getResult().getValue(); Optional<TokenEvaluator<Object>> nextEvaluator = getEvaluator(value.getClass()); return nextEvaluator.isPresent() ? evaluate(evaluationResult.getRemainingTokens(), nextEvaluator.get(), value) : noEvaluatorResult(value); } private static Result<?> noEvaluatorResult(Object value) { return Result.failure( FailureReason.INVALID_INPUT, "No evaluator available for objects of type {}", value.getClass().getName()); } /** * Gets the supported tokens on the given object. * * @param object the object for which to return the valid tokens * @return the tokens */ public static Set<String> tokens(Object object) { return getEvaluator(object.getClass()).map(evaluator -> evaluator.tokens(object)).orElse(ImmutableSet.of()); } //------------------------------------------------------------------------- // splits a value path into tokens for processing private static List<String> tokenize(String valuePath) { String[] tokens = valuePath.split(PATH_SEPARATOR); return ImmutableList.copyOf(tokens); } @SuppressWarnings("unchecked") private static Optional<TokenEvaluator<Object>> getEvaluator(Class<?> targetClass) { return EVALUATORS.stream() .filter(e -> e.getTargetType().isAssignableFrom(targetClass)) .map(e -> (TokenEvaluator<Object>) e) .findFirst(); } //------------------------------------------------------------------------- private ValuePathEvaluator() { } }
modules/report/src/main/java/com/opengamma/strata/report/framework/expression/ValuePathEvaluator.java
/** * Copyright (C) 2015 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.report.framework.expression; import static com.opengamma.strata.collect.Guavate.toImmutableList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.IntStream; import java.util.stream.Stream; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.opengamma.strata.basics.index.IborIndex; import com.opengamma.strata.collect.result.FailureReason; import com.opengamma.strata.collect.result.Result; import com.opengamma.strata.engine.config.Measure; import com.opengamma.strata.finance.rate.fra.Fra; import com.opengamma.strata.finance.rate.fra.FraTrade; import com.opengamma.strata.report.ReportCalculationResults; /** * Evaluates a path describing a value to be shown in a trade report. * <p> * For example, if the expression is '{@code Product.index.name}' and the results contain {@link FraTrade} instances * the following calls will be made for each trade in the results: * <ul> * <li>{@code FraTrade.getProduct()} returning a {@link Fra}</li> * <li>{@code Fra.getIndex()} returning an {@link IborIndex}</li> * <li>{@code IborIndex.getName()} returning the index name</li> * </ul> * The result of evaluating the expression is the index name. */ public class ValuePathEvaluator { /** The separator used in the value path. */ private static final String PATH_SEPARATOR = "\\."; private static final ImmutableList<TokenEvaluator<?>> EVALUATORS = ImmutableList.of( new CurrencyAmountTokenEvaluator(), new MapTokenEvaluator(), new CurveCurrencyParameterSensitivitiesTokenEvaluator(), new CurveCurrencyParameterSensitivityTokenEvaluator(), new TradeTokenEvaluator(), new BeanTokenEvaluator(), new IterableTokenEvaluator()); //------------------------------------------------------------------------- /** * Gets the measure encoded in a value path, if present. * * @param valuePath the value path * @return the measure, if present */ public static Optional<Measure> measure(String valuePath) { try { List<String> tokens = tokenize(valuePath); ValueRootType rootType = ValueRootType.parseToken(tokens.get(0)); if (rootType != ValueRootType.MEASURES || tokens.size() < 2) { return Optional.empty(); } Measure measure = Measure.of(tokens.get(1)); return Optional.of(measure); } catch (Exception ex) { return Optional.empty(); } } /** * Evaluates a value path against a set of results, returning the resolved result for each trade. * * @param valuePath the value path * @param results the calculation results * @return the list of resolved results for each trade */ @SuppressWarnings("unchecked") public static List<Result<?>> evaluate(String valuePath, ReportCalculationResults results) { List<String> tokens = tokenize(valuePath); if (tokens.size() < 1) { return Collections.nCopies( results.getTrades().size(), Result.failure(FailureReason.INVALID_INPUT, "Column expressions must not be empty")); } TokenEvaluator rootEvaluator = RootEvaluator.INSTANCE; int rowCount = results.getCalculationResults().getRowCount(); // javac 8u40 won't compile this if the call to collect() is chained after the call to mapToObj() // but it works fine if the intermediate stream is assigned to a local variable. Compiler bug? Stream<Result<?>> resultStream = IntStream.range(0, rowCount) .mapToObj(rowIndex -> evaluate(tokens, rootEvaluator, new ResultsRow(results, rowIndex))); return resultStream.collect(toImmutableList()); } // Tokens always has at least one token private static Result<?> evaluate(List<String> tokens, TokenEvaluator<Object> evaluator, Object target) { EvaluationResult evaluationResult = evaluator.evaluate(target, tokens.get(0), tokens.subList(1, tokens.size())); if (evaluationResult.isComplete()) { return evaluationResult.getResult(); } Object value = evaluationResult.getResult().getValue(); Optional<TokenEvaluator<Object>> nextEvaluator = getEvaluator(value.getClass()); return nextEvaluator.isPresent() ? evaluate(evaluationResult.getRemainingTokens(), nextEvaluator.get(), value) : noEvaluatorResult(value); } private static Result<?> noEvaluatorResult(Object value) { return Result.failure( FailureReason.INVALID_INPUT, "No evaluator available for objects of type {}", value.getClass().getName()); } /** * Gets the supported tokens on the given object. * * @param object the object for which to return the valid tokens * @return the tokens */ public static Set<String> tokens(Object object) { return getEvaluator(object.getClass()).map(evaluator -> evaluator.tokens(object)).orElse(ImmutableSet.of()); } //------------------------------------------------------------------------- // splits a value path into tokens for processing private static List<String> tokenize(String valuePath) { String[] tokens = valuePath.split(PATH_SEPARATOR); return ImmutableList.copyOf(tokens); } @SuppressWarnings("unchecked") private static Optional<TokenEvaluator<Object>> getEvaluator(Class<?> targetClass) { return EVALUATORS.stream() .filter(e -> e.getTargetType().isAssignableFrom(targetClass)) .map(e -> (TokenEvaluator<Object>) e) .findFirst(); } //------------------------------------------------------------------------- private ValuePathEvaluator() { } }
Avoid raw type in ValuePathEvaluator
modules/report/src/main/java/com/opengamma/strata/report/framework/expression/ValuePathEvaluator.java
Avoid raw type in ValuePathEvaluator
<ide><path>odules/report/src/main/java/com/opengamma/strata/report/framework/expression/ValuePathEvaluator.java <ide> import java.util.Optional; <ide> import java.util.Set; <ide> import java.util.stream.IntStream; <del>import java.util.stream.Stream; <ide> <ide> import com.google.common.collect.ImmutableList; <ide> import com.google.common.collect.ImmutableSet; <ide> * @param results the calculation results <ide> * @return the list of resolved results for each trade <ide> */ <del> @SuppressWarnings("unchecked") <ide> public static List<Result<?>> evaluate(String valuePath, ReportCalculationResults results) { <ide> List<String> tokens = tokenize(valuePath); <ide> <ide> results.getTrades().size(), <ide> Result.failure(FailureReason.INVALID_INPUT, "Column expressions must not be empty")); <ide> } <del> TokenEvaluator rootEvaluator = RootEvaluator.INSTANCE; <del> <ide> int rowCount = results.getCalculationResults().getRowCount(); <del> // javac 8u40 won't compile this if the call to collect() is chained after the call to mapToObj() <del> // but it works fine if the intermediate stream is assigned to a local variable. Compiler bug? <del> Stream<Result<?>> resultStream = IntStream.range(0, rowCount) <del> .mapToObj(rowIndex -> evaluate(tokens, rootEvaluator, new ResultsRow(results, rowIndex))); <del> return resultStream.collect(toImmutableList()); <add> return IntStream.range(0, rowCount) <add> .mapToObj(rowIndex -> evaluate(tokens, RootEvaluator.INSTANCE, new ResultsRow(results, rowIndex))) <add> .collect(toImmutableList()); <ide> } <ide> <ide> // Tokens always has at least one token <del> private static Result<?> evaluate(List<String> tokens, TokenEvaluator<Object> evaluator, Object target) { <add> private static <T> Result<?> evaluate(List<String> tokens, TokenEvaluator<T> evaluator, T target) { <ide> EvaluationResult evaluationResult = evaluator.evaluate(target, tokens.get(0), tokens.subList(1, tokens.size())); <ide> <ide> if (evaluationResult.isComplete()) {
JavaScript
apache-2.0
4e7f16f36fc96d2999ff818b84e99a256b2d0144
0
watson-developer-cloud/tone-analyzer-nodejs,watson-developer-cloud/tone-analyzer-nodejs,herchu/tone-analyzer-nodejs,herchu/tone-analyzer-nodejs
/** * Copyright 2015 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* global SAMPLE_TEXT:false, umviz:false, d3:false, $:false, WORD_TRAIT_CORR_TYPE:false, HIGHLIGHT_ANIMATION_DURATION:false, COLOR_SCHEMA:false */ 'use strict'; // DOM id for the tone visualization var vizId = '#visualization'; /** @type {d3.map()} global word - category mapping data structure for highlighting interaction */ var WORD_TO_CATEGORY = d3.map(), CATEGORY_TO_WORD = d3.map(); var SYNONYM_HOPS = 1, SYNONYM_LIMITS = 6; // Visualization var toneGenomeViz = new umviz.models.toneGenome() .width(880) .height(190) .margin({ top: -15, right: 50, bottom: 100, left: 45 }) .layoutMetric('count') .colorSchema(COLOR_SCHEMA); // Visualization container var mainViz = d3.select(vizId) .append('div') .classed('svg-container', true) //container class to make it responsive .append('svg') .attr('preserveAspectRatio', 'xMinYMin meet') //responsive SVG needs these 2 attributes and no width and height attr .attr('viewBox', '0 0 '+ toneGenomeViz.width() + ' ' + toneGenomeViz.height()) //class to make it responsive .classed('svg-content-responsive', true); // startup $(document).ready(function() { var $text = $('#textArea'), $loading = $('#loading'), $analyzeBtn = $('.analyze-btn'), $results = $('.results'), $jsonTab = $('.json-div'), $outputText = $('.text-output-div'), $outputTextLabel = $('.text-output-label'), $error = $('.error'), $errorMsg = $('.errorMsg'), $visualization = $(vizId); var CURRENT_TEXT = null; // current analyzed text var CURRENT_TONE = null; // current results var REPLACEABLE = null; // set initial text $text.val(SAMPLE_TEXT); function onAPIError(xhr) { var error; try { error = JSON.parse(xhr.responseText || {}); } catch(e) {} showError(error ? (error.error || error): ''); } $analyzeBtn.click(function() { $loading.show(); $results.hide(); /** * send the data to the Tone Analyzer API to get words * matched with LIWC categories; */ var text = $text.val(), $('.output-div')[0].scrollIntoView(true); // Boolean arguments $.post('/tone', {'text': text }) .done(function(response) { // save the json response in the JSON tab $jsonTab.html(JSON.stringify(response, null, 2)); //prepare the data processData(response); response.id = 'root'; CURRENT_TONE = response; doToneCheck(response, text); }) .fail(onAPIError) .always (function(){ $loading.hide(); // scroll to bottom $('.output-div')[0].scrollIntoView(true); // Boolean arguments }); }); /** * Display an error or a default message * @param {String} error The error */ function showError(error) { var defaultErrorMsg = 'Error processing the request, please try again later.'; $error.show(); $errorMsg.text(error || defaultErrorMsg); } /** * Updates the visualization with the tone analyzer results * * @param {Object} toneResponse: tone scores with linguistic evidence * @param {String} analyzedText: analyzed text */ function doToneCheck(toneResponse, analyzedText) { // If the list of words with any synonym in the system is available, keep it if (toneResponse.replaceable_words) { REPLACEABLE = {}; toneResponse.replaceable_words.forEach(function(w) { REPLACEABLE[w.toLowerCase()] = true; }); } else { REPLACEABLE = null; } $results.show(); CURRENT_TEXT = analyzedText; // normalize text var analyzedHtmlText = analyzedText.replace(/\r\n/g, '<br />').replace(/[\r\n]/g, '<br />'); // call visualization component mainViz.datum(toneResponse).call(toneGenomeViz); // add higlight span html tags for all matched words: WORD_TO_CATEGORY.keys().forEach(function(wd) { var cates = WORD_TO_CATEGORY.get(wd); if (cates !== undefined && cates instanceof Array) analyzedHtmlText = addPropertySpan(analyzedHtmlText, wd, cates.join(' ')); }); $outputText.html(analyzedHtmlText); //add highlight css for different categories CATEGORY_TO_WORD.keys().reverse().forEach(function(ele) { var cateName; if (ele.indexOf('_' + WORD_TRAIT_CORR_TYPE.positive) > 0) cateName = ele.substring(0, ele.indexOf('_' + WORD_TRAIT_CORR_TYPE.positive)); if (ele.indexOf('_' + WORD_TRAIT_CORR_TYPE.negative) > 0) cateName = ele.substring(0, ele.indexOf('_' + WORD_TRAIT_CORR_TYPE.negative)); $('.' + ele).css('color', COLOR_SCHEMA[cateName]); $('.' + ele).css('border', "1px solid "+COLOR_SCHEMA[cateName]); $('.' + ele).css('padding', '0.2em 0.5em 0.2em 0.5em'); $('.' + ele + ".replaceable").css('background-color', COLOR_SCHEMA[cateName]); $('.' + ele + ".replaceable").css('color', 'white'); }); $('.matched-word').mouseover(function() { highlightToneGenome($(this).attr('categories')); }); $('.matched-word').mouseout(function() { unhighlightToneGenome($(this).attr('categories')); }); setupSynonymExpansion(); } function addPropertySpan(data, search, stylecls) { var searchRgp = new RegExp('\\b(' + (search) + ')\\b', 'gi'); var match, matchIdxs = []; //store matches in the original text. var counter = -1; while ((match = searchRgp.exec(CURRENT_TEXT)) !== null) { matchIdxs.push(match.index); } function replacer(matchstr) { counter++; var replaceable = REPLACEABLE && REPLACEABLE[matchstr.toLowerCase()]; console.log("replacer", matchstr, replaceable); return '<span class="matched-word ' + (replaceable ? 'replaceable ' : '') + stylecls + '" categories="' + stylecls + '" offset = "' + matchIdxs[counter] + '">' + matchstr + '</span>'; } return data.replace(searchRgp, replacer); } /** * A function to get the context (array and idx) of a word in a text * @param {String} word the word to search * @param {int} offset * @return {Object} context array and offset */ function getContext(word, offset) { var result = { context: [], offset: -1 }, data = CURRENT_TEXT, pref = [], suf = [], contextHops = 2; //a reg exp alphanumeric, space or tab var charWithSpaceReg = /[\w\s\t]/i, wordBreakerReg = /[\s\t]/i; if (data !== null && data.length > 1) { var token = ''; var counter = 0; var c = 0; //search prefix context: if (offset > 0) { var i = offset - 1; counter = 0; c = data.charAt(i); while (i >= 0 && counter < contextHops && (charWithSpaceReg.exec(c) !== null)) { if (wordBreakerReg.exec(c) !== null && token.length > 0) { pref.unshift(token); counter++; token = ''; } if (wordBreakerReg.exec(c) === null) token = c + token; c = data.charAt(--i); } } token = ''; //serarch suffix context: if (offset < (data.length - word.length)) { var j = parseInt(offset) + parseInt(word.length); counter = 0; c = data.charAt(j); while (j <= (data.length - 1) && counter < contextHops && (charWithSpaceReg.exec(c) !== null)) { if (wordBreakerReg.exec(c) !== null && token.length > 0) { suf.push(token); counter++; token = ''; } if (wordBreakerReg.exec(c) === null) token = token.concat(c); c = data.charAt(++j); } } } if (pref.length > 0 || suf.length > 0) result.context = pref.concat([word], suf); result.offset = pref.length; return result; } function setupSynonymExpansion() { // on synonym word click $('.matched-word').click(function(event) { var _this = $(this); var cates = _this.attr('categories'), offset = _this.attr('offset'), word = _this.html().toLowerCase(); if ($(this).hasClass('suggested')) { event.preventDefault(); _this.popover('disable'); return; } word = (word === 'challenges' ? 'challenge' : word); //clean other pop-ups $('.pop').popover('hide') .removeClass('pop'); //get the context of this word: var cntxt = getContext(word, offset); $.ajax({ type: 'POST', data: JSON.stringify({ words: [word], limit: SYNONYM_LIMITS, // context: cntxt.context, // index: cntxt.offset, hops: SYNONYM_HOPS }), url: 'synonym', dataType: 'json', contentType: 'application/json', success: function(response) { $error.hide(); processSynonym(response, cates); }, error: onAPIError }); function processSynonym(allSyns, cates) { var $synonymTab = $('#synonymTabs'), $synonymContent = $('#synonymTabContent'); //clean the content first: $synonymContent.empty(); $synonymTab.empty(); //get synonym list for current categories var curTraitSyns = []; allSyns.forEach(function(e) { if (cates.toLowerCase().indexOf(e.trait.toLowerCase()) >= 0) curTraitSyns.push(e); }); if (!curTraitSyns.length) { _this.popover({ title: '<p>No synonyms available for ' + '<strong>' + word + '</strong></p>', placement: 'bottom', content: $('#synonymDiv').html(), html:true, }); //show the popover _this.popover('show').addClass('pop'); $('#closePopover').click(function() { _this.popover('hide') .removeClass('pop'); }); $('.popover')[0].scrollIntoView(); return; } curTraitSyns.forEach(function(ele) { var existingSyns = [], tabNaviTempl = '<li role="presentation"><a href="#TRAIT_ID_TO_REPLACE" aria-controls="TRAIT_ID_TO_REPLACE" role="tab" data-toggle="tab">TRAIT_ID_TO_REPLACE</a></li>', tabContentTempl = '<div role="tabpanel" class="tab-pane" id="TRAIT_ID_TO_REPLACE">TAB_CONTENT_TO_REPLACE</div>'; //generate tab nav $synonymTab.append(tabNaviTempl.replace(/TRAIT_ID_TO_REPLACE/g, ele.trait)); //generate tab content var synsListTempl = '<div class="list-group">LIST_CONTENT_TO_REPLACE</div>', synsListItemTempl = '<a class="list-group-item synonym-list-item" > <span class="badge badge-hidden">SYNONYM_WEIGHT</span>SYNONYM_CONTENT</a>', synsListItemContent = '', synsListGroup = ''; ele.synonyms.forEach(function(syn) { if (existingSyns.indexOf(syn.word) < 0) { existingSyns.push(syn.word); synsListItemContent += synsListItemTempl .replace(/SYNONYM_CONTENT/g, syn.word) .replace(/SYNONYM_WEIGHT/g, syn.weight.toFixed(2)); } }); synsListGroup = synsListTempl.replace(/LIST_CONTENT_TO_REPLACE/g, synsListItemContent); $synonymContent.append(tabContentTempl .replace(/TRAIT_ID_TO_REPLACE/g, ele.trait) .replace(/TAB_CONTENT_TO_REPLACE/g, synsListGroup)); }); _this.popover({ html: true, title: '<p>Suggested synonyms for ' + '<strong>' + word + '</strong> :</p>', content: $('#synonymDiv').html(), placement: 'bottom' }); //show the popover _this.popover('show').addClass('pop'); //show the first tab by default $('#synonymTabs a:first').tab('show'); $('.badge').each(function() { if (parseFloat($(this).html()) < 0) $(this).attr('class', 'badge badge-hidden badge-neg'); }); $('.synonym-list-item').click(function() { var synSelected = $(this).clone() //clone the element .children() //select all the children .remove() //remove all the children .end() //again go back to selected element .text(); $('div.modal-body').html('Are you sure you want to replace <strong>' + word + '</strong> with <strong>' + synSelected + '</strong>?'); $('#useSynModal').modal('show'); $('#confirmUseSyn').click(function() { $('#useSynModal').modal('hide'); _this.attr('orgWord', word); _this.css('background-color', '#ddd'); _this.css('color', 'black'); _this.addClass('suggested'); _this.html(synSelected); _this.popover('hide').removeClass('pop'); }); }); _this[0].scrollIntoView(); $('#closePopover').click(function() { _this.popover('hide') .removeClass('pop'); }); } //processSynonym }); } function highlightToneGenome(_cates) { var trait_cates = _cates.trim().split(' '); d3.select(vizId).selectAll('.g-block') .filter(function(sel) { // not in both positive(WORD_TRAIT_CORR_TYPE.positive) or // negative(WORD_TRAIT_CORR_TYPE.negative) categories return ($.inArray(sel.id + '_' + WORD_TRAIT_CORR_TYPE.positive, trait_cates) === -1) && ($.inArray(sel.id + '_' + WORD_TRAIT_CORR_TYPE.negative, trait_cates) === -1) ? true : false; }) .transition() .duration(HIGHLIGHT_ANIMATION_DURATION) .style('opacity', 0.1); d3.select(vizId).selectAll('.g-block-mixed-child') .filter(function(sel) { var _this = d3.select(this); if (($.inArray(sel.id + '_' + WORD_TRAIT_CORR_TYPE.negative, trait_cates) !== -1) && (_this.attr('corr') === WORD_TRAIT_CORR_TYPE.negative)) return false; if (($.inArray(sel.id + '_' + WORD_TRAIT_CORR_TYPE.positive, trait_cates) !== -1) && (_this.attr('corr') === WORD_TRAIT_CORR_TYPE.positive)) return false; return true; }) .transition() .duration(HIGHLIGHT_ANIMATION_DURATION) .style('opacity', 0.1); } function unhighlightToneGenome() { d3.select(vizId).selectAll('.g-block') .transition() .duration(HIGHLIGHT_ANIMATION_DURATION) .style('opacity', 1); d3.select(vizId).selectAll('.g-block-mixed-child') .transition() .duration(HIGHLIGHT_ANIMATION_DURATION) .style('opacity', 1); } function processData(traits) { if (traits.children === undefined) { //leaf node traits.mixedNode = traits.linguistic_evidence.length > 1 ? true : false; //use the score to calculate layout traits.linguistic_evidence.forEach(function(el) { if (el.correlation === WORD_TRAIT_CORR_TYPE.positive) { //extract trait-word mapping CATEGORY_TO_WORD.set(traits.id + '_' + WORD_TRAIT_CORR_TYPE.positive, el.words); //extract word-trait mapping if (el.words) { el.words.forEach(function(w) { var curCates = WORD_TO_CATEGORY.get(w); if (curCates === undefined) WORD_TO_CATEGORY.set(w, [traits.id + '_' + WORD_TRAIT_CORR_TYPE.positive]); else if ($.inArray(traits.id + '_' + WORD_TRAIT_CORR_TYPE.positive, curCates) === -1) { //not existing curCates.push(traits.id + '_' + WORD_TRAIT_CORR_TYPE.positive); WORD_TO_CATEGORY.set(w, curCates); } }); } } if (el.correlation === WORD_TRAIT_CORR_TYPE.negative) { //extract trait-word mapping CATEGORY_TO_WORD.set(traits.id + '_' + WORD_TRAIT_CORR_TYPE.negative, el.words); //extract word-trait mapping el.words.forEach(function(w) { var curCates = WORD_TO_CATEGORY.get(w); if (curCates === undefined) WORD_TO_CATEGORY.set(w, [traits.id + '_' + WORD_TRAIT_CORR_TYPE.negative]); else if ($.inArray(traits.id + '_' + WORD_TRAIT_CORR_TYPE.negative, curCates) === -1) { //not existing curCates.push(traits.id + '_' + WORD_TRAIT_CORR_TYPE.negative); WORD_TO_CATEGORY.set(w, curCates); } }); } }); } else { //recursive do the data process traits.children.forEach(processData); } } $('.metric-count').click(function setMetricCount() { toneGenomeViz.layoutMetric('count'); mainViz.datum(CURRENT_TONE).call(toneGenomeViz); }); $('.metric-percentile').click(function setMetricPercentile() { toneGenomeViz.layoutMetric('percentile'); mainViz.datum(CURRENT_TONE).call(toneGenomeViz); }); $('.nav-tabs a').click(function() { setTimeout(function() { if ($('#json').hasClass('active')) { $visualization.hide(); $outputTextLabel.hide(); $outputText.hide(); } else { $visualization.show(); $outputTextLabel.show(); $outputText.show(); } }, 30); }); });
public/js/index.js
/** * Copyright 2015 IBM Corp. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* global SAMPLE_TEXT:false, umviz:false, d3:false, $:false, WORD_TRAIT_CORR_TYPE:false, HIGHLIGHT_ANIMATION_DURATION:false, COLOR_SCHEMA:false */ 'use strict'; // DOM id for the tone visualization var vizId = '#visualization'; /** @type {d3.map()} global word - category mapping data structure for highlighting interaction */ var WORD_TO_CATEGORY = d3.map(), CATEGORY_TO_WORD = d3.map(); var SYNONYM_HOPS = 1, SYNONYM_LIMITS = 6; // Visualization var toneGenomeViz = new umviz.models.toneGenome() .width(880) .height(190) .margin({ top: -15, right: 50, bottom: 100, left: 45 }) .layoutMetric('count') .colorSchema(COLOR_SCHEMA); // Visualization container var mainViz = d3.select(vizId) .append('div') .classed('svg-container', true) //container class to make it responsive .append('svg') .attr('preserveAspectRatio', 'xMinYMin meet') //responsive SVG needs these 2 attributes and no width and height attr .attr('viewBox', '0 0 '+ toneGenomeViz.width() + ' ' + toneGenomeViz.height()) //class to make it responsive .classed('svg-content-responsive', true); // startup $(document).ready(function() { var $text = $('#textArea'), $loading = $('#loading'), $analyzeBtn = $('.analyze-btn'), $results = $('.results'), $jsonTab = $('.json-div'), $outputText = $('.text-output-div'), $outputTextLabel = $('.text-output-label'), $error = $('.error'), $errorMsg = $('.errorMsg'), $visualization = $(vizId); var CURRENT_TEXT = null; // current analyzed text var CURRENT_TONE = null; // current results var REPLACEABLE = null; // set initial text $text.val(SAMPLE_TEXT); function onAPIError(xhr) { var error; try { error = JSON.parse(xhr.responseText || {}); } catch(e) {} showError(error ? (error.error || error): ''); } $analyzeBtn.click(function() { $loading.show(); $results.hide(); /** * send the data to the Tone Analyzer API to get words * matched with LIWC categories; */ var text = $text.val(), CURRENT_TEXT = text; $('.output-div')[0].scrollIntoView(true); // Boolean arguments $.post('/tone', {'text': text }) .done(function(response) { // save the json response in the JSON tab $jsonTab.html(JSON.stringify(response, null, 2)); //prepare the data processData(response); response.id = 'root'; CURRENT_TONE = response; doToneCheck(response, text); }) .fail(onAPIError) .always (function(){ $loading.hide(); // scroll to bottom $('.output-div')[0].scrollIntoView(true); // Boolean arguments }); }); /** * Display an error or a default message * @param {String} error The error */ function showError(error) { var defaultErrorMsg = 'Error processing the request, please try again later.'; $error.show(); $errorMsg.text(error || defaultErrorMsg); } /** * Updates the visualization with the tone analyzer results * * @param {Object} toneResponse: tone scores with linguistic evidence * @param {String} analyzedText: analyzed text */ function doToneCheck(toneResponse, analyzedText) { // If the list of words with any synonym in the system is available, keep it if (toneResponse.replaceable_words) { REPLACEABLE = {}; toneResponse.replaceable_words.forEach(function(w) { REPLACEABLE[w.toLowerCase()] = true; }); } else { REPLACEABLE = null; } $results.show(); CURRENT_TEXT = analyzedText; // normalize text var analyzedHtmlText = analyzedText.replace(/\r\n/g, '<br />').replace(/[\r\n]/g, '<br />'); // call visualization component mainViz.datum(toneResponse).call(toneGenomeViz); // add higlight span html tags for all matched words: WORD_TO_CATEGORY.keys().forEach(function(wd) { var cates = WORD_TO_CATEGORY.get(wd); if (cates !== undefined && cates instanceof Array) analyzedHtmlText = addPropertySpan(analyzedHtmlText, wd, cates.join(' ')); }); $outputText.html(analyzedHtmlText); //add highlight css for different categories CATEGORY_TO_WORD.keys().reverse().forEach(function(ele) { var cateName; if (ele.indexOf('_' + WORD_TRAIT_CORR_TYPE.positive) > 0) cateName = ele.substring(0, ele.indexOf('_' + WORD_TRAIT_CORR_TYPE.positive)); if (ele.indexOf('_' + WORD_TRAIT_CORR_TYPE.negative) > 0) cateName = ele.substring(0, ele.indexOf('_' + WORD_TRAIT_CORR_TYPE.negative)); $('.' + ele).css('color', COLOR_SCHEMA[cateName]); $('.' + ele).css('border', "1px solid "+COLOR_SCHEMA[cateName]); $('.' + ele).css('padding', '0.2em 0.5em 0.2em 0.5em'); $('.' + ele + ".replaceable").css('background-color', COLOR_SCHEMA[cateName]); $('.' + ele + ".replaceable").css('color', 'white'); }); $('.matched-word').mouseover(function() { highlightToneGenome($(this).attr('categories')); }); $('.matched-word').mouseout(function() { unhighlightToneGenome($(this).attr('categories')); }); setupSynonymExpansion(); } function addPropertySpan(data, search, stylecls) { var searchRgp = new RegExp('\\b(' + (search) + ')\\b', 'gi'); var match, matchIdxs = []; //store matches in the original text. var counter = -1; while ((match = searchRgp.exec(CURRENT_TEXT)) !== null) { matchIdxs.push(match.index); } function replacer(matchstr) { counter++; var replaceable = REPLACEABLE && REPLACEABLE[matchstr.toLowerCase()]; console.log("replacer", matchstr, replaceable); return '<span class="matched-word ' + (replaceable ? 'replaceable ' : '') + stylecls + '" categories="' + stylecls + '" offset = "' + matchIdxs[counter] + '">' + matchstr + '</span>'; } return data.replace(searchRgp, replacer); } /** * A function to get the context (array and idx) of a word in a text * @param {String} word the word to search * @param {int} offset * @return {Object} context array and offset */ function getContext(word, offset) { var result = { context: [], offset: -1 }, data = CURRENT_TEXT, pref = [], suf = [], contextHops = 2; //a reg exp alphanumeric, space or tab var charWithSpaceReg = /[\w\s\t]/i, wordBreakerReg = /[\s\t]/i; if (data !== null && data.length > 1) { var token = ''; var counter = 0; var c = 0; //search prefix context: if (offset > 0) { var i = offset - 1; counter = 0; c = data.charAt(i); while (i >= 0 && counter < contextHops && (charWithSpaceReg.exec(c) !== null)) { if (wordBreakerReg.exec(c) !== null && token.length > 0) { pref.unshift(token); counter++; token = ''; } if (wordBreakerReg.exec(c) === null) token = c + token; c = data.charAt(--i); } } token = ''; //serarch suffix context: if (offset < (data.length - word.length)) { var j = parseInt(offset) + parseInt(word.length); counter = 0; c = data.charAt(j); while (j <= (data.length - 1) && counter < contextHops && (charWithSpaceReg.exec(c) !== null)) { if (wordBreakerReg.exec(c) !== null && token.length > 0) { suf.push(token); counter++; token = ''; } if (wordBreakerReg.exec(c) === null) token = token.concat(c); c = data.charAt(++j); } } } if (pref.length > 0 || suf.length > 0) result.context = pref.concat([word], suf); result.offset = pref.length; return result; } function setupSynonymExpansion() { // on synonym word click $('.matched-word').click(function(event) { var _this = $(this); var cates = _this.attr('categories'), offset = _this.attr('offset'), word = _this.html().toLowerCase(); if ($(this).hasClass('suggested')) { event.preventDefault(); _this.popover('disable'); return; } word = (word === 'challenges' ? 'challenge' : word); //clean other pop-ups $('.pop').popover('hide') .removeClass('pop'); //get the context of this word: var cntxt = getContext(word, offset); $.ajax({ type: 'POST', data: JSON.stringify({ words: [word], limit: SYNONYM_LIMITS, // context: cntxt.context, // index: cntxt.offset, hops: SYNONYM_HOPS }), url: 'synonym', dataType: 'json', contentType: 'application/json', success: function(response) { $error.hide(); processSynonym(response, cates); }, error: onAPIError }); function processSynonym(allSyns, cates) { var $synonymTab = $('#synonymTabs'), $synonymContent = $('#synonymTabContent'); //clean the content first: $synonymContent.empty(); $synonymTab.empty(); //get synonym list for current categories var curTraitSyns = []; allSyns.forEach(function(e) { if (cates.toLowerCase().indexOf(e.trait.toLowerCase()) >= 0) curTraitSyns.push(e); }); if (!curTraitSyns.length) { _this.popover({ title: '<p>No synonyms available for ' + '<strong>' + word + '</strong></p>', placement: 'bottom', content: $('#synonymDiv').html(), html:true, }); //show the popover _this.popover('show').addClass('pop'); $('#closePopover').click(function() { _this.popover('hide') .removeClass('pop'); }); $('.popover')[0].scrollIntoView(); return; } curTraitSyns.forEach(function(ele) { var existingSyns = [], tabNaviTempl = '<li role="presentation"><a href="#TRAIT_ID_TO_REPLACE" aria-controls="TRAIT_ID_TO_REPLACE" role="tab" data-toggle="tab">TRAIT_ID_TO_REPLACE</a></li>', tabContentTempl = '<div role="tabpanel" class="tab-pane" id="TRAIT_ID_TO_REPLACE">TAB_CONTENT_TO_REPLACE</div>'; //generate tab nav $synonymTab.append(tabNaviTempl.replace(/TRAIT_ID_TO_REPLACE/g, ele.trait)); //generate tab content var synsListTempl = '<div class="list-group">LIST_CONTENT_TO_REPLACE</div>', synsListItemTempl = '<a class="list-group-item synonym-list-item" > <span class="badge badge-hidden">SYNONYM_WEIGHT</span>SYNONYM_CONTENT</a>', synsListItemContent = '', synsListGroup = ''; ele.synonyms.forEach(function(syn) { if (existingSyns.indexOf(syn.word) < 0) { existingSyns.push(syn.word); synsListItemContent += synsListItemTempl .replace(/SYNONYM_CONTENT/g, syn.word) .replace(/SYNONYM_WEIGHT/g, syn.weight.toFixed(2)); } }); synsListGroup = synsListTempl.replace(/LIST_CONTENT_TO_REPLACE/g, synsListItemContent); $synonymContent.append(tabContentTempl .replace(/TRAIT_ID_TO_REPLACE/g, ele.trait) .replace(/TAB_CONTENT_TO_REPLACE/g, synsListGroup)); }); _this.popover({ html: true, title: '<p>Suggested synonyms for ' + '<strong>' + word + '</strong> :</p>', content: $('#synonymDiv').html(), placement: 'bottom' }); //show the popover _this.popover('show').addClass('pop'); //show the first tab by default $('#synonymTabs a:first').tab('show'); $('.badge').each(function() { if (parseFloat($(this).html()) < 0) $(this).attr('class', 'badge badge-hidden badge-neg'); }); $('.synonym-list-item').click(function() { var synSelected = $(this).clone() //clone the element .children() //select all the children .remove() //remove all the children .end() //again go back to selected element .text(); $('div.modal-body').html('Are you sure you want to replace <strong>' + word + '</strong> with <strong>' + synSelected + '</strong>?'); $('#useSynModal').modal('show'); $('#confirmUseSyn').click(function() { $('#useSynModal').modal('hide'); _this.attr('orgWord', word); _this.css('background-color', '#ddd'); _this.css('color', 'black'); _this.addClass('suggested'); _this.html(synSelected); _this.popover('hide').removeClass('pop'); }); }); _this[0].scrollIntoView(); $('#closePopover').click(function() { _this.popover('hide') .removeClass('pop'); }); } //processSynonym }); } function highlightToneGenome(_cates) { var trait_cates = _cates.trim().split(' '); d3.select(vizId).selectAll('.g-block') .filter(function(sel) { // not in both positive(WORD_TRAIT_CORR_TYPE.positive) or // negative(WORD_TRAIT_CORR_TYPE.negative) categories return ($.inArray(sel.id + '_' + WORD_TRAIT_CORR_TYPE.positive, trait_cates) === -1) && ($.inArray(sel.id + '_' + WORD_TRAIT_CORR_TYPE.negative, trait_cates) === -1) ? true : false; }) .transition() .duration(HIGHLIGHT_ANIMATION_DURATION) .style('opacity', 0.1); d3.select(vizId).selectAll('.g-block-mixed-child') .filter(function(sel) { var _this = d3.select(this); if (($.inArray(sel.id + '_' + WORD_TRAIT_CORR_TYPE.negative, trait_cates) !== -1) && (_this.attr('corr') === WORD_TRAIT_CORR_TYPE.negative)) return false; if (($.inArray(sel.id + '_' + WORD_TRAIT_CORR_TYPE.positive, trait_cates) !== -1) && (_this.attr('corr') === WORD_TRAIT_CORR_TYPE.positive)) return false; return true; }) .transition() .duration(HIGHLIGHT_ANIMATION_DURATION) .style('opacity', 0.1); } function unhighlightToneGenome() { d3.select(vizId).selectAll('.g-block') .transition() .duration(HIGHLIGHT_ANIMATION_DURATION) .style('opacity', 1); d3.select(vizId).selectAll('.g-block-mixed-child') .transition() .duration(HIGHLIGHT_ANIMATION_DURATION) .style('opacity', 1); } function processData(traits) { if (traits.children === undefined) { //leaf node traits.mixedNode = traits.linguistic_evidence.length > 1 ? true : false; //use the score to calculate layout traits.linguistic_evidence.forEach(function(el) { if (el.correlation === WORD_TRAIT_CORR_TYPE.positive) { //extract trait-word mapping CATEGORY_TO_WORD.set(traits.id + '_' + WORD_TRAIT_CORR_TYPE.positive, el.words); //extract word-trait mapping if (el.words) { el.words.forEach(function(w) { var curCates = WORD_TO_CATEGORY.get(w); if (curCates === undefined) WORD_TO_CATEGORY.set(w, [traits.id + '_' + WORD_TRAIT_CORR_TYPE.positive]); else if ($.inArray(traits.id + '_' + WORD_TRAIT_CORR_TYPE.positive, curCates) === -1) { //not existing curCates.push(traits.id + '_' + WORD_TRAIT_CORR_TYPE.positive); WORD_TO_CATEGORY.set(w, curCates); } }); } } if (el.correlation === WORD_TRAIT_CORR_TYPE.negative) { //extract trait-word mapping CATEGORY_TO_WORD.set(traits.id + '_' + WORD_TRAIT_CORR_TYPE.negative, el.words); //extract word-trait mapping el.words.forEach(function(w) { var curCates = WORD_TO_CATEGORY.get(w); if (curCates === undefined) WORD_TO_CATEGORY.set(w, [traits.id + '_' + WORD_TRAIT_CORR_TYPE.negative]); else if ($.inArray(traits.id + '_' + WORD_TRAIT_CORR_TYPE.negative, curCates) === -1) { //not existing curCates.push(traits.id + '_' + WORD_TRAIT_CORR_TYPE.negative); WORD_TO_CATEGORY.set(w, curCates); } }); } }); } else { //recursive do the data process traits.children.forEach(processData); } } $('.metric-count').click(function setMetricCount() { toneGenomeViz.layoutMetric('count'); mainViz.datum(CURRENT_TONE).call(toneGenomeViz); }); $('.metric-percentile').click(function setMetricPercentile() { toneGenomeViz.layoutMetric('percentile'); mainViz.datum(CURRENT_TONE).call(toneGenomeViz); }); $('.nav-tabs a').click(function() { setTimeout(function() { if ($('#json').hasClass('active')) { $visualization.hide(); $outputTextLabel.hide(); $outputText.hide(); } else { $visualization.show(); $outputTextLabel.show(); $outputText.show(); } }, 30); }); });
2. fix the context and offset (but not test since without a valid local API test env)
public/js/index.js
2. fix the context and offset (but not test since without a valid local API test env)
<ide><path>ublic/js/index.js <ide> * matched with LIWC categories; <ide> */ <ide> var text = $text.val(), <del> CURRENT_TEXT = text; <del> <add> <ide> $('.output-div')[0].scrollIntoView(true); // Boolean arguments <ide> <ide> $.post('/tone', {'text': text })
JavaScript
agpl-3.0
4fcc1e9fabc3ed28af6acc7b1690b61036d7f92c
0
WoWAnalyzer/WoWAnalyzer,anom0ly/WoWAnalyzer,fyruna/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,yajinni/WoWAnalyzer,yajinni/WoWAnalyzer,Juko8/WoWAnalyzer,anom0ly/WoWAnalyzer,Juko8/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,ronaldpereira/WoWAnalyzer,sMteX/WoWAnalyzer,fyruna/WoWAnalyzer,yajinni/WoWAnalyzer,Juko8/WoWAnalyzer,fyruna/WoWAnalyzer,ronaldpereira/WoWAnalyzer,anom0ly/WoWAnalyzer,sMteX/WoWAnalyzer,yajinni/WoWAnalyzer,sMteX/WoWAnalyzer,anom0ly/WoWAnalyzer,ronaldpereira/WoWAnalyzer
import { Juko8 } from 'CONTRIBUTORS'; import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; export default [ { date: new Date('2019-01-02'), changes: <>Added Azerite statistic for <SpellLink id={SPELLS.FURY_OF_XUEN.id} />.</>, contributors: [Juko8], }, { date: new Date('2018-12-27'), changes: <>Added Azerite statistic for <SpellLink id={SPELLS.GLORY_OF_THE_DAWN.id} />.</>, contributors: [Juko8], }, { date: new Date('2018-09-09'), changes: 'Added Azerite statistic for Swift Roundhouse.', contributors: [Juko8], }, { date: new Date('2018-09-04'), changes: 'Added Azerite statistics for Iron Fists and Meridian Strikes.', contributors: [Juko8], }, { date: new Date('2018-08-31'), changes: 'Removed "Casts in Storm, Earth and Fire/Serenity statistics" since it\'s no longer providing accurate analysis', contributors: [Juko8], }, { date: new Date('2018-08-29'), changes: 'Removed legion legendaries and tiersets', contributors: [Juko8], }, { date: new Date('2018-06-16'), changes: <>Updated for 8.0 Battle for Azeroth prepatch. All artifact traits and related analysis removed. Bad <SpellLink id={SPELLS.BLACKOUT_KICK.id} icon /> casts statistic and suggestions has been replaced with statistic and suggestions on <SpellLink id={SPELLS.BLACKOUT_KICK.id} icon />'s new cooldown reductions mechanic </>, contributors: [Juko8], }, ];
src/parser/monk/windwalker/CHANGELOG.js
import { Juko8 } from 'CONTRIBUTORS'; import React from 'react'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; export default [ { date: new Date('2018-09-09'), changes: <>Added Azerite statistic for Swift Roundhouse.</>, contributors: [Juko8], }, { date: new Date('2018-09-04'), changes: <>Added Azerite statistics for Iron Fists and Meridian Strikes.</>, contributors: [Juko8], }, { date: new Date('2018-08-31'), changes: 'Removed "Casts in Storm, Earth and Fire/Serenity statistics" since it\'s no longer providing accurate analysis', contributors: [Juko8], }, { date: new Date('2018-08-29'), changes: 'Removed legion legendaries and tiersets', contributors: [Juko8], }, { date: new Date('2018-06-16'), changes: <>Updated for 8.0 Battle for Azeroth prepatch. All artifact traits and related analysis removed. Bad <SpellLink id={SPELLS.BLACKOUT_KICK.id} icon /> casts statistic and suggestions has been replaced with statistic and suggestions on <SpellLink id={SPELLS.BLACKOUT_KICK.id} icon />'s new cooldown reductions mechanic </>, contributors: [Juko8], }, ];
Update CHANGELOG.js
src/parser/monk/windwalker/CHANGELOG.js
Update CHANGELOG.js
<ide><path>rc/parser/monk/windwalker/CHANGELOG.js <ide> <ide> export default [ <ide> { <add> date: new Date('2019-01-02'), <add> changes: <>Added Azerite statistic for <SpellLink id={SPELLS.FURY_OF_XUEN.id} />.</>, <add> contributors: [Juko8], <add> }, <add> { <add> date: new Date('2018-12-27'), <add> changes: <>Added Azerite statistic for <SpellLink id={SPELLS.GLORY_OF_THE_DAWN.id} />.</>, <add> contributors: [Juko8], <add> }, <add> { <ide> date: new Date('2018-09-09'), <del> changes: <>Added Azerite statistic for Swift Roundhouse.</>, <add> changes: 'Added Azerite statistic for Swift Roundhouse.', <ide> contributors: [Juko8], <ide> }, <ide> { <ide> date: new Date('2018-09-04'), <del> changes: <>Added Azerite statistics for Iron Fists and Meridian Strikes.</>, <add> changes: 'Added Azerite statistics for Iron Fists and Meridian Strikes.', <ide> contributors: [Juko8], <ide> }, <ide> {
Java
apache-2.0
16e415318aaa2f3d718fd6f0b98da4f1be44104e
0
DevStreet/FinanceAnalytics,McLeodMoores/starling,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,nssales/OG-Platform,codeaudit/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,jeorme/OG-Platform,jerome79/OG-Platform,ChinaQuants/OG-Platform,jeorme/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,codeaudit/OG-Platform,McLeodMoores/starling,ChinaQuants/OG-Platform,jerome79/OG-Platform,jerome79/OG-Platform,nssales/OG-Platform,codeaudit/OG-Platform,jerome79/OG-Platform,codeaudit/OG-Platform,jeorme/OG-Platform,nssales/OG-Platform,DevStreet/FinanceAnalytics
/** * Copyright (C) 2009 - 2009 by OpenGamma Inc. * * Please see distribution for license. */ package com.opengamma.financial.security.db; import java.util.Date; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.builder.ToStringBuilder; /** * * * @author jim */ public class IdentifierAssociationBean { private Long _id; private SecurityBean _security; private IdentifierBean _identifier; private Date _validStartDate; // inclusive private Date _validEndDate; // not inclusive public IdentifierAssociationBean() { } public IdentifierAssociationBean(SecurityBean security, IdentifierBean identifier) { _security = security; _identifier = identifier; } public Long getId() { return _id; } public void setId(Long id) { _id = id; } public IdentifierBean getIdentifier() { return _identifier; } public void setIdentifier(IdentifierBean identifier) { _identifier = identifier; } public SecurityBean getSecurity() { return _security; } public void setSecurity(SecurityBean security) { _security = security; } public Date getValidStartDate() { return _validStartDate; } public void setValidStartDate(final Date validStartDate) { _validStartDate = validStartDate; } public Date getValidEndDate() { return _validEndDate; } public void setValidEndDate(final Date validEndDate) { _validEndDate = validEndDate; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((_id == null) ? 0 : _id.hashCode()); result = prime * result + ((_security == null) ? 0 : _security.hashCode()); result = prime * result + ((_identifier == null) ? 0 : _identifier.hashCode()); result = prime * result + ((_validStartDate == null) ? 0 : _validStartDate.hashCode()); result = prime * result + ((_validEndDate == null) ? 0 : _validEndDate.hashCode()); return result; } //note this will match objects with different id's as long as the domain and identifier are the same. public boolean equals(Object other) { if (!(other instanceof IdentifierAssociationBean)) { return false; } IdentifierAssociationBean otherBean = (IdentifierAssociationBean) other; if (ObjectUtils.equals(otherBean.getId(), getId())) { return true; } if (ObjectUtils.equals(otherBean.getSecurity(), getSecurity()) && ObjectUtils.equals(otherBean.getIdentifier(), getIdentifier()) && ObjectUtils.equals(otherBean.getValidStartDate(), getValidStartDate()) && ObjectUtils.equals(otherBean.getValidEndDate(), getValidEndDate())) { return true; } return false; } public String toString() { return ToStringBuilder.reflectionToString(this); } }
src/com/opengamma/financial/security/db/IdentifierAssociationBean.java
/** * Copyright (C) 2009 - 2009 by OpenGamma Inc. * * Please see distribution for license. */ package com.opengamma.financial.security.db; import java.util.Date; import org.apache.commons.lang.ObjectUtils; import org.apache.commons.lang.builder.ToStringBuilder; /** * * * @author jim */ public class IdentifierAssociationBean { private Long _id = null; private SecurityBean _security = null; private IdentifierBean _identifier = null; private Date _validStartDate = null; // inclusive private Date _validEndDate = null; // not inclusive public IdentifierAssociationBean() { } public IdentifierAssociationBean(SecurityBean security, IdentifierBean identifier) { _security = security; _identifier = identifier; } public Long getId() { return _id; } public void setId(Long id) { _id = id; } public IdentifierBean getIdentifier() { return _identifier; } public void setIdentifier(IdentifierBean identifier) { _identifier = identifier; } public SecurityBean getSecurity() { return _security; } public void setSecurity(SecurityBean security) { _security = security; } public Date getValidStartDate () { return _validStartDate; } public void setValidStartDate (final Date validStartDate) { _validStartDate = validStartDate; } public Date getValidEndDate () { return _validEndDate; } public void setValidEndDate (final Date validEndDate) { _validEndDate = validEndDate; } // note this will match objects with different id's as long as the domain and identifier are the same. public boolean equals(Object other) { if (!(other instanceof IdentifierAssociationBean)) { return false; } IdentifierAssociationBean otherBean = (IdentifierAssociationBean) other; if (ObjectUtils.equals(otherBean.getId(), getId())) { return true; } if (ObjectUtils.equals(otherBean.getSecurity(), getSecurity()) && ObjectUtils.equals(otherBean.getIdentifier(), getIdentifier()) && ObjectUtils.equals(otherBean.getValidStartDate(), getValidStartDate()) && ObjectUtils.equals(otherBean.getValidStartDate(), getValidStartDate())) { return true; } return false; } public String toString() { return ToStringBuilder.reflectionToString(this); } }
added hashCode() implementation
src/com/opengamma/financial/security/db/IdentifierAssociationBean.java
added hashCode() implementation
<ide><path>rc/com/opengamma/financial/security/db/IdentifierAssociationBean.java <ide> * @author jim <ide> */ <ide> public class IdentifierAssociationBean { <del> private Long _id = null; <del> private SecurityBean _security = null; <del> private IdentifierBean _identifier = null; <del> private Date _validStartDate = null; // inclusive <del> private Date _validEndDate = null; // not inclusive <add> private Long _id; <add> private SecurityBean _security; <add> private IdentifierBean _identifier; <add> private Date _validStartDate; // inclusive <add> private Date _validEndDate; // not inclusive <ide> <ide> public IdentifierAssociationBean() { <ide> } <ide> _security = security; <ide> } <ide> <del> public Date getValidStartDate () { <add> public Date getValidStartDate() { <ide> return _validStartDate; <ide> } <ide> <del> public void setValidStartDate (final Date validStartDate) { <add> public void setValidStartDate(final Date validStartDate) { <ide> _validStartDate = validStartDate; <ide> } <ide> <del> public Date getValidEndDate () { <add> public Date getValidEndDate() { <ide> return _validEndDate; <ide> } <ide> <del> public void setValidEndDate (final Date validEndDate) { <add> public void setValidEndDate(final Date validEndDate) { <ide> _validEndDate = validEndDate; <ide> } <ide> <del> // note this will match objects with different id's as long as the domain and identifier are the same. <add> @Override <add> public int hashCode() { <add> final int prime = 31; <add> int result = 1; <add> result = prime * result + ((_id == null) ? 0 : _id.hashCode()); <add> result = prime * result + ((_security == null) ? 0 : _security.hashCode()); <add> result = prime * result + ((_identifier == null) ? 0 : _identifier.hashCode()); <add> result = prime * result + ((_validStartDate == null) ? 0 : _validStartDate.hashCode()); <add> result = prime * result + ((_validEndDate == null) ? 0 : _validEndDate.hashCode()); <add> return result; <add> } <add> <add> //note this will match objects with different id's as long as the domain and identifier are the same. <ide> public boolean equals(Object other) { <ide> if (!(other instanceof IdentifierAssociationBean)) { <ide> return false; <ide> if (ObjectUtils.equals(otherBean.getSecurity(), getSecurity()) && <ide> ObjectUtils.equals(otherBean.getIdentifier(), getIdentifier()) && <ide> ObjectUtils.equals(otherBean.getValidStartDate(), getValidStartDate()) && <del> ObjectUtils.equals(otherBean.getValidStartDate(), getValidStartDate())) { <add> ObjectUtils.equals(otherBean.getValidEndDate(), getValidEndDate())) { <ide> return true; <ide> } <ide> return false; <ide> } <del> <add> <ide> public String toString() { <ide> return ToStringBuilder.reflectionToString(this); <ide> }
JavaScript
mit
94daee67579d6dccc54f21868401868fb4e5f752
0
cpojer/mootools-filemanager,cpojer/mootools-filemanager
/* --- name: Fx.ProgressBar description: Fx.ProgressBar requires: [Core/Fx.Transitions, Core/Fx, Core/Class] provides: [Fx.ProgressBar] version: 1.1 license: MIT License author: Harald Kirschner <http://digitarald.de> ... */ Fx.ProgressBar = new Class({ Extends: Fx, options: { text: null, url: null, transition: Fx.Transitions.Circ.easeOut, fit: true, link: 'cancel' }, initialize: function(element, options) { this.element = $(element); this.parent(options); var url = this.options.url; if (url) { this.element.setStyles({ 'background-image': 'url(' + url + ')', 'background-repeat': 'no-repeat' }); } if (this.options.fit) { url = url || this.element.getStyle('background-image').replace(/^url\(["']?|["']?\)$/g, ''); if (url) { var fill = new Image(); fill.onload = function() { this.fill = fill.width; fill = fill.onload = null; this.set(this.now || 0); }.bind(this); fill.src = url; if (!this.fill && fill.width) fill.onload(); } } else { this.set(0); } }, start: function(to, total) { return this.parent(this.now, (arguments.length == 1 || !total) ? to.limit(0, 100) : to / total * 100); }, set: function(to) { this.now = to; var css = (this.fill) ? (((this.fill / -2) + (to / 100) * (this.element.width || 1) || 0).round() + 'px') : ((100 - to) + '%'); this.element.setStyle('backgroundPosition', css + ' 0px').title = Math.round(to) + '%'; var text = $(this.options.text); if (text) text.set('text', Math.round(to) + '%'); return this; } });
Source/Uploader/Fx.ProgressBar.js
/* --- name: Fx.ProgressBar description: Fx.ProgressBar requires: [Core/Fx.Transitions, Core/Fx, Core/Class] provides: [Fx.ProgressBar] version: 1.1 license: MIT License author: Harald Kirschner <http://digitarald.de> ... */ Fx.ProgressBar = new Class({ Extends: Fx, options: { text: null, url: null, transition: Fx.Transitions.Circ.easeOut, fit: true, link: 'cancel' }, initialize: function(element, options) { this.element = $(element); this.parent(options); var url = this.options.url; if (url) { this.element.setStyles({ 'background-image': 'url(' + url + ')', 'background-repeat': 'no-repeat' }); } if (this.options.fit) { url = url || this.element.getStyle('background-image').replace(/^url\(["']?|["']?\)$/g, ''); if (url) { var fill = new Image(); fill.onload = function() { this.fill = fill.width; fill = fill.onload = null; this.set(this.now || 0); }.bind(this); fill.src = url; if (!this.fill && fill.width) fill.onload(); } } else { this.set(0); } }, start: function(to, total) { return this.parent(this.now, (!total) ? to.limit(0, 100) : to / total * 100); }, set: function(to) { this.now = to; var css = (this.fill) ? (((this.fill / -2) + (to / 100) * (this.element.width || 1) || 0).round() + 'px') : ((100 - to) + '%'); this.element.setStyle('backgroundPosition', css + ' 0px').title = Math.round(to) + '%'; var text = $(this.options.text); if (text) text.set('text', Math.round(to) + '%'); return this; } });
bugfix for previous fancyupload merge: BOTH the argument list length check AND the 'total' value (division by zero!) should be checked.
Source/Uploader/Fx.ProgressBar.js
bugfix for previous fancyupload merge: BOTH the argument list length check AND the 'total' value (division by zero!) should be checked.
<ide><path>ource/Uploader/Fx.ProgressBar.js <ide> }, <ide> <ide> start: function(to, total) { <del> return this.parent(this.now, (!total) ? to.limit(0, 100) : to / total * 100); <add> return this.parent(this.now, (arguments.length == 1 || !total) ? to.limit(0, 100) : to / total * 100); <ide> }, <ide> <ide> set: function(to) {
JavaScript
cc0-1.0
e1842b77bf11960ebbbe335ec9ee6f65a0fefdbb
0
davidmerfield/Blot,davidmerfield/Blot,davidmerfield/Blot,davidmerfield/Blot
// Error Messages var BAD_CHARGE = 'We were unable to charge your card. Please fill out the form and try again, it should work.'; var NO_EMAIL = 'Please enter an email address'; var IN_USE = 'That email address is already used by another Blot account.'; var DECLINED = 'Your card was declined, please try again.'; var NO_CUSTOMER = 'No Customer'; var Express = require('express'); var config = require('config'); var stripe = require('stripe')(config.stripe.secret); var parse = require('body-parser').urlencoded({extended:false}); var User = require('user'); var signup = Express.Router(); var paymentForm = signup.route('/'); var passwordForm = signup.route('/create-account'); paymentForm.get(function(req, res){ if (req.session && req.session.email && req.session.subscription) return res.redirect(req.baseUrl + passwordForm.path); res.locals.title = 'Sign up for Blot and start your blog'; res.locals.error = req.query.error; res.locals.stripe_key = config.stripe.key; res.render('sign-up-payment'); }); paymentForm.post(parse, function(req, res, next){ // Card is a stripe token generated on the client var card = req.body && req.body.stripeToken; var email = req.body && req.body.email; if (!email) return next(new Error(NO_EMAIL)); if (!card) return next(new Error(BAD_CHARGE)); User.getByEmail(email, function(err, existingUser){ if (err) return next(err); if (existingUser) return next(new Error(IN_USE)); var info = { card: card, email: email, plan: 'yearly_20', description: 'Blot subscription' }; stripe.customers.create(info, function (err, customer) { if (err && err.type === 'StripeCardError') { return next(new Error(DECLINED)); } if (err) { return next(new Error(BAD_CHARGE)); } if (!customer) { return next(new Error(NO_CUSTOMER)); } // Store the user's email and charge ID // so that when the user returns from // Dropbox we know they have a blot account req.session.email = email; req.session.subscription = customer.subscription; console.log('Customer: ' + customer.subscription.customer + ' charged successfuly for ' + email); res.redirect(req.baseUrl + passwordForm.path); }); }); }); passwordForm.all(function(req, res, next) { if (!req.session || !req.session.email || !req.session.subscription) return res.redirect(req.baseUrl + paymentForm.path); next(); }); passwordForm.get(function(req, res){ res.locals.email = req.session.email; res.locals.subscription = !!req.session.subscription; res.locals.error = req.query.error; res.locals.change_email = req.query.change_email; res.render('sign-up-password'); }); passwordForm.post(parse, function(req, res, next){ var subscription = req.session.subscription; var email = req.body.email; var password = req.body.password; if (!email) return next(new Error('Please choose an email address')); if (!password) return next(new Error('Please choose a password')); User.hashPassword(password, function(err, passwordHash) { if (err) return next(err); User.create(email, passwordHash, subscription, function(err, user){ if (err) return next(err); delete req.session.email; delete req.session.subscription; req.session.uid = user.uid; res.redirect('/account/create-blog'); }); }); }); // This is error handling middleware // specific to the sign up page signup.use(function (err, req, res, next){ if (err && err.message) return res.redirect(req.baseUrl + req.path + '?error=' + encodeURIComponent(err.message)); next(); }); module.exports = signup;
app/site/routes/sign-up.js
module.exports = function(server){ var bodyParser = require('body-parser'); var Subscription = require('subscription'); var config = require('config'); var stripe = require('stripe')(config.stripe.secret); var parseBody = bodyParser.urlencoded({extended:false}); var excludeUser = require('middleware').excludeUser; // Stripe Errors var BAD_CHARGE = 'We were unable to charge your card. Please fill out the form and try again, it should work.'; var NO_EMAIL = 'Please enter an email address'; var DECLINED = 'Your card was declined, please try again.'; var DECLINED_CODE = 'StripeCardError'; var TITLE = 'Sign up for Blot and start your blog'; if (config.maintenance) { server.use('/sign-up', function(req, res, next){ res.redirect('/maintenance'); }); } server.route('/sign-up') // Authenticated users should not // see this page. It is served over SSL .all(excludeUser) .get(function(req, res){ res.render('sign-up', { title: TITLE, error: req.query.error, stripe_key: config.stripe.key }); }) // Take a stripe token generated // on the client and creates a charge .post(parseBody, function(request, response, next){ var stripeToken = request.body.stripeToken; var email = request.body.email; if (!stripeToken) return next(new Error(BAD_CHARGE)); if (!email) return next(new Error(NO_EMAIL)); var info = { card: stripeToken, email: email, plan: 'yearly_20', description: 'Blot subscription for $20 a year' }; stripe.customers.create(info, function (error, customer) { if (error && error.type === DECLINED_CODE) { return next(new Error(DECLINED)); } if (error) { return next(new Error(BAD_CHARGE)); } if (customer) { // Store the user's email and charge ID // so that when the user returns from // Dropbox we know they have a blot account request.session.email = email; request.session.subscription = customer.subscription; request.session.newUser = true; // Store the new customer's information Subscription.save(customer.subscription, function(error){ if (error) throw error; console.log('Customer: ' + customer.subscription.customer + ' charged successfuly for ' + email); response.redirect('/connect'); }); } }); }); // This is error handling middleware // specific to the sign up page server.use('/sign-up', function (error, req, res, next){ res.redirect('/sign-up?error=' + encodeURIComponent(error.message)); }) };
updated sign up route
app/site/routes/sign-up.js
updated sign up route
<ide><path>pp/site/routes/sign-up.js <del>module.exports = function(server){ <add>// Error Messages <add>var BAD_CHARGE = 'We were unable to charge your card. Please fill out the form and try again, it should work.'; <add>var NO_EMAIL = 'Please enter an email address'; <add>var IN_USE = 'That email address is already used by another Blot account.'; <add>var DECLINED = 'Your card was declined, please try again.'; <add>var NO_CUSTOMER = 'No Customer'; <ide> <del> var bodyParser = require('body-parser'); <del> var Subscription = require('subscription'); <del> var config = require('config'); <del> var stripe = require('stripe')(config.stripe.secret); <del> var parseBody = bodyParser.urlencoded({extended:false}); <del> var excludeUser = require('middleware').excludeUser; <add>var Express = require('express'); <add>var config = require('config'); <add>var stripe = require('stripe')(config.stripe.secret); <add>var parse = require('body-parser').urlencoded({extended:false}); <add>var User = require('user'); <ide> <del> // Stripe Errors <del> var BAD_CHARGE = 'We were unable to charge your card. Please fill out the form and try again, it should work.'; <del> var NO_EMAIL = 'Please enter an email address'; <del> var DECLINED = 'Your card was declined, please try again.'; <del> var DECLINED_CODE = 'StripeCardError'; <add>var signup = Express.Router(); <add>var paymentForm = signup.route('/'); <add>var passwordForm = signup.route('/create-account'); <ide> <del> var TITLE = 'Sign up for Blot and start your blog'; <add>paymentForm.get(function(req, res){ <ide> <del> if (config.maintenance) { <add> if (req.session && req.session.email && req.session.subscription) <add> return res.redirect(req.baseUrl + passwordForm.path); <ide> <del> server.use('/sign-up', function(req, res, next){ <add> res.locals.title = 'Sign up for Blot and start your blog'; <add> res.locals.error = req.query.error; <add> res.locals.stripe_key = config.stripe.key; <ide> <del> res.redirect('/maintenance'); <add> res.render('sign-up-payment'); <add>}); <add> <add>paymentForm.post(parse, function(req, res, next){ <add> <add> // Card is a stripe token generated on the client <add> var card = req.body && req.body.stripeToken; <add> var email = req.body && req.body.email; <add> <add> if (!email) <add> return next(new Error(NO_EMAIL)); <add> <add> if (!card) <add> return next(new Error(BAD_CHARGE)); <add> <add> User.getByEmail(email, function(err, existingUser){ <add> <add> if (err) return next(err); <add> <add> if (existingUser) return next(new Error(IN_USE)); <add> <add> var info = { <add> card: card, <add> email: email, <add> plan: 'yearly_20', <add> description: 'Blot subscription' <add> }; <add> <add> stripe.customers.create(info, function (err, customer) { <add> <add> if (err && err.type === 'StripeCardError') { <add> return next(new Error(DECLINED)); <add> } <add> <add> if (err) { <add> return next(new Error(BAD_CHARGE)); <add> } <add> <add> if (!customer) { <add> return next(new Error(NO_CUSTOMER)); <add> } <add> <add> // Store the user's email and charge ID <add> // so that when the user returns from <add> // Dropbox we know they have a blot account <add> req.session.email = email; <add> req.session.subscription = customer.subscription; <add> <add> console.log('Customer: ' + customer.subscription.customer + ' charged successfuly for ' + email); <add> res.redirect(req.baseUrl + passwordForm.path); <ide> }); <del> } <add> }); <add>}); <ide> <del> server.route('/sign-up') <add>passwordForm.all(function(req, res, next) { <ide> <del> // Authenticated users should not <del> // see this page. It is served over SSL <del> .all(excludeUser) <add> if (!req.session || !req.session.email || !req.session.subscription) <add> return res.redirect(req.baseUrl + paymentForm.path); <ide> <del> .get(function(req, res){ <add> next(); <add>}); <ide> <del> res.render('sign-up', { <del> title: TITLE, <del> error: req.query.error, <del> stripe_key: config.stripe.key <del> }); <del> }) <add>passwordForm.get(function(req, res){ <ide> <del> // Take a stripe token generated <del> // on the client and creates a charge <del> .post(parseBody, function(request, response, next){ <add> res.locals.email = req.session.email; <add> res.locals.subscription = !!req.session.subscription; <add> res.locals.error = req.query.error; <add> res.locals.change_email = req.query.change_email; <ide> <del> var stripeToken = request.body.stripeToken; <del> var email = request.body.email; <add> res.render('sign-up-password'); <add>}); <ide> <del> if (!stripeToken) <del> return next(new Error(BAD_CHARGE)); <add>passwordForm.post(parse, function(req, res, next){ <ide> <del> if (!email) <del> return next(new Error(NO_EMAIL)); <add> var subscription = req.session.subscription; <add> var email = req.body.email; <add> var password = req.body.password; <ide> <del> var info = { <del> card: stripeToken, <del> email: email, <del> plan: 'yearly_20', <del> description: 'Blot subscription for $20 a year' <del> }; <add> if (!email) return next(new Error('Please choose an email address')); <ide> <del> stripe.customers.create(info, function (error, customer) { <add> if (!password) return next(new Error('Please choose a password')); <ide> <del> if (error && error.type === DECLINED_CODE) { <del> return next(new Error(DECLINED)); <del> } <add> User.hashPassword(password, function(err, passwordHash) { <ide> <del> if (error) { <del> return next(new Error(BAD_CHARGE)); <del> } <add> if (err) return next(err); <ide> <del> if (customer) { <add> User.create(email, passwordHash, subscription, function(err, user){ <ide> <del> // Store the user's email and charge ID <del> // so that when the user returns from <del> // Dropbox we know they have a blot account <del> request.session.email = email; <del> request.session.subscription = customer.subscription; <del> request.session.newUser = true; <add> if (err) return next(err); <ide> <del> // Store the new customer's information <del> Subscription.save(customer.subscription, function(error){ <add> delete req.session.email; <add> delete req.session.subscription; <ide> <del> if (error) throw error; <add> req.session.uid = user.uid; <ide> <del> console.log('Customer: ' + customer.subscription.customer + ' charged successfuly for ' + email); <add> res.redirect('/account/create-blog'); <add> }); <add> }); <add>}); <ide> <del> response.redirect('/connect'); <del> }); <del> } <del> }); <del> }); <add>// This is error handling middleware <add>// specific to the sign up page <add>signup.use(function (err, req, res, next){ <ide> <del> // This is error handling middleware <del> // specific to the sign up page <del> server.use('/sign-up', function (error, req, res, next){ <del> res.redirect('/sign-up?error=' + encodeURIComponent(error.message)); <del> }) <del>}; <add> if (err && err.message) return res.redirect(req.baseUrl + req.path + '?error=' + encodeURIComponent(err.message)); <ide> <add> next(); <add>}); <add> <add>module.exports = signup;
Java
apache-2.0
a65807ffdc9fdf9d8dabb243809aae1c09dfa09e
0
OpenXIP/xip-host,OpenXIP/xip-host
/* * Copyright (c) 2012 Washington University in St. Louis. All Rights Reserved. */ package edu.wustl.xipHost.hostLogin; import javax.swing.*; import org.jdom.JDOMException; import edu.wustl.xipHost.application.Application; import edu.wustl.xipHost.application.ApplicationManager; import edu.wustl.xipHost.application.ApplicationManagerFactory; import edu.wustl.xipHost.hostControl.HostConfigurator; import java.awt.event.*; import java.awt.*; import java.io.File; import java.io.IOException; import java.util.List; public class SwitchUserDialog extends JDialog implements ActionListener { JLabel icon = new JLabel(); JLabel lblInfo = new JLabel("Running hosted applications:"); JLabel lblInfo_3 = new JLabel("Do you want to terminate the above applications and switch user?"); JPanel panelActiveApps; JPanel btnPanel = new JPanel(new GridLayout(1, 2)); JButton btnCancel = new JButton("Cancel"); Icon iconSwitchUser = new ImageIcon("./gif/Users.PNG"); JButton btnSwitch = new JButton("SwitchUser"); Color xipColor = new Color(51, 51, 102); public SwitchUserDialog(Frame owner, List<Application> activeApps){ super(owner, "Switch User", true); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); icon.setIcon(iconSwitchUser); //icon.setBorder(border1); Font font = new Font("SansSerif", 1, 14); Font font_1 = new Font("SansSerif", 1, 12); lblInfo.setFont(font); lblInfo.setForeground(Color.WHITE); panelActiveApps = new JPanel(new GridLayout(activeApps.size(), 1)); panelActiveApps.setBackground(xipColor); int i = 1; for(Application activeApp : activeApps){ JLabel lblActiveApp = new JLabel(i + ". " + activeApp.getName()); lblActiveApp.setFont(font_1); lblActiveApp.setForeground(Color.WHITE); panelActiveApps.add(lblActiveApp); i++; } lblInfo_3.setFont(font_1); lblInfo_3.setForeground(Color.WHITE); btnCancel.addActionListener(this); btnSwitch.addActionListener(this); btnCancel.setPreferredSize(new Dimension(80, 30)); btnSwitch.setPreferredSize(new Dimension(80, 30)); btnPanel.add(btnCancel); btnPanel.add(btnSwitch); btnPanel.setBackground(xipColor); add(icon); add(lblInfo); add(panelActiveApps); add(lblInfo_3); add(btnPanel); //versionDataPanel.setBackground(xipColor); //add(versionDataPanel); this.getContentPane().setBackground(xipColor); buildLayout(); //setSize(new Dimension(150, 25)); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension windowSize = this.getPreferredSize(); setBounds((screenSize.width - windowSize.width) / 2, (screenSize.height - windowSize.height) /4, windowSize.width, windowSize.height); setVisible(true); pack(); } public void buildLayout(){ GridBagLayout layout = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); setLayout(layout); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 0; constraints.gridy = 0; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.insets.top = 20; constraints.insets.left = 30; layout.setConstraints(icon, constraints); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 1; constraints.gridy = 0; constraints.gridwidth = 2; constraints.gridheight = 1; constraints.insets.top = 20; constraints.insets.right = 30; layout.setConstraints(lblInfo, constraints); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 1; constraints.gridy = 1; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.insets.top = 10; constraints.insets.left = 30; constraints.insets.bottom = 20; layout.setConstraints(panelActiveApps, constraints); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 1; constraints.gridy = 2; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.insets.top = 10; constraints.insets.right = 50; constraints.insets.bottom = 20; layout.setConstraints(lblInfo_3, constraints); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 1; constraints.gridy = 3; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.insets.top = 10; constraints.insets.right = 50; constraints.insets.bottom = 20; layout.setConstraints(btnPanel, constraints); } public static void main (String [] args) throws JDOMException, IOException{ ApplicationManager appMgr = ApplicationManagerFactory.getInstance(); File xipApplicationsConfig = new File("./config/applications.xml"); appMgr.loadApplications(xipApplicationsConfig); new SwitchUserDialog(new Frame(), appMgr.getApplications()); } public JButton getBtnSwitch(){ return btnSwitch; } @Override public void actionPerformed(ActionEvent event) { if(event.getSource() == btnCancel) { dispose(); } else if (event.getSource() == btnSwitch) { dispose(); HostConfigurator hostConfig = HostConfigurator.getHostConfigurator(); hostConfig.resetPanels(); hostConfig.terminateActiveApplications(hostConfig.getActiveApplications()); Login login = HostConfigurator.getLogin(); login.invalidateSecuredConnection(); HostConfigurator.getHostConfigurator().logNewUser(); } } }
src/edu/wustl/xipHost/hostLogin/SwitchUserDialog.java
/* * Copyright (c) 2012 Washington University in St. Louis. All Rights Reserved. */ package edu.wustl.xipHost.hostLogin; import javax.swing.*; import org.jdom.JDOMException; import edu.wustl.xipHost.application.Application; import edu.wustl.xipHost.application.ApplicationManager; import edu.wustl.xipHost.application.ApplicationManagerFactory; import edu.wustl.xipHost.hostControl.HostConfigurator; import java.awt.event.*; import java.awt.*; import java.io.File; import java.io.IOException; import java.util.List; public class SwitchUserDialog extends JDialog implements ActionListener { JLabel icon = new JLabel(); JLabel lblInfo = new JLabel("Running hosted applications:"); JLabel lblInfo_3 = new JLabel("Do you want to terminate the above applications and switch user?"); JPanel panelActiveApps; JPanel btnPanel = new JPanel(new GridLayout(1, 2)); JButton btnCancel = new JButton("Cancel"); Icon iconSwitchUser = new ImageIcon("./gif/Users.PNG"); JButton btnSwitch = new JButton("SwitchUser"); Color xipColor = new Color(51, 51, 102); public SwitchUserDialog(Frame owner, List<Application> activeApps){ super(owner, "Switch User", true); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); icon.setIcon(iconSwitchUser); //icon.setBorder(border1); Font font = new Font("SansSerif", 1, 14); Font font_1 = new Font("SansSerif", 1, 12); lblInfo.setFont(font); lblInfo.setForeground(Color.WHITE); panelActiveApps = new JPanel(new GridLayout(activeApps.size(), 1)); panelActiveApps.setBackground(xipColor); for(Application activeApp : activeApps){ JLabel lblActiveApp = new JLabel(activeApp.getName() + " ID: " + activeApp.getID().toString()); lblActiveApp.setFont(font_1); lblActiveApp.setForeground(Color.WHITE); panelActiveApps.add(lblActiveApp); } lblInfo_3.setFont(font_1); lblInfo_3.setForeground(Color.WHITE); btnCancel.addActionListener(this); btnSwitch.addActionListener(this); btnCancel.setPreferredSize(new Dimension(80, 30)); btnSwitch.setPreferredSize(new Dimension(80, 30)); btnPanel.add(btnCancel); btnPanel.add(btnSwitch); btnPanel.setBackground(xipColor); add(icon); add(lblInfo); add(panelActiveApps); add(lblInfo_3); add(btnPanel); //versionDataPanel.setBackground(xipColor); //add(versionDataPanel); this.getContentPane().setBackground(xipColor); buildLayout(); //setSize(new Dimension(150, 25)); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension windowSize = this.getPreferredSize(); setBounds((screenSize.width - windowSize.width) / 2, (screenSize.height - windowSize.height) /4, windowSize.width, windowSize.height); setVisible(true); pack(); } public void buildLayout(){ GridBagLayout layout = new GridBagLayout(); GridBagConstraints constraints = new GridBagConstraints(); setLayout(layout); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 0; constraints.gridy = 0; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.insets.top = 20; constraints.insets.left = 30; layout.setConstraints(icon, constraints); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 1; constraints.gridy = 0; constraints.gridwidth = 2; constraints.gridheight = 1; constraints.insets.top = 20; constraints.insets.right = 30; layout.setConstraints(lblInfo, constraints); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 1; constraints.gridy = 1; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.insets.top = 10; constraints.insets.left = 30; constraints.insets.bottom = 20; layout.setConstraints(panelActiveApps, constraints); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 1; constraints.gridy = 2; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.insets.top = 10; constraints.insets.right = 50; constraints.insets.bottom = 20; layout.setConstraints(lblInfo_3, constraints); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridx = 1; constraints.gridy = 3; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.insets.top = 10; constraints.insets.right = 50; constraints.insets.bottom = 20; layout.setConstraints(btnPanel, constraints); } public static void main (String [] args) throws JDOMException, IOException{ ApplicationManager appMgr = ApplicationManagerFactory.getInstance(); File xipApplicationsConfig = new File("./config/applications.xml"); appMgr.loadApplications(xipApplicationsConfig); new SwitchUserDialog(new Frame(), appMgr.getApplications()); } public JButton getBtnSwitch(){ return btnSwitch; } @Override public void actionPerformed(ActionEvent event) { if(event.getSource() == btnCancel) { dispose(); } else if (event.getSource() == btnSwitch) { dispose(); HostConfigurator hostConfig = HostConfigurator.getHostConfigurator(); hostConfig.resetPanels(); hostConfig.terminateActiveApplications(hostConfig.getActiveApplications()); Login login = HostConfigurator.getLogin(); login.invalidateSecuredConnection(); HostConfigurator.getHostConfigurator().logNewUser(); } } }
Replaced Applications ID displayed in SwitchUserDialog with numbers )e.g. 1, 2, .. etc) SVN-Revision: 1333
src/edu/wustl/xipHost/hostLogin/SwitchUserDialog.java
Replaced Applications ID displayed in SwitchUserDialog with numbers )e.g. 1, 2, .. etc)
<ide><path>rc/edu/wustl/xipHost/hostLogin/SwitchUserDialog.java <ide> <ide> panelActiveApps = new JPanel(new GridLayout(activeApps.size(), 1)); <ide> panelActiveApps.setBackground(xipColor); <add> int i = 1; <ide> for(Application activeApp : activeApps){ <del> JLabel lblActiveApp = new JLabel(activeApp.getName() + " ID: " + activeApp.getID().toString()); <add> JLabel lblActiveApp = new JLabel(i + ". " + activeApp.getName()); <ide> lblActiveApp.setFont(font_1); <ide> lblActiveApp.setForeground(Color.WHITE); <ide> panelActiveApps.add(lblActiveApp); <add> i++; <ide> } <ide> <ide>
Java
apache-2.0
8887ffd0155fd604a8c8ae43a0563e4a683b2784
0
BrunoEberhard/minimal-j,BrunoEberhard/minimal-j,BrunoEberhard/minimal-j
package org.minimalj.backend; import java.util.List; import java.util.Objects; import org.minimalj.application.Configuration; import org.minimalj.backend.repository.CountTransaction; import org.minimalj.backend.repository.DeleteEntityTransaction; import org.minimalj.backend.repository.InsertTransaction; import org.minimalj.backend.repository.ReadCriteriaTransaction; import org.minimalj.backend.repository.ReadEntityTransaction; import org.minimalj.backend.repository.SaveTransaction; import org.minimalj.backend.repository.UpdateTransaction; import org.minimalj.repository.Repository; import org.minimalj.repository.TransactionalRepository; import org.minimalj.repository.query.Query; import org.minimalj.security.Authentication; import org.minimalj.security.Authorization; import org.minimalj.transaction.Isolation; import org.minimalj.transaction.Transaction; import org.minimalj.transaction.TransactionAnnotations; /** * A Backend is responsible for executing the transactions. * It can do this by keeping a database (SqlRepository) or by * delegating everything to an other Backend (SocketBackend).<p> * * Every Frontend needs a Backend. But a Backend can serve more * than one Frontend.<p> * * The Backend configuration must be done with system properties. * These are handled in the initBackend method. The configuration * cannot be changed during the lifetime of an application VM.<p> * * The configuration properties: * <UL> * <LI><code>MjBackendAddress</code> and <code>MjBackendPort</code>: if * these two are set the transactions are delegated to a remote * SocketBackendServer.</LI> * <LI><code>MjBackend</code>: if this property is set it specifies * the classname of the Backend.</LI> * <LI>If the Backend should run in the same JVM as the Frontend you * don't need to set any property</LI> * </UL> */ public class Backend { private static Backend instance; public static Backend create() { String backendAddress = Configuration.get("MjBackendAddress"); String backendPort = Configuration.get("MjBackendPort", "8020"); if (backendAddress != null) { return new SocketBackend(backendAddress, Integer.valueOf(backendPort)); } if (Configuration.available("MjBackend")) { return Configuration.getClazz("MjBackend", Backend.class); } return new Backend(); }; private Repository repository = null; private Boolean authenticationActive = null; private Authentication authentication = null; private InheritableThreadLocal<Transaction<?>> currentTransaction = new InheritableThreadLocal<>(); public static void setInstance(Backend instance) { Objects.nonNull(instance); if (Backend.instance != null) { throw new IllegalStateException("Not allowed to change instance of " + Backend.class.getSimpleName()); } Backend.instance = instance; instance.init(); } public static Backend getInstance() { if (instance == null) { setInstance(create()); } return instance; } public void setRepository(Repository repository) { this.repository = repository; } public Repository getRepository() { if (!isInTransaction()) { throw new IllegalStateException("Repository may only be accessed from within a " + Transaction.class.getSimpleName()); } if (repository == null) { repository = Repository.create(); } return repository; } protected Authentication createAuthentication() { return Authentication.create(); } public final Authentication getAuthentication() { if (authentication == null) { if (authenticationActive == null) { authentication = createAuthentication(); authenticationActive = authentication != null; } } return authentication; } public boolean isAuthenticationActive() { return getAuthentication() != null; } public boolean isInTransaction() { return currentTransaction.get() != null; } // Could be moved in a class like "Do" but that would seem even more like magic // Backend.read or Backend.execute gives a hint that there is a separation between // the current stuff and the things done in the Transaction public static <T> T read(Class<T> clazz, Object id) { return execute(new ReadEntityTransaction<T>(clazz, id, null)); } public static <T> List<T> find(Class<T> clazz, Query query) { return execute(new ReadCriteriaTransaction<T>(clazz, query)); } public static <T> long count (Class<T> clazz, Query query) { return execute(new CountTransaction<T>(clazz, query)); } public static <T> Object insert(T object) { return execute(new InsertTransaction<T>(object)); } public static <T> void update(T object) { execute(new UpdateTransaction<T>(object)); } public static <T> T save(T object) { return execute(new SaveTransaction<T>(object)); } public static <T> void delete(Class<T> clazz, Object id) { execute(new DeleteEntityTransaction<T>(clazz, id)); } public static <T> T execute(Transaction<T> transaction) { return getInstance().doExecute(transaction); } public <T> T doExecute(Transaction<T> transaction) { if (isAuthenticationActive()) { Authorization.check(transaction); } try { currentTransaction.set(transaction); if (getRepository() instanceof TransactionalRepository) { TransactionalRepository transactionalRepository = (TransactionalRepository) getRepository(); return doExecute(transaction, transactionalRepository); } else { return transaction.execute(); } } finally { currentTransaction.set(null); } } private <T> T doExecute(Transaction<T> transaction, TransactionalRepository transactionalRepository) { Isolation.Level isolationLevel = TransactionAnnotations.getIsolation(transaction); T result; boolean commit = false; try { transactionalRepository.startTransaction(isolationLevel.getLevel()); result = transaction.execute(); commit = true; } finally { transactionalRepository.endTransaction(commit); } return result; } private void init() { if (Configuration.available("MjInit")) { Transaction<?> init = Configuration.getClazz("MjInit", Transaction.class); init.execute(); } } }
src/main/java/org/minimalj/backend/Backend.java
package org.minimalj.backend; import java.util.List; import java.util.Objects; import java.util.logging.Logger; import org.minimalj.application.Configuration; import org.minimalj.backend.repository.CountTransaction; import org.minimalj.backend.repository.DeleteEntityTransaction; import org.minimalj.backend.repository.InsertTransaction; import org.minimalj.backend.repository.ReadCriteriaTransaction; import org.minimalj.backend.repository.ReadEntityTransaction; import org.minimalj.backend.repository.SaveTransaction; import org.minimalj.backend.repository.UpdateTransaction; import org.minimalj.repository.Repository; import org.minimalj.repository.TransactionalRepository; import org.minimalj.repository.query.Query; import org.minimalj.repository.sql.SqlRepository; import org.minimalj.security.Authentication; import org.minimalj.security.Authorization; import org.minimalj.transaction.Isolation; import org.minimalj.transaction.Transaction; import org.minimalj.transaction.TransactionAnnotations; /** * A Backend is responsible for executing the transactions. * It can do this by keeping a database (SqlRepository) or by * delegating everything to an other Backend (SocketBackend).<p> * * Every Frontend needs a Backend. But a Backend can serve more * than one Frontend.<p> * * The Backend configuration must be done with system properties. * These are handled in the initBackend method. The configuration * cannot be changed during the lifetime of an application VM.<p> * * The configuration properties: * <UL> * <LI><code>MjBackendAddress</code> and <code>MjBackendPort</code>: if * these two are set the transactions are delegated to a remote * SocketBackendServer.</LI> * <LI><code>MjBackend</code>: if this property is set it specifies * the classname of the Backend.</LI> * <LI>If the Backend should run in the same JVM as the Frontend you * don't need to set any property</LI> * </UL> */ public class Backend { private static final Logger logger = Logger.getLogger(SqlRepository.class.getName()); private static Backend instance; public static Backend create() { String backendAddress = Configuration.get("MjBackendAddress"); String backendPort = Configuration.get("MjBackendPort", "8020"); if (backendAddress != null) { return new SocketBackend(backendAddress, Integer.valueOf(backendPort)); } if (Configuration.available("MjBackend")) { return Configuration.getClazz("MjBackend", Backend.class); } return new Backend(); }; private Repository repository = null; private Boolean authenticationActive = null; private Authentication authentication = null; private InheritableThreadLocal<Transaction<?>> currentTransaction = new InheritableThreadLocal<>(); public static void setInstance(Backend instance) { Objects.nonNull(instance); if (Backend.instance != null) { throw new IllegalStateException("Not allowed to change instance of " + Backend.class.getSimpleName()); } Backend.instance = instance; instance.init(); } public static Backend getInstance() { if (instance == null) { setInstance(create()); } return instance; } public void setRepository(Repository repository) { this.repository = repository; } public Repository getRepository() { if (!isInTransaction()) { throw new IllegalStateException("Repository may only be accessed from within a " + Transaction.class.getSimpleName()); } if (repository == null) { repository = Repository.create(); } return repository; } protected Authentication createAuthentication() { return Authentication.create(); } public final Authentication getAuthentication() { if (authentication == null) { if (authenticationActive == null) { authentication = createAuthentication(); authenticationActive = authentication != null; } } return authentication; } public boolean isAuthenticationActive() { return getAuthentication() != null; } public boolean isInTransaction() { return currentTransaction.get() != null; } // Could be moved in a class like "Do" but that would seem even more like magic // Backend.read or Backend.execute gives a hint that there is a separation between // the current stuff and the things done in the Transaction public static <T> T read(Class<T> clazz, Object id) { return execute(new ReadEntityTransaction<T>(clazz, id, null)); } public static <T> List<T> find(Class<T> clazz, Query query) { return execute(new ReadCriteriaTransaction<T>(clazz, query)); } public static <T> long count (Class<T> clazz, Query query) { return execute(new CountTransaction<T>(clazz, query)); } public static <T> Object insert(T object) { return execute(new InsertTransaction<T>(object)); } public static <T> void update(T object) { execute(new UpdateTransaction<T>(object)); } public static <T> T save(T object) { return execute(new SaveTransaction<T>(object)); } public static <T> void delete(Class<T> clazz, Object id) { execute(new DeleteEntityTransaction<T>(clazz, id)); } public static <T> T execute(Transaction<T> transaction) { return getInstance().doExecute(transaction); } public <T> T doExecute(Transaction<T> transaction) { if (isAuthenticationActive()) { Authorization.check(transaction); } try { currentTransaction.set(transaction); if (getRepository() instanceof TransactionalRepository) { TransactionalRepository transactionalRepository = (TransactionalRepository) getRepository(); return doExecute(transaction, transactionalRepository); } else { return transaction.execute(); } } finally { currentTransaction.set(null); } } private <T> T doExecute(Transaction<T> transaction, TransactionalRepository transactionalRepository) { Isolation.Level isolationLevel = TransactionAnnotations.getIsolation(transaction); if (isolationLevel != null) { return doExecute(transaction, transactionalRepository, isolationLevel); } else { return transaction.execute(); } } private <T> T doExecute(Transaction<T> transaction, TransactionalRepository transactionalRepository, Isolation.Level isolationLevel) { T result; boolean commit = false; try { transactionalRepository.startTransaction(isolationLevel.getLevel()); result = transaction.execute(); commit = true; } finally { transactionalRepository.endTransaction(commit); } return result; } private void init() { if (Configuration.available("MjInit")) { Transaction<?> init = Configuration.getClazz("MjInit", Transaction.class); init.execute(); } } }
Backend: refactoring
src/main/java/org/minimalj/backend/Backend.java
Backend: refactoring
<ide><path>rc/main/java/org/minimalj/backend/Backend.java <ide> <ide> import java.util.List; <ide> import java.util.Objects; <del>import java.util.logging.Logger; <ide> <ide> import org.minimalj.application.Configuration; <ide> import org.minimalj.backend.repository.CountTransaction; <ide> import org.minimalj.repository.Repository; <ide> import org.minimalj.repository.TransactionalRepository; <ide> import org.minimalj.repository.query.Query; <del>import org.minimalj.repository.sql.SqlRepository; <ide> import org.minimalj.security.Authentication; <ide> import org.minimalj.security.Authorization; <ide> import org.minimalj.transaction.Isolation; <ide> * </UL> <ide> */ <ide> public class Backend { <del> private static final Logger logger = Logger.getLogger(SqlRepository.class.getName()); <del> <ide> private static Backend instance; <ide> <ide> public static Backend create() { <ide> <ide> private <T> T doExecute(Transaction<T> transaction, TransactionalRepository transactionalRepository) { <ide> Isolation.Level isolationLevel = TransactionAnnotations.getIsolation(transaction); <del> if (isolationLevel != null) { <del> return doExecute(transaction, transactionalRepository, isolationLevel); <del> } else { <del> return transaction.execute(); <del> } <del> } <del> <del> private <T> T doExecute(Transaction<T> transaction, TransactionalRepository transactionalRepository, <del> Isolation.Level isolationLevel) { <ide> T result; <ide> boolean commit = false; <ide> try {
JavaScript
apache-2.0
b55642274b37704769bed712f00b1d21d32ad3e5
0
googleinterns/step98-2020,googleinterns/step98-2020
import React, { createRef } from 'react' import { sortTravelObjectsByDate, sameTravelObjectList } from "../../scripts/HelperFunctions" import ZoomInIcon from '@material-ui/icons/ZoomIn'; import ZoomOutIcon from '@material-ui/icons/ZoomOut'; import { Box, Fab } from "@material-ui/core" const MARKER_ZOOM = 15; const CENTER_ZOOM = 12; class MapComponent extends React.Component { constructor(props) { super(props); this.state = { finalizedMarkers: new Map(), unfinalizedMarkers: new Map(), geoPaths: [] } this.googleMapRef = createRef(); this.googleMap = undefined } componentDidMount() { this.googleMap = this.createMap(); if (this.props.finalized.length > 0 || this.props.unfinalized > 0) { let bounds = this.drawMap(); this.googleMap.fitBounds(bounds); } this.props.setMap(this.googleMap); } /* * Updates state with any changes in props */ componentDidUpdate(prevProps) { if (this.props.selected !== null && this.props.selected !== prevProps.selected) { let selectedObject = this.state.finalizedMarkers.has(this.props.selected) ? this.state.finalizedMarkers.get(this.props.selected) : this.state.unfinalizedMarkers.get(this.props.selected); let marker = selectedObject.type === "flight" ? selectedObject.marker.arrival : selectedObject.marker; this.zoomToMarker(marker); } else if (!sameTravelObjectList(prevProps.displayDate.events, this.props.displayDate.events) && this.props.displayDate.events.length !== 0) { // if changes to current day's events and isn't empty, zoom to todays events this.clearMap() this.drawMap(); this.googleMap.fitBounds(this.getTodaysBounds()); } else if (!sameTravelObjectList(prevProps.finalized, this.props.finalized) || !sameTravelObjectList(prevProps.unfinalized, this.props.unfinalized)) { // any other changes to finalized or unfinalized zoom out to encompass all markers. this.clearMap(); let bounds = this.drawMap(); // if there are no travel objects, set map to default trip location if (this.props.finalized.length == 0 && this.props.unfinalized.length == 0) { this.zoomToDefaultCoordinates(); } else { // no finalized events for current display date, set bounds to encompass all markers this.googleMap.fitBounds(bounds); } } } zoomToDefaultCoordinates() { this.googleMap.setZoom(CENTER_ZOOM); this.googleMap.setCenter(this.props.defaultCenter); } zoomToMarker(marker) { this.googleMap.setZoom(MARKER_ZOOM); this.googleMap.setCenter(marker.getPosition()); } getTodaysBounds() { var bounds = new window.google.maps.LatLngBounds(); this.props.displayDate.events.map((event) => { if (event.type === "flight") { bounds.extend(event.arrivalCoordinates); } else { bounds.extend(event.coordinates); } }) return bounds; } createMap() { return new window.google.maps.Map(this.googleMapRef.current, { zoom: CENTER_ZOOM, center: this.props.defaultCenter }) } drawMap() { var bounds = new window.google.maps.LatLngBounds(); let unfinalizedMarkers = this.drawMarkers(this.props.unfinalized, bounds); let finalizedMarkers = this.drawMarkers(sortTravelObjectsByDate(this.props.finalized), bounds); let pathArr = this.drawPaths(); this.setState({ unfinalizedMarkers: unfinalizedMarkers, finalizedMarkers: finalizedMarkers, geoPaths: pathArr }); return bounds; } /* * Given a list of travel object data, draws corresponding markers on map and * returns hash map containing marker objects */ drawMarkers(list, bounds) { // construct hashmap with key: travelObject id, value: marker object return list.reduce((objectIDToMarker, item) => { if (item.type !== "flight") { objectIDToMarker.set(item.id, { marker: this.addMarker(item.coordinates, item.type, item.title), type: item.type }); bounds.extend(item.coordinates); } else { objectIDToMarker.set(item.id, { marker: { departure: this.addMarker(item.departureCoordinates, item.type, item.departureAirport), arrival: this.addMarker(item.arrivalCoordinates, item.type, item.arrivalAirport) }, type: item.type }); bounds.extend(item.arrivalCoordinates); } return objectIDToMarker; }, new Map()) } addMarker(coordinates, type, content) { var iconUrl; if (type === "flight") { iconUrl = "http://maps.google.com/mapfiles/ms/icons/blue-dot.png" } else if (type === "event") { iconUrl = "http://maps.google.com/mapfiles/ms/icons/green-dot.png" } else { iconUrl = "http://maps.google.com/mapfiles/ms/icons/red-dot.png" } var newMarker = new window.google.maps.Marker({ position: coordinates, map: this.googleMap, animation: window.google.maps.Animation.DROP, icon: { url: iconUrl } }) const infowindow = new window.google.maps.InfoWindow({ content: content }) // zoom to marker when clicked newMarker.addListener('click', () => { this.googleMap.setZoom(MARKER_ZOOM); this.googleMap.setCenter(newMarker.getPosition()); infowindow.open(this.googleMap, newMarker) }); return newMarker; } /* * Draws path between all finalized travel objects, returns list of path objects */ drawPaths() { let paths = this.getPathSegments(); // add each path to the map and return array of path objects var red = 60; let change = paths.length === 0 ? 0 : red / (paths.length - 1); return paths.map((path) => { let color = "hsl(0, 100%, " + red + "%)"; red -= change; return this.addPath(this.googleMap, path, color); }) } // splits finalized trips into segments of coordinate pairs getPathSegments() { var paths = []; var curPath = []; for (let i = 0; i < this.props.displayDate.events.length; i++) { let item = this.props.displayDate.events[i]; // found flight -> create new path segment if (item.type === "flight") { if (paths.length !== 0) { curPath.push(item.departureCoordinates) paths.push(curPath); } curPath = [item.arrivalCoordinates]; } else { curPath.push(item.coordinates); paths.push(curPath); curPath = [item.coordinates]; } } // add remaining path, if any, to paths if (curPath.length > 1) { paths.push(curPath); } return paths; } // constructs path object and places on map. Returns path object. addPath(map, path, color) { // TODO : change to show directions between paths // dotted line var lineSymbol = { path: 'M 0,-1 0,1', strokeOpacity: 1, scale: 4 }; let geoPath = new window.google.maps.Polyline({ path: path, strokeColor: color, strokeOpacity: 0, strokeWeight: 5, icons: [{ icon: lineSymbol, offset: '0', repeat: '20px' }] }); geoPath.setMap(map); return geoPath; } clearMap() { this.removeAllMarkers(this.state.unfinalizedMarkers); this.removeAllMarkers(this.state.finalizedMarkers); // remove all paths this.state.geoPaths.map((path) => path.setMap(null)); } removeAllMarkers(hashMap) { for (const [key, value] of hashMap) { if (value.type !== "flight") { value.marker.setMap(null); } else { value.marker.departure.setMap(null); value.marker.arrival.setMap(null); } } } render() { return ( <div id='map' ref={this.googleMapRef} /> ) } } export default MapComponent;
step-capstone/src/components/Utilities/Map.js
import React, { createRef } from 'react' import { sortTravelObjectsByDate, sameTravelObjectList } from "../../scripts/HelperFunctions" import ZoomOutMapIcon from '@material-ui/icons/ZoomOutMap'; import MapIcon from '@material-ui/icons/Map'; import TodayIcon from '@material-ui/icons/Today'; import { Typography } from '@material-ui/core'; const MARKER_ZOOM = 15; const CENTER_ZOOM = 12; class MapComponent extends React.Component { constructor(props) { super(props); this.state = { finalizedMarkers: new Map(), unfinalizedMarkers: new Map(), geoPaths: [] } this.googleMapRef = createRef(); this.googleMap = undefined } componentDidMount() { this.googleMap = this.createMap(); if (this.props.finalized.length > 0 || this.props.unfinalized > 0) { let bounds = this.drawMap(); this.googleMap.fitBounds(bounds); } this.props.setMap(this.googleMap); } /* * Updates state with any changes in props */ componentDidUpdate(prevProps) { if (this.props.selected !== null && this.props.selected !== prevProps.selected) { let selectedObject = this.state.finalizedMarkers.has(this.props.selected) ? this.state.finalizedMarkers.get(this.props.selected) : this.state.unfinalizedMarkers.get(this.props.selected); let marker = selectedObject.type === "flight" ? selectedObject.marker.arrival : selectedObject.marker; this.zoomToMarker(marker); } else if (!sameTravelObjectList(prevProps.displayDate.events, this.props.displayDate.events) && this.props.displayDate.events.length !== 0) { // if changes to current day's events and isn't empty, zoom to todays events this.clearMap() this.drawMap(); this.googleMap.fitBounds(this.getTodaysBounds()); } else if (!sameTravelObjectList(prevProps.finalized, this.props.finalized) || !sameTravelObjectList(prevProps.unfinalized, this.props.unfinalized)) { // any other changes to finalized or unfinalized zoom out to encompass all markers. this.clearMap(); let bounds = this.drawMap(); // if there are no travel objects, set map to default trip location if (this.props.finalized.length == 0 && this.props.unfinalized.length == 0) { this.zoomToDefaultCoordinates(); } else { // no finalized events for current display date, set bounds to encompass all markers this.googleMap.fitBounds(bounds); } } } zoomToDefaultCoordinates() { this.googleMap.setZoom(CENTER_ZOOM); this.googleMap.setCenter(this.props.defaultCenter); } zoomToMarker(marker) { this.googleMap.setZoom(MARKER_ZOOM); this.googleMap.setCenter(marker.getPosition()); } getTodaysBounds() { var bounds = new window.google.maps.LatLngBounds(); this.props.displayDate.events.map((event) => { if (event.type === "flight") { bounds.extend(event.arrivalCoordinates); } else { bounds.extend(event.coordinates); } }) return bounds; } createMap() { return new window.google.maps.Map(this.googleMapRef.current, { zoom: CENTER_ZOOM, center: this.props.defaultCenter }) } drawMap() { var bounds = new window.google.maps.LatLngBounds(); let unfinalizedMarkers = this.drawMarkers(this.props.unfinalized, bounds); let finalizedMarkers = this.drawMarkers(sortTravelObjectsByDate(this.props.finalized), bounds); let pathArr = this.drawPaths(); this.setState({ unfinalizedMarkers: unfinalizedMarkers, finalizedMarkers: finalizedMarkers, geoPaths: pathArr }); return bounds; } /* * Given a list of travel object data, draws corresponding markers on map and * returns hash map containing marker objects */ drawMarkers(list, bounds) { // construct hashmap with key: travelObject id, value: marker object return list.reduce((objectIDToMarker, item) => { if (item.type !== "flight") { objectIDToMarker.set(item.id, { marker: this.addMarker(item.coordinates, item.type, item.title), type: item.type }); bounds.extend(item.coordinates); } else { objectIDToMarker.set(item.id, { marker: { departure: this.addMarker(item.departureCoordinates, item.type, item.departureAirport), arrival: this.addMarker(item.arrivalCoordinates, item.type, item.arrivalAirport) }, type: item.type }); bounds.extend(item.arrivalCoordinates); } return objectIDToMarker; }, new Map()) } addMarker(coordinates, type, content) { var iconUrl; if (type === "flight") { iconUrl = "http://maps.google.com/mapfiles/ms/icons/blue-dot.png" } else if (type === "event") { iconUrl = "http://maps.google.com/mapfiles/ms/icons/green-dot.png" } else { iconUrl = "http://maps.google.com/mapfiles/ms/icons/red-dot.png" } var newMarker = new window.google.maps.Marker({ position: coordinates, map: this.googleMap, animation: window.google.maps.Animation.DROP, icon: { url: iconUrl } }) const infowindow = new window.google.maps.InfoWindow({content: content}) // zoom to marker when clicked newMarker.addListener('click', () => { this.googleMap.setZoom(MARKER_ZOOM); this.googleMap.setCenter(newMarker.getPosition()); infowindow.open(this.googleMap, newMarker) }); return newMarker; } /* * Draws path between all finalized travel objects, returns list of path objects */ drawPaths() { let paths = this.getPathSegments(); // add each path to the map and return array of path objects var red = 60; let change = paths.length === 0 ? 0 : red / (paths.length - 1); return paths.map((path) => { let color = "hsl(0, 100%, " + red + "%)"; red -= change; return this.addPath(this.googleMap, path, color); }) } // splits finalized trips into segments of coordinate pairs getPathSegments() { var paths = []; var curPath = []; for (let i = 0; i < this.props.displayDate.events.length; i++) { let item = this.props.displayDate.events[i]; // found flight -> create new path segment if (item.type === "flight") { if (paths.length !== 0) { curPath.push(item.departureCoordinates) paths.push(curPath); } curPath = [item.arrivalCoordinates]; } else { curPath.push(item.coordinates); paths.push(curPath); curPath = [item.coordinates]; } } // add remaining path, if any, to paths if (curPath.length > 1) { paths.push(curPath); } return paths; } // constructs path object and places on map. Returns path object. addPath(map, path, color) { // TODO : change to show directions between paths // dotted line var lineSymbol = { path: 'M 0,-1 0,1', strokeOpacity: 1, scale: 4 }; let geoPath = new window.google.maps.Polyline({ path: path, strokeColor: color, strokeOpacity: 0, strokeWeight: 5, icons: [{ icon: lineSymbol, offset: '0', repeat: '20px' }] }); geoPath.setMap(map); return geoPath; } clearMap() { this.removeAllMarkers(this.state.unfinalizedMarkers); this.removeAllMarkers(this.state.finalizedMarkers); // remove all paths this.state.geoPaths.map((path) => path.setMap(null)); } removeAllMarkers(hashMap) { for (const [key, value] of hashMap) { if (value.type !== "flight") { value.marker.setMap(null); } else { value.marker.departure.setMap(null); value.marker.arrival.setMap(null); } } } render() { return ( <div id='map' ref={this.googleMapRef} /> ) } } export default MapComponent;
Final fixes
step-capstone/src/components/Utilities/Map.js
Final fixes
<ide><path>tep-capstone/src/components/Utilities/Map.js <ide> import React, { createRef } from 'react' <ide> import { sortTravelObjectsByDate, sameTravelObjectList } from "../../scripts/HelperFunctions" <del>import ZoomOutMapIcon from '@material-ui/icons/ZoomOutMap'; <del>import MapIcon from '@material-ui/icons/Map'; <del>import TodayIcon from '@material-ui/icons/Today'; <del>import { Typography } from '@material-ui/core'; <add>import ZoomInIcon from '@material-ui/icons/ZoomIn'; <add>import ZoomOutIcon from '@material-ui/icons/ZoomOut'; <add>import { Box, Fab } from "@material-ui/core" <ide> <ide> const MARKER_ZOOM = 15; <ide> const CENTER_ZOOM = 12; <ide> icon: { url: iconUrl } <ide> }) <ide> <del> const infowindow = new window.google.maps.InfoWindow({content: content}) <add> const infowindow = new window.google.maps.InfoWindow({ content: content }) <ide> <ide> // zoom to marker when clicked <ide> newMarker.addListener('click', () => {
JavaScript
mit
cf8fb42161611a8be347dfa845304805d4a40b02
0
CodeWall-EStudio/XZone,CodeWall-EStudio/XZone,CodeWall-EStudio/XZone
/** * mOxie - multi-runtime File API & XMLHttpRequest L2 Polyfill * v1.0.0 * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing * * Date: 2013-09-23 */ /** * Compiled inline version. (Library mode) */ /*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */ /*globals $code */ (function(exports, undefined) { "use strict"; var modules = {}; function require(ids, callback) { var module, defs = []; for (var i = 0; i < ids.length; ++i) { module = modules[ids[i]] || resolve(ids[i]); if (!module) { throw 'module definition dependecy not found: ' + ids[i]; } defs.push(module); } callback.apply(null, defs); } function define(id, dependencies, definition) { if (typeof id !== 'string') { throw 'invalid module definition, module id must be defined and be a string'; } if (dependencies === undefined) { throw 'invalid module definition, dependencies must be specified'; } if (definition === undefined) { throw 'invalid module definition, definition function must be specified'; } require(dependencies, function() { modules[id] = definition.apply(null, arguments); }); } function defined(id) { return !!modules[id]; } function resolve(id) { var target = exports; var fragments = id.split(/[.\/]/); for (var fi = 0; fi < fragments.length; ++fi) { if (!target[fragments[fi]]) { return; } target = target[fragments[fi]]; } return target; } function expose(ids) { for (var i = 0; i < ids.length; i++) { var target = exports; var id = ids[i]; var fragments = id.split(/[.\/]/); for (var fi = 0; fi < fragments.length - 1; ++fi) { if (target[fragments[fi]] === undefined) { target[fragments[fi]] = {}; } target = target[fragments[fi]]; } target[fragments[fragments.length - 1]] = modules[id]; } } // Included from: src/javascript/core/utils/Basic.js /** * Basic.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Basic', [], function() { /** Gets the true type of the built-in object (better version of typeof). @author Angus Croll (http://javascriptweblog.wordpress.com/) @method typeOf @for Utils @static @param {Object} o Object to check. @return {String} Object [[Class]] */ var typeOf = function(o) { var undef; if (o === undef) { return 'undefined'; } else if (o === null) { return 'null'; } else if (o.nodeType) { return 'node'; } // the snippet below is awesome, however it fails to detect null, undefined and arguments types in IE lte 8 return ({}).toString.call(o).match(/\s([a-z|A-Z]+)/)[1].toLowerCase(); }; /** Extends the specified object with another object. @method extend @static @param {Object} target Object to extend. @param {Object} [obj]* Multiple objects to extend with. @return {Object} Same as target, the extended object. */ var extend = function(target) { var undef; each(arguments, function(arg, i) { if (i > 0) { each(arg, function(value, key) { if (value !== undef) { if (typeOf(target[key]) === typeOf(value) && !!~inArray(typeOf(value), ['array', 'object'])) { extend(target[key], value); } else { target[key] = value; } } }); } }); return target; }; /** Executes the callback function for each item in array/object. If you return false in the callback it will break the loop. @method each @static @param {Object} obj Object to iterate. @param {function} callback Callback function to execute for each item. */ var each = function(obj, callback) { var length, key, i, undef; if (obj) { try { length = obj.length; } catch(ex) { length = undef; } if (length === undef) { // Loop object items for (key in obj) { if (obj.hasOwnProperty(key)) { if (callback(obj[key], key) === false) { return; } } } } else { // Loop array items for (i = 0; i < length; i++) { if (callback(obj[i], i) === false) { return; } } } } }; /** Checks if object is empty. @method isEmptyObj @static @param {Object} o Object to check. @return {Boolean} */ var isEmptyObj = function(obj) { var prop; if (!obj || typeOf(obj) !== 'object') { return true; } for (prop in obj) { return false; } return true; }; /** Recieve an array of functions (usually async) to call in sequence, each function receives a callback as first argument that it should call, when it completes. Finally, after everything is complete, main callback is called. Passing truthy value to the callback as a first argument will interrupt the sequence and invoke main callback immediately. @method inSeries @static @param {Array} queue Array of functions to call in sequence @param {Function} cb Main callback that is called in the end, or in case of erro */ var inSeries = function(queue, cb) { var i = 0, length = queue.length; if (typeOf(cb) !== 'function') { cb = function() {}; } if (!queue || !queue.length) { cb(); } function callNext(i) { if (typeOf(queue[i]) === 'function') { queue[i](function(error) { /*jshint expr:true */ ++i < length && !error ? callNext(i) : cb(error); }); } } callNext(i); }; /** Find an element in array and return it's index if present, otherwise return -1. @method inArray @static @param {Mixed} needle Element to find @param {Array} array @return {Int} Index of the element, or -1 if not found */ var inArray = function(needle, array) { if (array) { if (Array.prototype.indexOf) { return Array.prototype.indexOf.call(array, needle); } for (var i = 0, length = array.length; i < length; i++) { if (array[i] === needle) { return i; } } } return -1; }; /** Returns elements of first array if they are not present in second. And false - otherwise. @private @method arrayDiff @param {Array} needles @param {Array} array @return {Array|Boolean} */ var arrayDiff = function(needles, array) { var diff = []; if (typeOf(needles) !== 'array') { needles = [needles]; } if (typeOf(array) !== 'array') { array = [array]; } for (var i in needles) { if (inArray(needles[i], array) === -1) { diff.push(needles[i]); } } return diff.length ? diff : false; }; /** Find intersection of two arrays. @private @method arrayIntersect @param {Array} array1 @param {Array} array2 @return {Array} Intersection of two arrays or null if there is none */ var arrayIntersect = function(array1, array2) { var result = []; each(array1, function(item) { if (inArray(item, array2) !== -1) { result.push(item); } }); return result.length ? result : null; }; /** Forces anything into an array. @method toArray @static @param {Object} obj Object with length field. @return {Array} Array object containing all items. */ var toArray = function(obj) { var i, arr = []; for (i = 0; i < obj.length; i++) { arr[i] = obj[i]; } return arr; }; /** Generates an unique ID. This is 99.99% unique since it takes the current time and 5 random numbers. The only way a user would be able to get the same ID is if the two persons at the same exact milisecond manages to get 5 the same random numbers between 0-65535 it also uses a counter so each call will be guaranteed to be page unique. It's more probable for the earth to be hit with an ansteriod. Y @method guid @static @param {String} prefix to prepend (by default 'o' will be prepended). @method guid @return {String} Virtually unique id. */ var guid = (function() { var counter = 0; return function(prefix) { var guid = new Date().getTime().toString(32), i; for (i = 0; i < 5; i++) { guid += Math.floor(Math.random() * 65535).toString(32); } return (prefix || 'o_') + guid + (counter++).toString(32); }; }()); /** Trims white spaces around the string @method trim @static @param {String} str @return {String} */ var trim = function(str) { if (!str) { return str; } return String.prototype.trim ? String.prototype.trim.call(str) : str.toString().replace(/^\s*/, '').replace(/\s*$/, ''); }; /** Parses the specified size string into a byte value. For example 10kb becomes 10240. @method parseSizeStr @static @param {String/Number} size String to parse or number to just pass through. @return {Number} Size in bytes. */ var parseSizeStr = function(size) { if (typeof(size) !== 'string') { return size; } var muls = { t: 1099511627776, g: 1073741824, m: 1048576, k: 1024 }, mul; size = /^([0-9]+)([mgk]?)$/.exec(size.toLowerCase().replace(/[^0-9mkg]/g, '')); mul = size[2]; size = +size[1]; if (muls.hasOwnProperty(mul)) { size *= muls[mul]; } return size; }; return { guid: guid, typeOf: typeOf, extend: extend, each: each, isEmptyObj: isEmptyObj, inSeries: inSeries, inArray: inArray, arrayDiff: arrayDiff, arrayIntersect: arrayIntersect, toArray: toArray, trim: trim, parseSizeStr: parseSizeStr }; }); // Included from: src/javascript/core/I18n.js /** * I18n.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/core/I18n", [ "moxie/core/utils/Basic" ], function(Basic) { var i18n = {}; return { /** * Extends the language pack object with new items. * * @param {Object} pack Language pack items to add. * @return {Object} Extended language pack object. */ addI18n: function(pack) { return Basic.extend(i18n, pack); }, /** * Translates the specified string by checking for the english string in the language pack lookup. * * @param {String} str String to look for. * @return {String} Translated string or the input string if it wasn't found. */ translate: function(str) { return i18n[str] || str; }, /** * Shortcut for translate function * * @param {String} str String to look for. * @return {String} Translated string or the input string if it wasn't found. */ _: function(str) { return this.translate(str); }, /** * Pseudo sprintf implementation - simple way to replace tokens with specified values. * * @param {String} str String with tokens * @return {String} String with replaced tokens */ sprintf: function(str) { var args = [].slice.call(arguments, 1), reStr = ''; Basic.each(str.split(/%[a-z]/), function(part) { reStr += part; if (args.length) { reStr += args.shift(); } }); return reStr; } }; }); // Included from: src/javascript/core/utils/Mime.js /** * Mime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/core/utils/Mime", [ "moxie/core/utils/Basic", "moxie/core/I18n" ], function(Basic, I18n) { var mimeData = "" + "application/msword,doc dot," + "application/pdf,pdf," + "application/pgp-signature,pgp," + "application/postscript,ps ai eps," + "application/rtf,rtf," + "application/vnd.ms-excel,xls xlb," + "application/vnd.ms-powerpoint,ppt pps pot," + "application/zip,zip," + "application/x-shockwave-flash,swf swfl," + "application/vnd.openxmlformats-officedocument.wordprocessingml.document,docx," + "application/vnd.openxmlformats-officedocument.wordprocessingml.template,dotx," + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,xlsx," + "application/vnd.openxmlformats-officedocument.presentationml.presentation,pptx," + "application/vnd.openxmlformats-officedocument.presentationml.template,potx," + "application/vnd.openxmlformats-officedocument.presentationml.slideshow,ppsx," + "application/x-javascript,js," + "application/json,json," + "audio/mpeg,mp3 mpga mpega mp2," + "audio/x-wav,wav," + "audio/mp4,m4a," + "audio/ogg,oga ogg," + "audio/aiff,aiff aif," + "audio/flac,flac," + "audio/aac,aac," + "audio/ac3,ac3," + "audio/x-ms-wma,wma," + "image/bmp,bmp," + "image/gif,gif," + "image/jpeg,jpg jpeg jpe," + "image/photoshop,psd," + "image/png,png," + "image/svg+xml,svg svgz," + "image/tiff,tiff tif," + "text/plain,asc txt text diff log," + "text/html,htm html xhtml," + "text/css,css," + "text/csv,csv," + "text/rtf,rtf," + "video/mpeg,mpeg mpg mpe m2v," + "video/quicktime,qt mov," + "video/mp4,mp4," + "video/x-m4v,m4v," + "video/x-flv,flv," + "video/x-ms-wmv,wmv," + "video/avi,avi," + "video/webm,webm," + "video/3gpp,3gpp 3gp," + "video/3gpp2,3g2," + "video/vnd.rn-realvideo,rv," + "video/ogg,ogv," + "video/x-matroska,mkv," + "application/vnd.oasis.opendocument.formula-template,otf," + "application/octet-stream,exe"; var Mime = { mimes: {}, extensions: {}, // Parses the default mime types string into a mimes and extensions lookup maps addMimeType: function (mimeData) { var items = mimeData.split(/,/), i, ii, ext; for (i = 0; i < items.length; i += 2) { ext = items[i + 1].split(/ /); // extension to mime lookup for (ii = 0; ii < ext.length; ii++) { this.mimes[ext[ii]] = items[i]; } // mime to extension lookup this.extensions[items[i]] = ext; } }, extList2mimes: function (filters, addMissingExtensions) { var self = this, ext, i, ii, type, mimes = []; // convert extensions to mime types list for (i = 0; i < filters.length; i++) { ext = filters[i].extensions.split(/\s*,\s*/); for (ii = 0; ii < ext.length; ii++) { // if there's an asterisk in the list, then accept attribute is not required if (ext[ii] === '*') { return []; } type = self.mimes[ext[ii]]; if (!type) { if (addMissingExtensions && /^\w+$/.test(ext[ii])) { mimes.push('.' + ext[ii]); } else { return []; // accept all } } else if (Basic.inArray(type, mimes) === -1) { mimes.push(type); } } } return mimes; }, mimes2exts: function(mimes) { var self = this, exts = []; Basic.each(mimes, function(mime) { if (mime === '*') { exts = []; return false; } // check if this thing looks like mime type var m = mime.match(/^(\w+)\/(\*|\w+)$/); if (m) { if (m[2] === '*') { // wildcard mime type detected Basic.each(self.extensions, function(arr, mime) { if ((new RegExp('^' + m[1] + '/')).test(mime)) { [].push.apply(exts, self.extensions[mime]); } }); } else if (self.extensions[mime]) { [].push.apply(exts, self.extensions[mime]); } } }); return exts; }, mimes2extList: function(mimes) { var accept = [], exts = []; if (Basic.typeOf(mimes) === 'string') { mimes = Basic.trim(mimes).split(/\s*,\s*/); } exts = this.mimes2exts(mimes); accept.push({ title: I18n.translate('Files'), extensions: exts.length ? exts.join(',') : '*' }); // save original mimes string accept.mimes = mimes; return accept; }, getFileExtension: function(fileName) { var matches = fileName && fileName.match(/\.([^.]+)$/); if (matches) { return matches[1].toLowerCase(); } return ''; }, getFileMime: function(fileName) { return this.mimes[this.getFileExtension(fileName)] || ''; } }; Mime.addMimeType(mimeData); return Mime; }); // Included from: src/javascript/core/utils/Env.js /** * Env.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/core/utils/Env", [ "moxie/core/utils/Basic" ], function(Basic) { var browser = [{ s1: navigator.userAgent, s2: "Android", id: "Android Browser", // default or Dolphin sv: "Version" },{ s1: navigator.userAgent, // string s2: "Chrome", // substring id: "Chrome" // identity },{ s1: navigator.vendor, s2: "Apple", id: "Safari", sv: "Version" // version },{ prop: window.opera && window.opera.buildNumber, id: "Opera", sv: "Version" },{ s1: navigator.vendor, s2: "KDE", id: "Konqueror" },{ s1: navigator.userAgent, s2: "Firefox", id: "Firefox" },{ s1: navigator.vendor, s2: "Camino", id: "Camino" },{ // for newer Netscapes (6+) s1: navigator.userAgent, s2: "Netscape", id: "Netscape" },{ s1: navigator.userAgent, s2: "MSIE", id: "IE", sv: "MSIE" },{ s1: navigator.userAgent, s2: "Gecko", id: "Mozilla", sv: "rv" }], os = [{ s1: navigator.platform, s2: "Win", id: "Windows" },{ s1: navigator.platform, s2: "Mac", id: "Mac" },{ s1: navigator.userAgent, s2: "iPhone", id: "iOS" },{ s1: navigator.userAgent, s2: "iPad", id: "iOS" },{ s1: navigator.userAgent, s2: "Android", id: "Android" },{ s1: navigator.platform, s2: "Linux", id: "Linux" }] , version; function getStr(data) { var str, prop; for (var i = 0; i < data.length; i++) { str = data[i].s1; prop = data[i].prop; version = data[i].sv || data[i].id; if (str) { if (str.indexOf(data[i].s2) != -1) { return data[i].id; } } else if (prop) { return data[i].id; } } } function getVer(str) { var index = str.indexOf(version); if (index == -1) { return; } return parseFloat(str.substring(index + version.length + 1)); } var can = (function() { var caps = { define_property: (function() { /* // currently too much extra code required, not exactly worth it try { // as of IE8, getters/setters are supported only on DOM elements var obj = {}; if (Object.defineProperty) { Object.defineProperty(obj, 'prop', { enumerable: true, configurable: true }); return true; } } catch(ex) {} if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) { return true; }*/ return false; }()), create_canvas: (function() { // On the S60 and BB Storm, getContext exists, but always returns undefined // so we actually have to call getContext() to verify // github.com/Modernizr/Modernizr/issues/issue/97/ var el = document.createElement('canvas'); return !!(el.getContext && el.getContext('2d')); }()), return_response_type: function(responseType) { try { if (Basic.inArray(responseType, ['', 'text', 'document']) !== -1) { return true; } else if (window.XMLHttpRequest){ var xhr = new XMLHttpRequest(); xhr.open('get', '/'); // otherwise Gecko throws an exception if ('responseType' in xhr) { xhr.responseType = responseType; // as of 23.0.1271.64, Chrome switched from throwing exception to merely logging it to the console (why? o why?) if (xhr.responseType !== responseType) { return false; } return true; } } } catch (ex) {} return false; }, // ideas for this heavily come from Modernizr (http://modernizr.com/) use_data_uri: (function() { var du = new Image(); du.onload = function() { caps.use_data_uri = (du.width === 1 && du.height === 1); }; setTimeout(function() { du.src = "data:image/gif;base64,R0lGODlhAQABAIAAAP8AAAAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=="; }, 1); return false; }()), use_data_uri_over32kb: function() { // IE8 return caps.use_data_uri && (Env.browser !== 'IE' || Env.version >= 9); }, use_data_uri_of: function(bytes) { return (caps.use_data_uri && bytes < 33000 || caps.use_data_uri_over32kb()); }, use_fileinput: function() { var el = document.createElement('input'); el.setAttribute('type', 'file'); return !el.disabled; } }; return function(cap) { var args = [].slice.call(arguments); args.shift(); // shift of cap return Basic.typeOf(caps[cap]) === 'function' ? caps[cap].apply(this, args) : !!caps[cap]; }; }()); var Env = { can: can, browser: getStr(browser), version: getVer(navigator.userAgent) || getVer(navigator.appVersion), OS: getStr(os), swf_url: "../flash/Moxie.swf", xap_url: "../silverlight/Moxie.xap", global_event_dispatcher: "moxie.core.EventTarget.instance.dispatchEvent" }; return Env; }); // Included from: src/javascript/core/utils/Dom.js /** * Dom.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Dom', ['moxie/core/utils/Env'], function(Env) { /** Get DOM Element by it's id. @method get @for Utils @param {String} id Identifier of the DOM Element @return {DOMElement} */ var get = function(id) { if (typeof id !== 'string') { return id; } return document.getElementById(id); }; /** Checks if specified DOM element has specified class. @method hasClass @static @param {Object} obj DOM element like object to add handler to. @param {String} name Class name */ var hasClass = function(obj, name) { var regExp; if (obj.className === '') { return false; } regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)"); return regExp.test(obj.className); }; /** Adds specified className to specified DOM element. @method addClass @static @param {Object} obj DOM element like object to add handler to. @param {String} name Class name */ var addClass = function(obj, name) { if (!hasClass(obj, name)) { obj.className = obj.className === '' ? name : obj.className.replace(/\s+$/, '') + ' ' + name; } }; /** Removes specified className from specified DOM element. @method removeClass @static @param {Object} obj DOM element like object to add handler to. @param {String} name Class name */ var removeClass = function(obj, name) { var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)"); obj.className = obj.className.replace(regExp, function($0, $1, $2) { return $1 === ' ' && $2 === ' ' ? ' ' : ''; }); }; /** Returns a given computed style of a DOM element. @method getStyle @static @param {Object} obj DOM element like object. @param {String} name Style you want to get from the DOM element */ var getStyle = function(obj, name) { if (obj.currentStyle) { return obj.currentStyle[name]; } else if (window.getComputedStyle) { return window.getComputedStyle(obj, null)[name]; } }; /** Returns the absolute x, y position of an Element. The position will be returned in a object with x, y fields. @method getPos @static @param {Element} node HTML element or element id to get x, y position from. @param {Element} root Optional root element to stop calculations at. @return {object} Absolute position of the specified element object with x, y fields. */ var getPos = function(node, root) { var x = 0, y = 0, parent, doc = document, nodeRect, rootRect; node = node; root = root || doc.body; // Returns the x, y cordinate for an element on IE 6 and IE 7 function getIEPos(node) { var bodyElm, rect, x = 0, y = 0; if (node) { rect = node.getBoundingClientRect(); bodyElm = doc.compatMode === "CSS1Compat" ? doc.documentElement : doc.body; x = rect.left + bodyElm.scrollLeft; y = rect.top + bodyElm.scrollTop; } return { x : x, y : y }; } // Use getBoundingClientRect on IE 6 and IE 7 but not on IE 8 in standards mode if (node && node.getBoundingClientRect && Env.browser === 'IE' && (!doc.documentMode || doc.documentMode < 8)) { nodeRect = getIEPos(node); rootRect = getIEPos(root); return { x : nodeRect.x - rootRect.x, y : nodeRect.y - rootRect.y }; } parent = node; while (parent && parent != root && parent.nodeType) { x += parent.offsetLeft || 0; y += parent.offsetTop || 0; parent = parent.offsetParent; } parent = node.parentNode; while (parent && parent != root && parent.nodeType) { x -= parent.scrollLeft || 0; y -= parent.scrollTop || 0; parent = parent.parentNode; } return { x : x, y : y }; }; /** Returns the size of the specified node in pixels. @method getSize @static @param {Node} node Node to get the size of. @return {Object} Object with a w and h property. */ var getSize = function(node) { return { w : node.offsetWidth || node.clientWidth, h : node.offsetHeight || node.clientHeight }; }; return { get: get, hasClass: hasClass, addClass: addClass, removeClass: removeClass, getStyle: getStyle, getPos: getPos, getSize: getSize }; }); // Included from: src/javascript/core/Exceptions.js /** * Exceptions.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/Exceptions', [ 'moxie/core/utils/Basic' ], function(Basic) { function _findKey(obj, value) { var key; for (key in obj) { if (obj[key] === value) { return key; } } return null; } return { RuntimeError: (function() { var namecodes = { NOT_INIT_ERR: 1, NOT_SUPPORTED_ERR: 9, JS_ERR: 4 }; function RuntimeError(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": RuntimeError " + this.code; } Basic.extend(RuntimeError, namecodes); RuntimeError.prototype = Error.prototype; return RuntimeError; }()), OperationNotAllowedException: (function() { function OperationNotAllowedException(code) { this.code = code; this.name = 'OperationNotAllowedException'; } Basic.extend(OperationNotAllowedException, { NOT_ALLOWED_ERR: 1 }); OperationNotAllowedException.prototype = Error.prototype; return OperationNotAllowedException; }()), ImageError: (function() { var namecodes = { WRONG_FORMAT: 1, MAX_RESOLUTION_ERR: 2 }; function ImageError(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": ImageError " + this.code; } Basic.extend(ImageError, namecodes); ImageError.prototype = Error.prototype; return ImageError; }()), FileException: (function() { var namecodes = { NOT_FOUND_ERR: 1, SECURITY_ERR: 2, ABORT_ERR: 3, NOT_READABLE_ERR: 4, ENCODING_ERR: 5, NO_MODIFICATION_ALLOWED_ERR: 6, INVALID_STATE_ERR: 7, SYNTAX_ERR: 8 }; function FileException(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": FileException " + this.code; } Basic.extend(FileException, namecodes); FileException.prototype = Error.prototype; return FileException; }()), DOMException: (function() { var namecodes = { INDEX_SIZE_ERR: 1, DOMSTRING_SIZE_ERR: 2, HIERARCHY_REQUEST_ERR: 3, WRONG_DOCUMENT_ERR: 4, INVALID_CHARACTER_ERR: 5, NO_DATA_ALLOWED_ERR: 6, NO_MODIFICATION_ALLOWED_ERR: 7, NOT_FOUND_ERR: 8, NOT_SUPPORTED_ERR: 9, INUSE_ATTRIBUTE_ERR: 10, INVALID_STATE_ERR: 11, SYNTAX_ERR: 12, INVALID_MODIFICATION_ERR: 13, NAMESPACE_ERR: 14, INVALID_ACCESS_ERR: 15, VALIDATION_ERR: 16, TYPE_MISMATCH_ERR: 17, SECURITY_ERR: 18, NETWORK_ERR: 19, ABORT_ERR: 20, URL_MISMATCH_ERR: 21, QUOTA_EXCEEDED_ERR: 22, TIMEOUT_ERR: 23, INVALID_NODE_TYPE_ERR: 24, DATA_CLONE_ERR: 25 }; function DOMException(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": DOMException " + this.code; } Basic.extend(DOMException, namecodes); DOMException.prototype = Error.prototype; return DOMException; }()), EventException: (function() { function EventException(code) { this.code = code; this.name = 'EventException'; } Basic.extend(EventException, { UNSPECIFIED_EVENT_TYPE_ERR: 0 }); EventException.prototype = Error.prototype; return EventException; }()) }; }); // Included from: src/javascript/core/EventTarget.js /** * EventTarget.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/EventTarget', [ 'moxie/core/Exceptions', 'moxie/core/utils/Basic' ], function(x, Basic) { /** Parent object for all event dispatching components and objects @class EventTarget @constructor EventTarget */ function EventTarget() { // hash of event listeners by object uid var eventpool = {}; Basic.extend(this, { /** Unique id of the event dispatcher, usually overriden by children @property uid @type String */ uid: null, /** Can be called from within a child in order to acquire uniqie id in automated manner @method init */ init: function() { if (!this.uid) { this.uid = Basic.guid('uid_'); } }, /** Register a handler to a specific event dispatched by the object @method addEventListener @param {String} type Type or basically a name of the event to subscribe to @param {Function} fn Callback function that will be called when event happens @param {Number} [priority=0] Priority of the event handler - handlers with higher priorities will be called first @param {Object} [scope=this] A scope to invoke event handler in */ addEventListener: function(type, fn, priority, scope) { var self = this, list; type = Basic.trim(type); if (/\s/.test(type)) { // multiple event types were passed for one handler Basic.each(type.split(/\s+/), function(type) { self.addEventListener(type, fn, priority, scope); }); return; } type = type.toLowerCase(); priority = parseInt(priority, 10) || 0; list = eventpool[this.uid] && eventpool[this.uid][type] || []; list.push({fn : fn, priority : priority, scope : scope || this}); if (!eventpool[this.uid]) { eventpool[this.uid] = {}; } eventpool[this.uid][type] = list; }, /** Check if any handlers were registered to the specified event @method hasEventListener @param {String} type Type or basically a name of the event to check @return {Mixed} Returns a handler if it was found and false, if - not */ hasEventListener: function(type) { return type ? !!(eventpool[this.uid] && eventpool[this.uid][type]) : !!eventpool[this.uid]; }, /** Unregister the handler from the event, or if former was not specified - unregister all handlers @method removeEventListener @param {String} type Type or basically a name of the event @param {Function} [fn] Handler to unregister */ removeEventListener: function(type, fn) { type = type.toLowerCase(); var list = eventpool[this.uid] && eventpool[this.uid][type], i; if (list) { if (fn) { for (i = list.length - 1; i >= 0; i--) { if (list[i].fn === fn) { list.splice(i, 1); break; } } } else { list = []; } // delete event list if it has become empty if (!list.length) { delete eventpool[this.uid][type]; // and object specific entry in a hash if it has no more listeners attached if (Basic.isEmptyObj(eventpool[this.uid])) { delete eventpool[this.uid]; } } } }, /** Remove all event handlers from the object @method removeAllEventListeners */ removeAllEventListeners: function() { if (eventpool[this.uid]) { delete eventpool[this.uid]; } }, /** Dispatch the event @method dispatchEvent @param {String/Object} Type of event or event object to dispatch @param {Mixed} [...] Variable number of arguments to be passed to a handlers @return {Boolean} true by default and false if any handler returned false */ dispatchEvent: function(type) { var uid, list, args, tmpEvt, evt = {}; if (Basic.typeOf(type) !== 'string') { // we can't use original object directly (because of Silverlight) tmpEvt = type; if (Basic.typeOf(tmpEvt.type) === 'string') { type = tmpEvt.type; if (tmpEvt.total && tmpEvt.loaded) { // progress event evt.total = tmpEvt.total; evt.loaded = tmpEvt.loaded; } evt.async = tmpEvt.async || false; } else { throw new x.EventException(x.EventException.UNSPECIFIED_EVENT_TYPE_ERR); } } // check if event is meant to be dispatched on an object having specific uid if (type.indexOf('::') !== -1) { (function(arr) { uid = arr[0]; type = arr[1]; }(type.split('::'))); } else { uid = this.uid; } type = type.toLowerCase(); list = eventpool[uid] && eventpool[uid][type]; if (list) { // sort event list by prority list.sort(function(a, b) { return b.priority - a.priority; }); args = [].slice.call(arguments); // first argument will be pseudo-event object args.shift(); evt.type = type; args.unshift(evt); // Dispatch event to all listeners var queue = []; Basic.each(list, function(handler) { // explicitly set the target, otherwise events fired from shims do not get it args[0].target = handler.scope; // if event is marked as async, detach the handler if (evt.async) { queue.push(function(cb) { setTimeout(function() { cb(handler.fn.apply(handler.scope, args) === false); }, 1); }); } else { queue.push(function(cb) { cb(handler.fn.apply(handler.scope, args) === false); // if handler returns false stop propagation }); } }); if (queue.length) { Basic.inSeries(queue); } } return true; }, /** Alias for addEventListener @method bind @protected */ bind: function() { this.addEventListener.apply(this, arguments); }, /** Alias for removeEventListener @method unbind @protected */ unbind: function() { this.removeEventListener.apply(this, arguments); }, /** Alias for removeAllEventListeners @method unbindAll @protected */ unbindAll: function() { this.removeAllEventListeners.apply(this, arguments); }, /** Alias for dispatchEvent @method trigger @protected */ trigger: function() { this.dispatchEvent.apply(this, arguments); }, /** Converts properties of on[event] type to corresponding event handlers, is used to avoid extra hassle around the process of calling them back @method convertEventPropsToHandlers @private */ convertEventPropsToHandlers: function(handlers) { var h; if (Basic.typeOf(handlers) !== 'array') { handlers = [handlers]; } for (var i = 0; i < handlers.length; i++) { h = 'on' + handlers[i]; if (Basic.typeOf(this[h]) === 'function') { this.addEventListener(handlers[i], this[h]); } else if (Basic.typeOf(this[h]) === 'undefined') { this[h] = null; // object must have defined event properties, even if it doesn't make use of them } } } }); } EventTarget.instance = new EventTarget(); return EventTarget; }); // Included from: src/javascript/core/utils/Encode.js /** * Encode.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Encode', [], function() { /** Encode string with UTF-8 @method utf8_encode @for Utils @static @param {String} str String to encode @return {String} UTF-8 encoded string */ var utf8_encode = function(str) { return unescape(encodeURIComponent(str)); }; /** Decode UTF-8 encoded string @method utf8_decode @static @param {String} str String to decode @return {String} Decoded string */ var utf8_decode = function(str_data) { return decodeURIComponent(escape(str_data)); }; /** Decode Base64 encoded string (uses browser's default method if available), from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_decode.js @method atob @static @param {String} data String to decode @return {String} Decoded string */ var atob = function(data, utf8) { if (typeof(window.atob) === 'function') { return utf8 ? utf8_decode(window.atob(data)) : window.atob(data); } // http://kevin.vanzonneveld.net // + original by: Tyler Akins (http://rumkin.com) // + improved by: Thunder.m // + input by: Aman Gupta // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Onno Marsman // + bugfixed by: Pellentesque Malesuada // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // * example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA=='); // * returns 1: 'Kevin van Zonneveld' // mozilla has this native // - but breaks in 2.0.0.12! //if (typeof this.window.atob == 'function') { // return atob(data); //} var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = []; if (!data) { return data; } data += ''; do { // unpack four hexets into three octets using index points in b64 h1 = b64.indexOf(data.charAt(i++)); h2 = b64.indexOf(data.charAt(i++)); h3 = b64.indexOf(data.charAt(i++)); h4 = b64.indexOf(data.charAt(i++)); bits = h1 << 18 | h2 << 12 | h3 << 6 | h4; o1 = bits >> 16 & 0xff; o2 = bits >> 8 & 0xff; o3 = bits & 0xff; if (h3 == 64) { tmp_arr[ac++] = String.fromCharCode(o1); } else if (h4 == 64) { tmp_arr[ac++] = String.fromCharCode(o1, o2); } else { tmp_arr[ac++] = String.fromCharCode(o1, o2, o3); } } while (i < data.length); dec = tmp_arr.join(''); return utf8 ? utf8_decode(dec) : dec; }; /** Base64 encode string (uses browser's default method if available), from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_encode.js @method btoa @static @param {String} data String to encode @return {String} Base64 encoded string */ var btoa = function(data, utf8) { if (utf8) { utf8_encode(data); } if (typeof(window.btoa) === 'function') { return window.btoa(data); } // http://kevin.vanzonneveld.net // + original by: Tyler Akins (http://rumkin.com) // + improved by: Bayron Guevara // + improved by: Thunder.m // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Pellentesque Malesuada // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Rafał Kukawski (http://kukawski.pl) // * example 1: base64_encode('Kevin van Zonneveld'); // * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA==' // mozilla has this native // - but breaks in 2.0.0.12! var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc = "", tmp_arr = []; if (!data) { return data; } do { // pack three octets into four hexets o1 = data.charCodeAt(i++); o2 = data.charCodeAt(i++); o3 = data.charCodeAt(i++); bits = o1 << 16 | o2 << 8 | o3; h1 = bits >> 18 & 0x3f; h2 = bits >> 12 & 0x3f; h3 = bits >> 6 & 0x3f; h4 = bits & 0x3f; // use hexets to index into b64, and append result to encoded string tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); } while (i < data.length); enc = tmp_arr.join(''); var r = data.length % 3; return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3); }; return { utf8_encode: utf8_encode, utf8_decode: utf8_decode, atob: atob, btoa: btoa }; }); // Included from: src/javascript/runtime/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/runtime/Runtime', [ "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/EventTarget" ], function(Basic, Dom, EventTarget) { var runtimeConstructors = {}, runtimes = {}; /** Common set of methods and properties for every runtime instance @class Runtime @param {Object} options @param {String} type Sanitized name of the runtime @param {Object} [caps] Set of capabilities that differentiate specified runtime @param {Object} [modeCaps] Set of capabilities that do require specific operational mode @param {String} [defaultMode='browser'] Default operational mode to choose if no required capabilities were requested */ function Runtime(options, type, caps, modeCaps, defaultMode) { /** Dispatched when runtime is initialized and ready. Results in RuntimeInit on a connected component. @event Init */ /** Dispatched when runtime fails to initialize. Results in RuntimeError on a connected component. @event Error */ var self = this , _shim , _uid = Basic.guid(type + '_') ; /** Runtime (not native one) may operate in browser or client mode. @method _setMode @private @param {Object} [modeCaps] Set of capabilities that do require specific operational mode @param {Object} [defaultMode] The mode to switch to if modeCaps or requiredCaps are empty */ function _setMode(modeCaps, defaultMode) { var mode = null , rc = options && options.required_caps ; defaultMode = defaultMode || 'browser'; // mode can be effectively set only once if (this.mode !== null) { return this.mode; } if (rc && !Basic.isEmptyObj(modeCaps)) { // loop over required caps and check if they do require the same mode Basic.each(rc, function(value, cap) { if (modeCaps.hasOwnProperty(cap)) { var capMode = modeCaps[cap](value); // make sure we always have an array if (typeof(capMode) === 'string') { capMode = [capMode]; } if (!mode) { mode = capMode; } else if (!(mode = Basic.arrayIntersect(mode, capMode))) { // if cap requires conflicting mode - runtime cannot fulfill required caps return (mode = false); } } }); if (mode) { this.mode = Basic.inArray(defaultMode, mode) !== -1 ? defaultMode : mode[0]; } else if (mode === false) { this.mode = false; } } // if mode still not defined if (this.mode === null) { this.mode = defaultMode; } // once we got the mode, test against all caps if (this.mode && rc && !this.can(rc)) { this.mode = false; } } // register runtime in private hash runtimes[_uid] = this; /** Default set of capabilities, which can be redifined later by specific runtime @private @property caps @type Object */ caps = Basic.extend({ // Runtime can: // provide access to raw binary data of the file access_binary: false, // provide access to raw binary data of the image (image extension is optional) access_image_binary: false, // display binary data as thumbs for example display_media: false, // make cross-domain requests do_cors: false, // accept files dragged and dropped from the desktop drag_and_drop: false, // filter files in selection dialog by their extensions filter_by_extension: true, // resize image (and manipulate it raw data of any file in general) resize_image: false, // periodically report how many bytes of total in the file were uploaded (loaded) report_upload_progress: false, // provide access to the headers of http response return_response_headers: false, // support response of specific type, which should be passed as an argument // e.g. runtime.can('return_response_type', 'blob') return_response_type: false, // return http status code of the response return_status_code: true, // send custom http header with the request send_custom_headers: false, // pick up the files from a dialog select_file: false, // select whole folder in file browse dialog select_folder: false, // select multiple files at once in file browse dialog select_multiple: true, // send raw binary data, that is generated after image resizing or manipulation of other kind send_binary_string: false, // send cookies with http request and therefore retain session send_browser_cookies: true, // send data formatted as multipart/form-data send_multipart: true, // slice the file or blob to smaller parts slice_blob: false, // upload file without preloading it to memory, stream it out directly from disk stream_upload: false, // programmatically trigger file browse dialog summon_file_dialog: false, // upload file of specific size, size should be passed as argument // e.g. runtime.can('upload_filesize', '500mb') upload_filesize: true, // initiate http request with specific http method, method should be passed as argument // e.g. runtime.can('use_http_method', 'put') use_http_method: true }, caps); // small extension factory here (is meant to be extended with actual extensions constructors) _shim = (function() { var objpool = {}; return { exec: function(uid, comp, fn, args) { if (_shim[comp]) { if (!objpool[uid]) { objpool[uid] = { context: this, instance: new _shim[comp]() }; } if (objpool[uid].instance[fn]) { return objpool[uid].instance[fn].apply(this, args); } } }, removeInstance: function(uid) { delete objpool[uid]; }, removeAllInstances: function() { var self = this; Basic.each(objpool, function(obj, uid) { if (Basic.typeOf(obj.instance.destroy) === 'function') { obj.instance.destroy.call(obj.context); } self.removeInstance(uid); }); } }; }()); // public methods Basic.extend(this, { /** Specifies whether runtime instance was initialized or not @property initialized @type {Boolean} @default false */ initialized: false, // shims require this flag to stop initialization retries /** Unique ID of the runtime @property uid @type {String} */ uid: _uid, /** Runtime type (e.g. flash, html5, etc) @property type @type {String} */ type: type, /** Runtime (not native one) may operate in browser or client mode. @property mode @private @type {String|Boolean} current mode or false, if none possible */ mode: null, /** id of the DOM container for the runtime (if available) @property shimid @type {String} */ shimid: _uid + '_container', /** Number of connected clients. If equal to zero, runtime can be destroyed @property clients @type {Number} */ clients: 0, /** Runtime initialization options @property options @type {Object} */ options: options, /** Checks if the runtime has specific capability @method can @param {String} cap Name of capability to check @param {Mixed} [value] If passed, capability should somehow correlate to the value @param {Object} [refCaps] Set of capabilities to check the specified cap against (defaults to internal set) @return {Boolean} true if runtime has such capability and false, if - not */ can: function(cap, value) { var refCaps = arguments[2] || caps; // if cap var is a comma-separated list of caps, convert it to object (key/value) if (Basic.typeOf(cap) === 'string' && Basic.typeOf(value) === 'undefined') { cap = Runtime.parseCaps(cap); } if (Basic.typeOf(cap) === 'object') { for (var key in cap) { if (!this.can(key, cap[key], refCaps)) { return false; } } return true; } // check the individual cap if (Basic.typeOf(refCaps[cap]) === 'function') { return refCaps[cap].call(this, value); } else { return (value === refCaps[cap]); } }, /** Returns container for the runtime as DOM element @method getShimContainer @return {DOMElement} */ getShimContainer: function() { var container, shimContainer = Dom.get(this.shimid); // if no container for shim, create one if (!shimContainer) { container = this.options.container ? Dom.get(this.options.container) : document.body; // create shim container and insert it at an absolute position into the outer container shimContainer = document.createElement('div'); shimContainer.id = this.shimid; shimContainer.className = 'moxie-shim moxie-shim-' + this.type; Basic.extend(shimContainer.style, { position: 'absolute', top: '0px', left: '0px', width: '1px', height: '1px', overflow: 'hidden' }); container.appendChild(shimContainer); container = null; } return shimContainer; }, /** Returns runtime as DOM element (if appropriate) @method getShim @return {DOMElement} */ getShim: function() { return _shim; }, /** Invokes a method within the runtime itself (might differ across the runtimes) @method shimExec @param {Mixed} [] @protected @return {Mixed} Depends on the action and component */ shimExec: function(component, action) { var args = [].slice.call(arguments, 2); return self.getShim().exec.call(this, this.uid, component, action, args); }, /** Operaional interface that is used by components to invoke specific actions on the runtime (is invoked in the scope of component) @method exec @param {Mixed} []* @protected @return {Mixed} Depends on the action and component */ exec: function(component, action) { // this is called in the context of component, not runtime var args = [].slice.call(arguments, 2); if (self[component] && self[component][action]) { return self[component][action].apply(this, args); } return self.shimExec.apply(this, arguments); }, /** Destroys the runtime (removes all events and deletes DOM structures) @method destroy */ destroy: function() { if (!self) { return; // obviously already destroyed } var shimContainer = Dom.get(this.shimid); if (shimContainer) { shimContainer.parentNode.removeChild(shimContainer); } if (_shim) { _shim.removeAllInstances(); } this.unbindAll(); delete runtimes[this.uid]; this.uid = null; // mark this runtime as destroyed _uid = self = _shim = shimContainer = null; } }); _setMode.call(this, modeCaps, defaultMode); } /** Default order to try different runtime types @property order @type String @static */ Runtime.order = 'html5,flash,silverlight,html4'; /** Retrieves runtime from private hash by it's uid @method getRuntime @private @static @param {String} uid Unique identifier of the runtime @return {Runtime|Boolean} Returns runtime, if it exists and false, if - not */ Runtime.getRuntime = function(uid) { return runtimes[uid] ? runtimes[uid] : false; }; /** Register constructor for the Runtime of new (or perhaps modified) type @method addConstructor @static @param {String} type Runtime type (e.g. flash, html5, etc) @param {Function} construct Constructor for the Runtime type */ Runtime.addConstructor = function(type, constructor) { constructor.prototype = EventTarget.instance; runtimeConstructors[type] = constructor; }; /** Get the constructor for the specified type. method getConstructor @static @param {String} type Runtime type (e.g. flash, html5, etc) @return {Function} Constructor for the Runtime type */ Runtime.getConstructor = function(type) { return runtimeConstructors[type] || null; }; /** Get info about the runtime (uid, type, capabilities) @method getInfo @static @param {String} uid Unique identifier of the runtime @return {Mixed} Info object or null if runtime doesn't exist */ Runtime.getInfo = function(uid) { var runtime = Runtime.getRuntime(uid); if (runtime) { return { uid: runtime.uid, type: runtime.type, can: function() { return runtime.can.apply(runtime, arguments); } }; } return null; }; /** Convert caps represented by a comma-separated string to the object representation. @method parseCaps @static @param {String} capStr Comma-separated list of capabilities @return {Object} */ Runtime.parseCaps = function(capStr) { var capObj = {}; if (Basic.typeOf(capStr) !== 'string') { return capStr || {}; } Basic.each(capStr.split(','), function(key) { capObj[key] = true; // we assume it to be - true }); return capObj; }; /** Test the specified runtime for specific capabilities. @method can @static @param {String} type Runtime type (e.g. flash, html5, etc) @param {String|Object} caps Set of capabilities to check @return {Boolean} Result of the test */ Runtime.can = function(type, caps) { var runtime , constructor = Runtime.getConstructor(type) , mode ; if (constructor) { runtime = new constructor({ required_caps: caps }); mode = runtime.mode; runtime.destroy(); return !!mode; } return false; }; /** Figure out a runtime that supports specified capabilities. @method thatCan @static @param {String|Object} caps Set of capabilities to check @param {String} [runtimeOrder] Comma-separated list of runtimes to check against @return {String} Usable runtime identifier or null */ Runtime.thatCan = function(caps, runtimeOrder) { var types = (runtimeOrder || Runtime.order).split(/\s*,\s*/); for (var i in types) { if (Runtime.can(types[i], caps)) { return types[i]; } } return null; }; /** Capability check that always returns true @private @static @return {True} */ Runtime.capTrue = function() { return true; }; /** Capability check that always returns false @private @static @return {False} */ Runtime.capFalse = function() { return false; }; /** Evaluate the expression to boolean value and create a function that always returns it. @private @static @param {Mixed} expr Expression to evaluate @return {Function} Function returning the result of evaluation */ Runtime.capTest = function(expr) { return function() { return !!expr; }; }; return Runtime; }); // Included from: src/javascript/runtime/RuntimeClient.js /** * RuntimeClient.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/runtime/RuntimeClient', [ 'moxie/core/Exceptions', 'moxie/core/utils/Basic', 'moxie/runtime/Runtime' ], function(x, Basic, Runtime) { /** Set of methods and properties, required by a component to acquire ability to connect to a runtime @class RuntimeClient */ return function RuntimeClient() { var runtime; Basic.extend(this, { /** Connects to the runtime specified by the options. Will either connect to existing runtime or create a new one. Increments number of clients connected to the specified runtime. @method connectRuntime @param {Mixed} options Can be a runtme uid or a set of key-value pairs defining requirements and pre-requisites */ connectRuntime: function(options) { var comp = this, ruid; function initialize(items) { var type, constructor; // if we ran out of runtimes if (!items.length) { comp.trigger('RuntimeError', new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR)); runtime = null; return; } type = items.shift(); constructor = Runtime.getConstructor(type); if (!constructor) { initialize(items); return; } // try initializing the runtime runtime = new constructor(options); //alert(runtime); runtime.bind('Init', function() { // mark runtime as initialized runtime.initialized = true; // jailbreak ... setTimeout(function() { //console.log(runtime,typeof runtime); runtime.clients++; // this will be triggered on component comp.trigger('RuntimeInit', runtime); }, 2000); }); runtime.bind('Error', function() { runtime.destroy(); // runtime cannot destroy itself from inside at a right moment, thus we do it here initialize(items); }); /*runtime.bind('Exception', function() { });*/ // check if runtime managed to pick-up operational mode if (!runtime.mode) { runtime.trigger('Error'); return; } setTimeout(function(){ runtime.init(); },200); } // check if a particular runtime was requested if (Basic.typeOf(options) === 'string') { ruid = options; } else if (Basic.typeOf(options.ruid) === 'string') { ruid = options.ruid; } if (ruid) { runtime = Runtime.getRuntime(ruid); if (runtime) { runtime.clients++; return runtime; } else { // there should be a runtime and there's none - weird case throw new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR); } } // initialize a fresh one, that fits runtime list and required features best initialize((options.runtime_order || Runtime.order).split(/\s*,\s*/)); }, /** Returns the runtime to which the client is currently connected. @method getRuntime @return {Runtime} Runtime or null if client is not connected */ getRuntime: function() { if (runtime && runtime.uid) { return runtime; } runtime = null; // make sure we do not leave zombies rambling around return null; }, /** Disconnects from the runtime. Decrements number of clients connected to the specified runtime. @method disconnectRuntime */ disconnectRuntime: function() { if (runtime && --runtime.clients <= 0) { runtime.destroy(); runtime = null; } } }); }; }); // Included from: src/javascript/file/Blob.js /** * Blob.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/Blob', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Encode', 'moxie/runtime/RuntimeClient' ], function(Basic, Encode, RuntimeClient) { var blobpool = {}; /** @class Blob @constructor @param {String} ruid Unique id of the runtime, to which this blob belongs to @param {Object} blob Object "Native" blob object, as it is represented in the runtime */ function Blob(ruid, blob) { function _sliceDetached(start, end, type) { var blob, data = blobpool[this.uid]; if (Basic.typeOf(data) !== 'string' || !data.length) { return null; // or throw exception } blob = new Blob(null, { type: type, size: end - start }); blob.detach(data.substr(start, blob.size)); return blob; } RuntimeClient.call(this); if (ruid) { this.connectRuntime(ruid); } if (!blob) { blob = {}; } else if (Basic.typeOf(blob) === 'string') { // dataUrl or binary string blob = { data: blob }; } Basic.extend(this, { /** Unique id of the component @property uid @type {String} */ uid: blob.uid || Basic.guid('uid_'), /** Unique id of the connected runtime, if falsy, then runtime will have to be initialized before this Blob can be used, modified or sent @property ruid @type {String} */ ruid: ruid, /** Size of blob @property size @type {Number} @default 0 */ size: blob.size || 0, /** Mime type of blob @property type @type {String} @default '' */ type: blob.type || '', /** @method slice @param {Number} [start=0] */ slice: function(start, end, type) { if (this.isDetached()) { return _sliceDetached.apply(this, arguments); } return this.getRuntime().exec.call(this, 'Blob', 'slice', this.getSource(), start, end, type); }, /** Returns "native" blob object (as it is represented in connected runtime) or null if not found @method getSource @return {Blob} Returns "native" blob object or null if not found */ getSource: function() { if (!blobpool[this.uid]) { return null; } return blobpool[this.uid]; }, /** Detaches blob from any runtime that it depends on and initialize with standalone value @method detach @protected @param {DOMString} [data=''] Standalone value */ detach: function(data) { if (this.ruid) { this.getRuntime().exec.call(this, 'Blob', 'destroy', blobpool[this.uid]); this.disconnectRuntime(); this.ruid = null; } data = data || ''; // if dataUrl, convert to binary string var matches = data.match(/^data:([^;]*);base64,/); if (matches) { this.type = matches[1]; data = Encode.atob(data.substring(data.indexOf('base64,') + 7)); } this.size = data.length; blobpool[this.uid] = data; }, /** Checks if blob is standalone (detached of any runtime) @method isDetached @protected @return {Boolean} */ isDetached: function() { return !this.ruid && Basic.typeOf(blobpool[this.uid]) === 'string'; }, /** Destroy Blob and free any resources it was using @method destroy */ destroy: function() { this.detach(); delete blobpool[this.uid]; } }); if (blob.data) { this.detach(blob.data); // auto-detach if payload has been passed } else { blobpool[this.uid] = blob; } } return Blob; }); // Included from: src/javascript/file/File.js /** * File.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/File', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Mime', 'moxie/file/Blob' ], function(Basic, Mime, Blob) { /** @class File @extends Blob @constructor @param {String} ruid Unique id of the runtime, to which this blob belongs to @param {Object} file Object "Native" file object, as it is represented in the runtime */ function File(ruid, file) { var name, type; if (!file) { // avoid extra errors in case we overlooked something file = {}; } // figure out the type if (file.type && file.type !== '') { type = file.type; } else { type = Mime.getFileMime(file.name); } // sanitize file name or generate new one if (file.name) { name = file.name.replace(/\\/g, '/'); name = name.substr(name.lastIndexOf('/') + 1); } else { var prefix = type.split('/')[0]; name = Basic.guid((prefix !== '' ? prefix : 'file') + '_'); if (Mime.extensions[type]) { name += '.' + Mime.extensions[type][0]; // append proper extension if possible } } Blob.apply(this, arguments); Basic.extend(this, { /** File mime type @property type @type {String} @default '' */ type: type || '', /** File name @property name @type {String} @default UID */ name: name || Basic.guid('file_'), /** Date of last modification @property lastModifiedDate @type {String} @default now */ lastModifiedDate: file.lastModifiedDate || (new Date()).toLocaleString() // Thu Aug 23 2012 19:40:00 GMT+0400 (GET) }); } File.prototype = Blob.prototype; return File; }); // Included from: src/javascript/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/FileInput', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Mime', 'moxie/core/utils/Dom', 'moxie/core/Exceptions', 'moxie/core/EventTarget', 'moxie/core/I18n', 'moxie/file/File', 'moxie/runtime/Runtime', 'moxie/runtime/RuntimeClient' ], function(Basic, Mime, Dom, x, EventTarget, I18n, File, Runtime, RuntimeClient) { /** Provides a convenient way to create cross-browser file-picker. Generates file selection dialog on click, converts selected files to _File_ objects, to be used in conjunction with _Image_, preloaded in memory with _FileReader_ or uploaded to a server through _XMLHttpRequest_. @class FileInput @constructor @extends EventTarget @uses RuntimeClient @param {Object|String|DOMElement} options If options is string or node, argument is considered as _browse\_button_. @param {String|DOMElement} options.browse_button DOM Element to turn into file picker. @param {Array} [options.accept] Array of mime types to accept. By default accepts all. @param {String} [options.file='file'] Name of the file field (not the filename). @param {Boolean} [options.multiple=false] Enable selection of multiple files. @param {Boolean} [options.directory=false] Turn file input into the folder input (cannot be both at the same time). @param {String|DOMElement} [options.container] DOM Element to use as a container for file-picker. Defaults to parentNode for _browse\_button_. @param {Object|String} [options.required_caps] Set of required capabilities, that chosen runtime must support. @example <div id="container"> <a id="file-picker" href="javascript:;">Browse...</a> </div> <script> var fileInput = new mOxie.FileInput({ browse_button: 'file-picker', // or document.getElementById('file-picker') container: 'container', accept: [ {title: "Image files", extensions: "jpg,gif,png"} // accept only images ], multiple: true // allow multiple file selection }); fileInput.onchange = function(e) { // do something to files array //console.info(e.target.files); // or this.files or fileInput.files }; fileInput.init(); // initialize </script> */ var dispatches = [ /** Dispatched when runtime is connected and file-picker is ready to be used. @event ready @param {Object} event */ 'ready', /** Dispatched right after [ready](#event_ready) event, and whenever [refresh()](#method_refresh) is invoked. Check [corresponding documentation entry](#method_refresh) for more info. @event refresh @param {Object} event */ /** Dispatched when selection of files in the dialog is complete. @event change @param {Object} event */ 'change', 'cancel', // TODO: might be useful /** Dispatched when mouse cursor enters file-picker area. Can be used to style element accordingly. @event mouseenter @param {Object} event */ 'mouseenter', /** Dispatched when mouse cursor leaves file-picker area. Can be used to style element accordingly. @event mouseleave @param {Object} event */ 'mouseleave', /** Dispatched when functional mouse button is pressed on top of file-picker area. @event mousedown @param {Object} event */ 'mousedown', /** Dispatched when functional mouse button is released on top of file-picker area. @event mouseup @param {Object} event */ 'mouseup' ]; function FileInput(options) { var self = this, container, browseButton, defaults; // if flat argument passed it should be browse_button id if (Basic.inArray(Basic.typeOf(options), ['string', 'node']) !== -1) { options = { browse_button : options }; } // this will help us to find proper default container browseButton = Dom.get(options.browse_button); if (!browseButton) { // browse button is required throw new x.DOMException(x.DOMException.NOT_FOUND_ERR); } // figure out the options defaults = { accept: [{ title: I18n.translate('All Files'), extensions: '*' }], name: 'file', multiple: false, required_caps: false, container: browseButton.parentNode || document.body }; options = Basic.extend({}, defaults, options); // convert to object representation if (typeof(options.required_caps) === 'string') { options.required_caps = Runtime.parseCaps(options.required_caps); } // normalize accept option (could be list of mime types or array of title/extensions pairs) if (typeof(options.accept) === 'string') { options.accept = Mime.mimes2extList(options.accept); } container = Dom.get(options.container); // make sure we have container if (!container) { container = document.body; } // make container relative, if it's not if (Dom.getStyle(container, 'position') === 'static') { container.style.position = 'relative'; } container = browseButton = null; // IE RuntimeClient.call(self); Basic.extend(self, { /** Unique id of the component @property uid @protected @readOnly @type {String} @default UID */ uid: Basic.guid('uid_'), /** Unique id of the connected runtime, if any. @property ruid @protected @type {String} */ ruid: null, /** Array of selected mOxie.File objects @property files @type {Array} @default null */ files: null, /** Initializes the file-picker, connects it to runtime and dispatches event ready when done. @method init */ init: function() { self.convertEventPropsToHandlers(dispatches); self.bind('RuntimeInit', function(e, runtime) { self.ruid = runtime.uid; self.bind("Ready", function() { self.trigger("Refresh"); }, 999); self.bind("Change", function() { var files = runtime.exec.call(self, 'FileInput', 'getFiles'); self.files = []; Basic.each(files, function(file) { // ignore empty files (IE10 for example hangs if you try to send them via XHR) if (file.size === 0) { return true; } self.files.push(new File(self.ruid, file)); }); }, 999); // re-position and resize shim container self.bind('Refresh', function() { var pos, size, browseButton, shimContainer; browseButton = Dom.get(options.browse_button); shimContainer = Dom.get(runtime.shimid); // do not use runtime.getShimContainer(), since it will create container if it doesn't exist if (browseButton) { pos = Dom.getPos(browseButton, Dom.get(options.container)); size = Dom.getSize(browseButton); if (shimContainer) { Basic.extend(shimContainer.style, { top : pos.y + 'px', left : pos.x + 'px', width : size.w + 'px', height : size.h + 'px' }); } } shimContainer = browseButton = null; }); runtime.exec.call(self, 'FileInput', 'init', options); }); // runtime needs: options.required_features, options.runtime_order and options.container self.connectRuntime(Basic.extend({}, options, { required_caps: { select_file: true } })); }, /** Disables file-picker element, so that it doesn't react to mouse clicks. @method disable @param {Boolean} [state=true] Disable component if - true, enable if - false */ disable: function(state) { var runtime = this.getRuntime(); if (runtime) { runtime.exec.call(this, 'FileInput', 'disable', Basic.typeOf(state) === 'undefined' ? true : state); } }, /** Reposition and resize dialog trigger to match the position and size of browse_button element. @method refresh */ refresh: function() { self.trigger("Refresh"); }, /** Destroy component. @method destroy */ destroy: function() { var runtime = this.getRuntime(); if (runtime) { runtime.exec.call(this, 'FileInput', 'destroy'); this.disconnectRuntime(); } if (Basic.typeOf(this.files) === 'array') { // no sense in leaving associated files behind Basic.each(this.files, function(file) { file.destroy(); }); } this.files = null; } }); } FileInput.prototype = EventTarget.instance; return FileInput; }); // Included from: src/javascript/file/FileDrop.js /** * FileDrop.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/FileDrop', [ 'moxie/core/I18n', 'moxie/core/utils/Dom', 'moxie/core/Exceptions', 'moxie/core/utils/Basic', 'moxie/file/File', 'moxie/runtime/RuntimeClient', 'moxie/core/EventTarget', 'moxie/core/utils/Mime' ], function(I18n, Dom, x, Basic, File, RuntimeClient, EventTarget, Mime) { /** Turn arbitrary DOM element to a drop zone accepting files. Converts selected files to _File_ objects, to be used in conjunction with _Image_, preloaded in memory with _FileReader_ or uploaded to a server through _XMLHttpRequest_. @example <div id="drop_zone"> Drop files here </div> <br /> <div id="filelist"></div> <script type="text/javascript"> var fileDrop = new mOxie.FileDrop('drop_zone'), fileList = mOxie.get('filelist'); fileDrop.ondrop = function() { mOxie.each(this.files, function(file) { fileList.innerHTML += '<div>' + file.name + '</div>'; }); }; fileDrop.init(); </script> @class FileDrop @constructor @extends EventTarget @uses RuntimeClient @param {Object|String} options If options has typeof string, argument is considered as options.drop_zone @param {String|DOMElement} options.drop_zone DOM Element to turn into a drop zone @param {Array} [options.accept] Array of mime types to accept. By default accepts all @param {Object|String} [options.required_caps] Set of required capabilities, that chosen runtime must support */ var dispatches = [ /** Dispatched when runtime is connected and drop zone is ready to accept files. @event ready @param {Object} event */ 'ready', /** Dispatched when dragging cursor enters the drop zone. @event dragenter @param {Object} event */ 'dragenter', /** Dispatched when dragging cursor leaves the drop zone. @event dragleave @param {Object} event */ 'dragleave', /** Dispatched when file is dropped onto the drop zone. @event drop @param {Object} event */ 'drop', /** Dispatched if error occurs. @event error @param {Object} event */ 'error' ]; function FileDrop(options) { var self = this, defaults; // if flat argument passed it should be drop_zone id if (typeof(options) === 'string') { options = { drop_zone : options }; } // figure out the options defaults = { accept: [{ title: I18n.translate('All Files'), extensions: '*' }], required_caps: { drag_and_drop: true } }; options = typeof(options) === 'object' ? Basic.extend({}, defaults, options) : defaults; // this will help us to find proper default container options.container = Dom.get(options.drop_zone) || document.body; // make container relative, if it is not if (Dom.getStyle(options.container, 'position') === 'static') { options.container.style.position = 'relative'; } // normalize accept option (could be list of mime types or array of title/extensions pairs) if (typeof(options.accept) === 'string') { options.accept = Mime.mimes2extList(options.accept); } RuntimeClient.call(self); Basic.extend(self, { uid: Basic.guid('uid_'), ruid: null, files: null, init: function() { self.convertEventPropsToHandlers(dispatches); self.bind('RuntimeInit', function(e, runtime) { self.ruid = runtime.uid; self.bind("Drop", function() { var files = runtime.exec.call(self, 'FileDrop', 'getFiles'); self.files = []; Basic.each(files, function(file) { self.files.push(new File(self.ruid, file)); }); }, 999); runtime.exec.call(self, 'FileDrop', 'init', options); self.dispatchEvent('ready'); }); // runtime needs: options.required_features, options.runtime_order and options.container self.connectRuntime(options); // throws RuntimeError }, destroy: function() { var runtime = this.getRuntime(); if (runtime) { runtime.exec.call(this, 'FileDrop', 'destroy'); this.disconnectRuntime(); } this.files = null; } }); } FileDrop.prototype = EventTarget.instance; return FileDrop; }); // Included from: src/javascript/runtime/RuntimeTarget.js /** * RuntimeTarget.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/runtime/RuntimeTarget', [ 'moxie/core/utils/Basic', 'moxie/runtime/RuntimeClient', "moxie/core/EventTarget" ], function(Basic, RuntimeClient, EventTarget) { /** Instance of this class can be used as a target for the events dispatched by shims, when allowing them onto components is for either reason inappropriate @class RuntimeTarget @constructor @protected @extends EventTarget */ function RuntimeTarget() { this.uid = Basic.guid('uid_'); RuntimeClient.call(this); this.destroy = function() { this.disconnectRuntime(); this.unbindAll(); }; } RuntimeTarget.prototype = EventTarget.instance; return RuntimeTarget; }); // Included from: src/javascript/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/FileReader', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Encode', 'moxie/core/Exceptions', 'moxie/core/EventTarget', 'moxie/file/Blob', 'moxie/file/File', 'moxie/runtime/RuntimeTarget' ], function(Basic, Encode, x, EventTarget, Blob, File, RuntimeTarget) { /** Utility for preloading o.Blob/o.File objects in memory. By design closely follows [W3C FileReader](http://www.w3.org/TR/FileAPI/#dfn-filereader) interface. Where possible uses native FileReader, where - not falls back to shims. @class FileReader @constructor FileReader @extends EventTarget @uses RuntimeClient */ var dispatches = [ /** Dispatched when the read starts. @event loadstart @param {Object} event */ 'loadstart', /** Dispatched while reading (and decoding) blob, and reporting partial Blob data (progess.loaded/progress.total). @event progress @param {Object} event */ 'progress', /** Dispatched when the read has successfully completed. @event load @param {Object} event */ 'load', /** Dispatched when the read has been aborted. For instance, by invoking the abort() method. @event abort @param {Object} event */ 'abort', /** Dispatched when the read has failed. @event error @param {Object} event */ 'error', /** Dispatched when the request has completed (either in success or failure). @event loadend @param {Object} event */ 'loadend' ]; function FileReader() { var self = this, _fr; Basic.extend(this, { /** UID of the component instance. @property uid @type {String} */ uid: Basic.guid('uid_'), /** Contains current state of FileReader object. Can take values of FileReader.EMPTY, FileReader.LOADING and FileReader.DONE. @property readyState @type {Number} @default FileReader.EMPTY */ readyState: FileReader.EMPTY, /** Result of the successful read operation. @property result @type {String} */ result: null, /** Stores the error of failed asynchronous read operation. @property error @type {DOMError} */ error: null, /** Initiates reading of File/Blob object contents to binary string. @method readAsBinaryString @param {Blob|File} blob Object to preload */ readAsBinaryString: function(blob) { _read.call(this, 'readAsBinaryString', blob); }, /** Initiates reading of File/Blob object contents to dataURL string. @method readAsDataURL @param {Blob|File} blob Object to preload */ readAsDataURL: function(blob) { _read.call(this, 'readAsDataURL', blob); }, /** Initiates reading of File/Blob object contents to string. @method readAsText @param {Blob|File} blob Object to preload */ readAsText: function(blob) { _read.call(this, 'readAsText', blob); }, /** Aborts preloading process. @method abort */ abort: function() { this.result = null; if (Basic.inArray(this.readyState, [FileReader.EMPTY, FileReader.DONE]) !== -1) { return; } else if (this.readyState === FileReader.LOADING) { this.readyState = FileReader.DONE; } if (_fr) { _fr.getRuntime().exec.call(this, 'FileReader', 'abort'); } this.trigger('abort'); this.trigger('loadend'); }, /** Destroy component and release resources. @method destroy */ destroy: function() { this.abort(); if (_fr) { _fr.getRuntime().exec.call(this, 'FileReader', 'destroy'); _fr.disconnectRuntime(); } self = _fr = null; } }); function _read(op, blob) { _fr = new RuntimeTarget(); function error(err) { self.readyState = FileReader.DONE; self.error = err; self.trigger('error'); loadEnd(); } function loadEnd() { _fr.destroy(); _fr = null; self.trigger('loadend'); } function exec(runtime) { _fr.bind('Error', function(e, err) { error(err); }); _fr.bind('Progress', function(e) { self.result = runtime.exec.call(_fr, 'FileReader', 'getResult'); self.trigger(e); }); _fr.bind('Load', function(e) { self.readyState = FileReader.DONE; self.result = runtime.exec.call(_fr, 'FileReader', 'getResult'); self.trigger(e); loadEnd(); }); runtime.exec.call(_fr, 'FileReader', 'read', op, blob); } this.convertEventPropsToHandlers(dispatches); if (this.readyState === FileReader.LOADING) { return error(new x.DOMException(x.DOMException.INVALID_STATE_ERR)); } this.readyState = FileReader.LOADING; this.trigger('loadstart'); // if source is o.Blob/o.File if (blob instanceof Blob) { if (blob.isDetached()) { var src = blob.getSource(); switch (op) { case 'readAsText': case 'readAsBinaryString': this.result = src; break; case 'readAsDataURL': this.result = 'data:' + blob.type + ';base64,' + Encode.btoa(src); break; } this.readyState = FileReader.DONE; this.trigger('load'); loadEnd(); } else { exec(_fr.connectRuntime(blob.ruid)); } } else { error(new x.DOMException(x.DOMException.NOT_FOUND_ERR)); } } } /** Initial FileReader state @property EMPTY @type {Number} @final @static @default 0 */ FileReader.EMPTY = 0; /** FileReader switches to this state when it is preloading the source @property LOADING @type {Number} @final @static @default 1 */ FileReader.LOADING = 1; /** Preloading is complete, this is a final state @property DONE @type {Number} @final @static @default 2 */ FileReader.DONE = 2; FileReader.prototype = EventTarget.instance; return FileReader; }); // Included from: src/javascript/core/utils/Url.js /** * Url.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Url', [], function() { /** Parse url into separate components and fill in absent parts with parts from current url, based on https://raw.github.com/kvz/phpjs/master/functions/url/parse_url.js @method parseUrl @for Utils @static @param {String} str Url to parse (defaults to empty string if undefined) @return {Object} Hash containing extracted uri components */ var parseUrl = function(str) { var key = ['source', 'scheme', 'authority', 'userInfo', 'user', 'pass', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'fragment'] , i = key.length , ports = { http: 80, https: 443 } , uri = {} , regex = /^(?:([^:\/?#]+):)?(?:\/\/()(?:(?:()(?:([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?()(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\\?([^#]*))?(?:#(.*))?)/ , m = regex.exec(str || '') // default to empty string if undefined ; while (i--) { if (m[i]) { uri[key[i]] = m[i]; } } if (/^[^\/]/.test(uri.path) && !uri.scheme) { // when url is relative, we need to figure out the path ourselves var path = document.location.pathname; // if path ends with a filename, strip it if (!/(\/|\/[^\.]+)$/.test(path)) { path = path.replace(/[^\/]+$/, ''); } uri.host = document.location.hostname; uri.path = path + (uri.path || ''); // site may reside at domain.com or domain.com/subdir } if (!uri.scheme) { uri.scheme = document.location.protocol.replace(/:$/, ''); } if (!uri.host) { uri.host = document.location.hostname; } if (!uri.port) { uri.port = document.location.port || ports[uri.scheme] || 80; } uri.port = parseInt(uri.port, 10); if (!uri.path) { uri.path = "/"; } delete uri.source; return uri; }; /** Resolve url - among other things will turn relative url to absolute @method resolveUrl @static @param {String} url Either absolute or relative @return {String} Resolved, absolute url */ var resolveUrl = function(url) { var ports = { // we ignore default ports http: 80, https: 443 } , urlp = parseUrl(url) ; return urlp.scheme + '://' + urlp.host + (urlp.port !== ports[urlp.scheme] ? ':' + urlp.port : '') + urlp.path + (urlp.query ? urlp.query : ''); }; /** Check if specified url has the same origin as the current document @method hasSameOrigin @param {String|Object} url @return {Boolean} */ var hasSameOrigin = function(url) { function origin(url) { return [url.scheme, url.host, url.port].join('/'); } if (typeof url === 'string') { url = parseUrl(url); } return origin(parseUrl()) === origin(url); }; return { parseUrl: parseUrl, resolveUrl: resolveUrl, hasSameOrigin: hasSameOrigin }; }); // Included from: src/javascript/file/FileReaderSync.js /** * FileReaderSync.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/FileReaderSync', [ 'moxie/core/utils/Basic', 'moxie/runtime/RuntimeClient', 'moxie/core/utils/Encode' ], function(Basic, RuntimeClient, Encode) { /** Synchronous FileReader implementation. Something like this is available in WebWorkers environment, here it can be used to read only preloaded blobs/files and only below certain size (not yet sure what that'd be, but probably < 1mb). Not meant to be used directly by user. @class FileReaderSync @private @constructor */ return function() { RuntimeClient.call(this); Basic.extend(this, { uid: Basic.guid('uid_'), readAsBinaryString: function(blob) { return _read.call(this, 'readAsBinaryString', blob); }, readAsDataURL: function(blob) { return _read.call(this, 'readAsDataURL', blob); }, /*readAsArrayBuffer: function(blob) { return _read.call(this, 'readAsArrayBuffer', blob); },*/ readAsText: function(blob) { return _read.call(this, 'readAsText', blob); } }); function _read(op, blob) { if (blob.isDetached()) { var src = blob.getSource(); switch (op) { case 'readAsBinaryString': return src; case 'readAsDataURL': return 'data:' + blob.type + ';base64,' + Encode.btoa(src); case 'readAsText': var txt = ''; for (var i = 0, length = src.length; i < length; i++) { txt += String.fromCharCode(src[i]); } return txt; } } else { var result = this.connectRuntime(blob.ruid).exec.call(this, 'FileReaderSync', 'read', op, blob); this.disconnectRuntime(); return result; } } }; }); // Included from: src/javascript/xhr/FormData.js /** * FormData.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/xhr/FormData", [ "moxie/core/Exceptions", "moxie/core/utils/Basic", "moxie/file/Blob" ], function(x, Basic, Blob) { /** FormData @class FormData @constructor */ function FormData() { var _blobField, _fields = {}, _name = ""; Basic.extend(this, { /** Append another key-value pair to the FormData object @method append @param {String} name Name for the new field @param {String|Blob|Array|Object} value Value for the field */ append: function(name, value) { var self = this, valueType = Basic.typeOf(value); if (value instanceof Blob) { if (_blobField) { delete _fields[_blobField]; } _blobField = name; _fields[name] = [value]; // unfortunately we can only send single Blob in one FormData } else if ('array' === valueType) { name += '[]'; Basic.each(value, function(value) { self.append.call(self, name, value); }); } else if ('object' === valueType) { Basic.each(value, function(value, key) { self.append.call(self, name + '[' + key + ']', value); }); } else { value = value.toString(); // according to specs value might be either Blob or String if (!_fields[name]) { _fields[name] = []; } _fields[name].push(value); } }, /** Checks if FormData contains Blob. @method hasBlob @return {Boolean} */ hasBlob: function() { return !!_blobField; }, /** Retrieves blob. @method getBlob @return {Object} Either Blob if found or null */ getBlob: function() { return _fields[_blobField] && _fields[_blobField][0] || null; }, /** Retrieves blob field name. @method getBlobName @return {String} Either Blob field name or null */ getBlobName: function() { return _blobField || null; }, /** Loop over the fields in FormData and invoke the callback for each of them. @method each @param {Function} cb Callback to call for each field */ each: function(cb) { Basic.each(_fields, function(value, name) { Basic.each(value, function(value) { cb(value, name); }); }); }, destroy: function() { _blobField = null; _name = ""; _fields = {}; } }); } return FormData; }); // Included from: src/javascript/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/xhr/XMLHttpRequest", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/core/EventTarget", "moxie/core/utils/Encode", "moxie/core/utils/Url", "moxie/runtime/Runtime", "moxie/runtime/RuntimeTarget", "moxie/file/Blob", "moxie/file/FileReaderSync", "moxie/xhr/FormData", "moxie/core/utils/Env", "moxie/core/utils/Mime" ], function(Basic, x, EventTarget, Encode, Url, Runtime, RuntimeTarget, Blob, FileReaderSync, FormData, Env, Mime) { var httpCode = { 100: 'Continue', 101: 'Switching Protocols', 102: 'Processing', 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-Authoritative Information', 204: 'No Content', 205: 'Reset Content', 206: 'Partial Content', 207: 'Multi-Status', 226: 'IM Used', 300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Found', 303: 'See Other', 304: 'Not Modified', 305: 'Use Proxy', 306: 'Reserved', 307: 'Temporary Redirect', 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Timeout', 409: 'Conflict', 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 413: 'Request Entity Too Large', 414: 'Request-URI Too Long', 415: 'Unsupported Media Type', 416: 'Requested Range Not Satisfiable', 417: 'Expectation Failed', 422: 'Unprocessable Entity', 423: 'Locked', 424: 'Failed Dependency', 426: 'Upgrade Required', 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout', 505: 'HTTP Version Not Supported', 506: 'Variant Also Negotiates', 507: 'Insufficient Storage', 510: 'Not Extended' }; function XMLHttpRequestUpload() { this.uid = Basic.guid('uid_'); } XMLHttpRequestUpload.prototype = EventTarget.instance; /** Implementation of XMLHttpRequest @class XMLHttpRequest @constructor @uses RuntimeClient @extends EventTarget */ var dispatches = ['loadstart', 'progress', 'abort', 'error', 'load', 'timeout', 'loadend']; // & readystatechange (for historical reasons) var NATIVE = 1, RUNTIME = 2; function XMLHttpRequest() { var self = this, // this (together with _p() @see below) is here to gracefully upgrade to setter/getter syntax where possible props = { /** The amount of milliseconds a request can take before being terminated. Initially zero. Zero means there is no timeout. @property timeout @type Number @default 0 */ timeout: 0, /** Current state, can take following values: UNSENT (numeric value 0) The object has been constructed. OPENED (numeric value 1) The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method. HEADERS_RECEIVED (numeric value 2) All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available. LOADING (numeric value 3) The response entity body is being received. DONE (numeric value 4) @property readyState @type Number @default 0 (UNSENT) */ readyState: XMLHttpRequest.UNSENT, /** True when user credentials are to be included in a cross-origin request. False when they are to be excluded in a cross-origin request and when cookies are to be ignored in its response. Initially false. @property withCredentials @type Boolean @default false */ withCredentials: false, /** Returns the HTTP status code. @property status @type Number @default 0 */ status: 0, /** Returns the HTTP status text. @property statusText @type String */ statusText: "", /** Returns the response type. Can be set to change the response type. Values are: the empty string (default), "arraybuffer", "blob", "document", "json", and "text". @property responseType @type String */ responseType: "", /** Returns the document response entity body. Throws an "InvalidStateError" exception if responseType is not the empty string or "document". @property responseXML @type Document */ responseXML: null, /** Returns the text response entity body. Throws an "InvalidStateError" exception if responseType is not the empty string or "text". @property responseText @type String */ responseText: null, /** Returns the response entity body (http://www.w3.org/TR/XMLHttpRequest/#response-entity-body). Can become: ArrayBuffer, Blob, Document, JSON, Text @property response @type Mixed */ response: null }, _async = true, _url, _method, _headers = {}, _user, _password, _encoding = null, _mimeType = null, // flags _sync_flag = false, _send_flag = false, _upload_events_flag = false, _upload_complete_flag = false, _error_flag = false, _same_origin_flag = false, // times _start_time, _timeoutset_time, _finalMime = null, _finalCharset = null, _options = {}, _xhr, _responseHeaders = '', _responseHeadersBag ; Basic.extend(this, props, { /** Unique id of the component @property uid @type String */ uid: Basic.guid('uid_'), /** Target for Upload events @property upload @type XMLHttpRequestUpload */ upload: new XMLHttpRequestUpload(), /** Sets the request method, request URL, synchronous flag, request username, and request password. Throws a "SyntaxError" exception if one of the following is true: method is not a valid HTTP method. url cannot be resolved. url contains the "user:password" format in the userinfo production. Throws a "SecurityError" exception if method is a case-insensitive match for CONNECT, TRACE or TRACK. Throws an "InvalidAccessError" exception if one of the following is true: Either user or password is passed as argument and the origin of url does not match the XMLHttpRequest origin. There is an associated XMLHttpRequest document and either the timeout attribute is not zero, the withCredentials attribute is true, or the responseType attribute is not the empty string. @method open @param {String} method HTTP method to use on request @param {String} url URL to request @param {Boolean} [async=true] If false request will be done in synchronous manner. Asynchronous by default. @param {String} [user] Username to use in HTTP authentication process on server-side @param {String} [password] Password to use in HTTP authentication process on server-side */ open: function(method, url, async, user, password) { var urlp; // first two arguments are required if (!method || !url) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 2 - check if any code point in method is higher than U+00FF or after deflating method it does not match the method if (/[\u0100-\uffff]/.test(method) || Encode.utf8_encode(method) !== method) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 3 if (!!~Basic.inArray(method.toUpperCase(), ['CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'TRACE', 'TRACK'])) { _method = method.toUpperCase(); } // 4 - allowing these methods poses a security risk if (!!~Basic.inArray(_method, ['CONNECT', 'TRACE', 'TRACK'])) { throw new x.DOMException(x.DOMException.SECURITY_ERR); } // 5 url = Encode.utf8_encode(url); // 6 - Resolve url relative to the XMLHttpRequest base URL. If the algorithm returns an error, throw a "SyntaxError". urlp = Url.parseUrl(url); _same_origin_flag = Url.hasSameOrigin(urlp); // 7 - manually build up absolute url _url = Url.resolveUrl(url); // 9-10, 12-13 if ((user || password) && !_same_origin_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } _user = user || urlp.user; _password = password || urlp.pass; // 11 _async = async || true; if (_async === false && (_p('timeout') || _p('withCredentials') || _p('responseType') !== "")) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // 14 - terminate abort() // 15 - terminate send() // 18 _sync_flag = !_async; _send_flag = false; _headers = {}; _reset.call(this); // 19 _p('readyState', XMLHttpRequest.OPENED); // 20 this.convertEventPropsToHandlers(['readystatechange']); // unify event handlers this.dispatchEvent('readystatechange'); }, /** Appends an header to the list of author request headers, or if header is already in the list of author request headers, combines its value with value. Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set. Throws a "SyntaxError" exception if header is not a valid HTTP header field name or if value is not a valid HTTP header field value. @method setRequestHeader @param {String} header @param {String|Number} value */ setRequestHeader: function(header, value) { var uaHeaders = [ // these headers are controlled by the user agent "accept-charset", "accept-encoding", "access-control-request-headers", "access-control-request-method", "connection", "content-length", "cookie", "cookie2", "content-transfer-encoding", "date", "expect", "host", "keep-alive", "origin", "referer", "te", "trailer", "transfer-encoding", "upgrade", "user-agent", "via" ]; // 1-2 if (_p('readyState') !== XMLHttpRequest.OPENED || _send_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 3 if (/[\u0100-\uffff]/.test(header) || Encode.utf8_encode(header) !== header) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 4 /* this step is seemingly bypassed in browsers, probably to allow various unicode characters in header values if (/[\u0100-\uffff]/.test(value) || Encode.utf8_encode(value) !== value) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); }*/ header = Basic.trim(header).toLowerCase(); // setting of proxy-* and sec-* headers is prohibited by spec if (!!~Basic.inArray(header, uaHeaders) || /^(proxy\-|sec\-)/.test(header)) { return false; } // camelize // browsers lowercase header names (at least for custom ones) // header = header.replace(/\b\w/g, function($1) { return $1.toUpperCase(); }); if (!_headers[header]) { _headers[header] = value; } else { // http://tools.ietf.org/html/rfc2616#section-4.2 (last paragraph) _headers[header] += ', ' + value; } return true; }, /** Returns all headers from the response, with the exception of those whose field name is Set-Cookie or Set-Cookie2. @method getAllResponseHeaders @return {String} reponse headers or empty string */ getAllResponseHeaders: function() { return _responseHeaders || ''; }, /** Returns the header field value from the response of which the field name matches header, unless the field name is Set-Cookie or Set-Cookie2. @method getResponseHeader @param {String} header @return {String} value(s) for the specified header or null */ getResponseHeader: function(header) { header = header.toLowerCase(); if (_error_flag || !!~Basic.inArray(header, ['set-cookie', 'set-cookie2'])) { return null; } if (_responseHeaders && _responseHeaders !== '') { // if we didn't parse response headers until now, do it and keep for later if (!_responseHeadersBag) { _responseHeadersBag = {}; Basic.each(_responseHeaders.split(/\r\n/), function(line) { var pair = line.split(/:\s+/); if (pair.length === 2) { // last line might be empty, omit pair[0] = Basic.trim(pair[0]); // just in case _responseHeadersBag[pair[0].toLowerCase()] = { // simply to retain header name in original form header: pair[0], value: Basic.trim(pair[1]) }; } }); } if (_responseHeadersBag.hasOwnProperty(header)) { return _responseHeadersBag[header].header + ': ' + _responseHeadersBag[header].value; } } return null; }, /** Sets the Content-Type header for the response to mime. Throws an "InvalidStateError" exception if the state is LOADING or DONE. Throws a "SyntaxError" exception if mime is not a valid media type. @method overrideMimeType @param String mime Mime type to set */ overrideMimeType: function(mime) { var matches, charset; // 1 if (!!~Basic.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2 mime = Basic.trim(mime.toLowerCase()); if (/;/.test(mime) && (matches = mime.match(/^([^;]+)(?:;\scharset\=)?(.*)$/))) { mime = matches[1]; if (matches[2]) { charset = matches[2]; } } if (!Mime.mimes[mime]) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 3-4 _finalMime = mime; _finalCharset = charset; }, /** Initiates the request. The optional argument provides the request entity body. The argument is ignored if request method is GET or HEAD. Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set. @method send @param {Blob|Document|String|FormData} [data] Request entity body @param {Object} [options] Set of requirements and pre-requisities for runtime initialization */ send: function(data, options) { if (Basic.typeOf(options) === 'string') { _options = { ruid: options }; } else if (!options) { _options = {}; } else { _options = options; } this.convertEventPropsToHandlers(dispatches); this.upload.convertEventPropsToHandlers(dispatches); // 1-2 if (this.readyState !== XMLHttpRequest.OPENED || _send_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 3 // sending Blob if (data instanceof Blob) { _options.ruid = data.ruid; _mimeType = data.type || 'application/octet-stream'; } // FormData else if (data instanceof FormData) { if (data.hasBlob()) { var blob = data.getBlob(); _options.ruid = blob.ruid; _mimeType = blob.type || 'application/octet-stream'; } } // DOMString else if (typeof data === 'string') { _encoding = 'UTF-8'; _mimeType = 'text/plain;charset=UTF-8'; // data should be converted to Unicode and encoded as UTF-8 data = Encode.utf8_encode(data); } // if withCredentials not set, but requested, set it automatically if (!this.withCredentials) { this.withCredentials = (_options.required_caps && _options.required_caps.send_browser_cookies) && !_same_origin_flag; } // 4 - storage mutex // 5 _upload_events_flag = (!_sync_flag && this.upload.hasEventListener()); // DSAP // 6 _error_flag = false; // 7 _upload_complete_flag = !data; // 8 - Asynchronous steps if (!_sync_flag) { // 8.1 _send_flag = true; // 8.2 // this.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr // 8.3 if (!_upload_complete_flag) { // this.upload.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr } } // 8.5 - Return the send() method call, but continue running the steps in this algorithm. _doXHR.call(this, data); }, /** Cancels any network activity. @method abort */ abort: function() { _error_flag = true; _sync_flag = false; if (!~Basic.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED, XMLHttpRequest.DONE])) { _p('readyState', XMLHttpRequest.DONE); _send_flag = false; if (_xhr) { _xhr.getRuntime().exec.call(_xhr, 'XMLHttpRequest', 'abort', _upload_complete_flag); } else { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } _upload_complete_flag = true; } else { _p('readyState', XMLHttpRequest.UNSENT); } }, destroy: function() { if (_xhr) { if (Basic.typeOf(_xhr.destroy) === 'function') { _xhr.destroy(); } _xhr = null; } this.unbindAll(); if (this.upload) { this.upload.unbindAll(); this.upload = null; } } }); /* this is nice, but maybe too lengthy // if supported by JS version, set getters/setters for specific properties o.defineProperty(this, 'readyState', { configurable: false, get: function() { return _p('readyState'); } }); o.defineProperty(this, 'timeout', { configurable: false, get: function() { return _p('timeout'); }, set: function(value) { if (_sync_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // timeout still should be measured relative to the start time of request _timeoutset_time = (new Date).getTime(); _p('timeout', value); } }); // the withCredentials attribute has no effect when fetching same-origin resources o.defineProperty(this, 'withCredentials', { configurable: false, get: function() { return _p('withCredentials'); }, set: function(value) { // 1-2 if (!~o.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED]) || _send_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 3-4 if (_anonymous_flag || _sync_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // 5 _p('withCredentials', value); } }); o.defineProperty(this, 'status', { configurable: false, get: function() { return _p('status'); } }); o.defineProperty(this, 'statusText', { configurable: false, get: function() { return _p('statusText'); } }); o.defineProperty(this, 'responseType', { configurable: false, get: function() { return _p('responseType'); }, set: function(value) { // 1 if (!!~o.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2 if (_sync_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // 3 _p('responseType', value.toLowerCase()); } }); o.defineProperty(this, 'responseText', { configurable: false, get: function() { // 1 if (!~o.inArray(_p('responseType'), ['', 'text'])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2-3 if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } return _p('responseText'); } }); o.defineProperty(this, 'responseXML', { configurable: false, get: function() { // 1 if (!~o.inArray(_p('responseType'), ['', 'document'])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2-3 if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } return _p('responseXML'); } }); o.defineProperty(this, 'response', { configurable: false, get: function() { if (!!~o.inArray(_p('responseType'), ['', 'text'])) { if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) { return ''; } } if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) { return null; } return _p('response'); } }); */ function _p(prop, value) { if (!props.hasOwnProperty(prop)) { return; } if (arguments.length === 1) { // get return Env.can('define_property') ? props[prop] : self[prop]; } else { // set if (Env.can('define_property')) { props[prop] = value; } else { self[prop] = value; } } } /* function _toASCII(str, AllowUnassigned, UseSTD3ASCIIRules) { // TODO: http://tools.ietf.org/html/rfc3490#section-4.1 return str.toLowerCase(); } */ function _doXHR(data) { var self = this; _start_time = new Date().getTime(); _xhr = new RuntimeTarget(); function loadEnd() { _xhr.destroy(); _xhr = null; self.dispatchEvent('loadend'); self = null; } function exec(runtime) { _xhr.bind('LoadStart', function(e) { _p('readyState', XMLHttpRequest.LOADING); self.dispatchEvent('readystatechange'); self.dispatchEvent(e); if (_upload_events_flag) { self.upload.dispatchEvent(e); } }); _xhr.bind('Progress', function(e) { if (_p('readyState') !== XMLHttpRequest.LOADING) { _p('readyState', XMLHttpRequest.LOADING); // LoadStart unreliable (in Flash for example) self.dispatchEvent('readystatechange'); } self.dispatchEvent(e); }); _xhr.bind('UploadProgress', function(e) { if (_upload_events_flag) { self.upload.dispatchEvent({ type: 'progress', lengthComputable: false, total: e.total, loaded: e.loaded }); } }); _xhr.bind('Load', function(e) { _p('readyState', XMLHttpRequest.DONE); _p('status', Number(runtime.exec.call(_xhr, 'XMLHttpRequest', 'getStatus') || 0)); _p('statusText', httpCode[_p('status')] || ""); _p('response', runtime.exec.call(_xhr, 'XMLHttpRequest', 'getResponse', _p('responseType'))); if (!!~Basic.inArray(_p('responseType'), ['text', ''])) { _p('responseText', _p('response')); } else if (_p('responseType') === 'document') { _p('responseXML', _p('response')); } _responseHeaders = runtime.exec.call(_xhr, 'XMLHttpRequest', 'getAllResponseHeaders'); self.dispatchEvent('readystatechange'); if (_p('status') > 0) { // status 0 usually means that server is unreachable if (_upload_events_flag) { self.upload.dispatchEvent(e); } self.dispatchEvent(e); } else { _error_flag = true; self.dispatchEvent('error'); } loadEnd(); }); _xhr.bind('Abort', function(e) { self.dispatchEvent(e); loadEnd(); }); _xhr.bind('Error', function(e) { _error_flag = true; _p('readyState', XMLHttpRequest.DONE); self.dispatchEvent('readystatechange'); _upload_complete_flag = true; self.dispatchEvent(e); loadEnd(); }); runtime.exec.call(_xhr, 'XMLHttpRequest', 'send', { url: _url, method: _method, async: _async, user: _user, password: _password, headers: _headers, mimeType: _mimeType, encoding: _encoding, responseType: self.responseType, withCredentials: self.withCredentials, options: _options }, data); } // clarify our requirements if (typeof(_options.required_caps) === 'string') { _options.required_caps = Runtime.parseCaps(_options.required_caps); } _options.required_caps = Basic.extend({}, _options.required_caps, { return_response_type: self.responseType }); if (data instanceof FormData) { _options.required_caps.send_multipart = true; } if (!_same_origin_flag) { _options.required_caps.do_cors = true; } if (_options.ruid) { // we do not need to wait if we can connect directly exec(_xhr.connectRuntime(_options)); } else { _xhr.bind('RuntimeInit', function(e, runtime) { exec(runtime); }); _xhr.bind('RuntimeError', function(e, err) { self.dispatchEvent('RuntimeError', err); }); _xhr.connectRuntime(_options); } } function _reset() { _p('responseText', ""); _p('responseXML', null); _p('response', null); _p('status', 0); _p('statusText', ""); _start_time = _timeoutset_time = null; } } XMLHttpRequest.UNSENT = 0; XMLHttpRequest.OPENED = 1; XMLHttpRequest.HEADERS_RECEIVED = 2; XMLHttpRequest.LOADING = 3; XMLHttpRequest.DONE = 4; XMLHttpRequest.prototype = EventTarget.instance; return XMLHttpRequest; }); // Included from: src/javascript/runtime/Transporter.js /** * Transporter.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/runtime/Transporter", [ "moxie/core/utils/Basic", "moxie/core/utils/Encode", "moxie/runtime/RuntimeClient", "moxie/core/EventTarget" ], function(Basic, Encode, RuntimeClient, EventTarget) { function Transporter() { var mod, _runtime, _data, _size, _pos, _chunk_size; RuntimeClient.call(this); Basic.extend(this, { uid: Basic.guid('uid_'), state: Transporter.IDLE, result: null, transport: function(data, type, options) { var self = this; options = Basic.extend({ chunk_size: 204798 }, options); // should divide by three, base64 requires this if ((mod = options.chunk_size % 3)) { options.chunk_size += 3 - mod; } _chunk_size = options.chunk_size; _reset.call(this); _data = data; _size = data.length; if (Basic.typeOf(options) === 'string' || options.ruid) { _run.call(self, type, this.connectRuntime(options)); } else { // we require this to run only once var cb = function(e, runtime) { self.unbind("RuntimeInit", cb); _run.call(self, type, runtime); }; this.bind("RuntimeInit", cb); this.connectRuntime(options); } }, abort: function() { var self = this; self.state = Transporter.IDLE; if (_runtime) { _runtime.exec.call(self, 'Transporter', 'clear'); self.trigger("TransportingAborted"); } _reset.call(self); }, destroy: function() { this.unbindAll(); _runtime = null; this.disconnectRuntime(); _reset.call(this); } }); function _reset() { _size = _pos = 0; _data = this.result = null; } function _run(type, runtime) { var self = this; _runtime = runtime; //self.unbind("RuntimeInit"); self.bind("TransportingProgress", function(e) { _pos = e.loaded; if (_pos < _size && Basic.inArray(self.state, [Transporter.IDLE, Transporter.DONE]) === -1) { _transport.call(self); } }, 999); self.bind("TransportingComplete", function() { _pos = _size; self.state = Transporter.DONE; _data = null; // clean a bit self.result = _runtime.exec.call(self, 'Transporter', 'getAsBlob', type || ''); }, 999); self.state = Transporter.BUSY; self.trigger("TransportingStarted"); _transport.call(self); } function _transport() { var self = this, chunk, bytesLeft = _size - _pos; if (_chunk_size > bytesLeft) { _chunk_size = bytesLeft; } chunk = Encode.btoa(_data.substr(_pos, _chunk_size)); _runtime.exec.call(self, 'Transporter', 'receive', chunk, _size); } } Transporter.IDLE = 0; Transporter.BUSY = 1; Transporter.DONE = 2; Transporter.prototype = EventTarget.instance; return Transporter; }); // Included from: src/javascript/core/JSON.js /** * JSON.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*jshint smarttabs:true */ define("moxie/core/JSON", [], function() { /** Parse string into the JSON object in a safe way @credits Douglas Crockford: https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js @method parse @static @protected @param {Object} obj Object to add property to @param {String} prop Property name @param {Object} desc Set of key-value pairs defining descriptor for the property */ return !!window.JSON && JSON.parse || (function() { "use strict"; // This is a function that can parse a JSON text, producing a JavaScript // data structure. It is a simple, recursive descent parser. It does not use // eval or regular expressions, so it can be used as a model for implementing // a JSON parser in other languages. // We are defining the function inside of another function to avoid // creating global variables. var at, // The index of the current character ch, // The current character escapee = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' }, text, error = function (m) { // Call error when something is wrong. throw { name: 'SyntaxError', message: m, at: at, text: text }; }, next = function (c) { // If a c parameter is provided, verify that it matches the current character. if (c && c !== ch) { error("Expected '" + c + "' instead of '" + ch + "'"); } // Get the next character. When there are no more characters, // return the empty string. ch = text.charAt(at); at += 1; return ch; }, number = function () { // Parse a number value. var number, string = ''; if (ch === '-') { string = '-'; next('-'); } while (ch >= '0' && ch <= '9') { string += ch; next(); } if (ch === '.') { string += '.'; while (next() && ch >= '0' && ch <= '9') { string += ch; } } if (ch === 'e' || ch === 'E') { string += ch; next(); if (ch === '-' || ch === '+') { string += ch; next(); } while (ch >= '0' && ch <= '9') { string += ch; next(); } } number = +string; if (!isFinite(number)) { error("Bad number"); } else { return number; } }, string = function () { // Parse a string value. var hex, i, string = '', uffff; // When parsing for string values, we must look for " and \ characters. if (ch === '"') { while (next()) { if (ch === '"') { next(); return string; } else if (ch === '\\') { next(); if (ch === 'u') { uffff = 0; for (i = 0; i < 4; i += 1) { hex = parseInt(next(), 16); if (!isFinite(hex)) { break; } uffff = uffff * 16 + hex; } string += String.fromCharCode(uffff); } else if (typeof escapee[ch] === 'string') { string += escapee[ch]; } else { break; } } else { string += ch; } } } error("Bad string"); }, white = function () { // Skip whitespace. while (ch && ch <= ' ') { next(); } }, word = function () { // true, false, or null. switch (ch) { case 't': next('t'); next('r'); next('u'); next('e'); return true; case 'f': next('f'); next('a'); next('l'); next('s'); next('e'); return false; case 'n': next('n'); next('u'); next('l'); next('l'); return null; } error("Unexpected '" + ch + "'"); }, value, // Place holder for the value function. array = function () { // Parse an array value. var array = []; if (ch === '[') { next('['); white(); if (ch === ']') { next(']'); return array; // empty array } while (ch) { array.push(value()); white(); if (ch === ']') { next(']'); return array; } next(','); white(); } } error("Bad array"); }, object = function () { // Parse an object value. var key, object = {}; if (ch === '{') { next('{'); white(); if (ch === '}') { next('}'); return object; // empty object } while (ch) { key = string(); white(); next(':'); if (Object.hasOwnProperty.call(object, key)) { error('Duplicate key "' + key + '"'); } object[key] = value(); white(); if (ch === '}') { next('}'); return object; } next(','); white(); } } error("Bad object"); }; value = function () { // Parse a JSON value. It could be an object, an array, a string, a number, // or a word. white(); switch (ch) { case '{': return object(); case '[': return array(); case '"': return string(); case '-': return number(); default: return ch >= '0' && ch <= '9' ? number() : word(); } }; // Return the json_parse function. It will have access to all of the above // functions and variables. return function (source, reviver) { var result; text = source; at = 0; ch = ' '; result = value(); white(); if (ch) { error("Syntax error"); } // If there is a reviver function, we recursively walk the new structure, // passing each name/value pair to the reviver function for possible // transformation, starting with a temporary root object that holds the result // in an empty key. If there is not a reviver function, we simply return the // result. return typeof reviver === 'function' ? (function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); }({'': result}, '')) : result; }; }()); }); // Included from: src/javascript/image/Image.js /** * Image.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/image/Image", [ "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/Exceptions", "moxie/file/FileReaderSync", "moxie/xhr/XMLHttpRequest", "moxie/runtime/Runtime", "moxie/runtime/RuntimeClient", "moxie/runtime/Transporter", "moxie/core/utils/Env", "moxie/core/EventTarget", "moxie/file/Blob", "moxie/file/File", "moxie/core/utils/Encode", "moxie/core/JSON" ], function(Basic, Dom, x, FileReaderSync, XMLHttpRequest, Runtime, RuntimeClient, Transporter, Env, EventTarget, Blob, File, Encode, parseJSON) { /** Image preloading and manipulation utility. Additionally it provides access to image meta info (Exif, GPS) and raw binary data. @class Image @constructor @extends EventTarget */ var dispatches = [ 'progress', /** Dispatched when loading is complete. @event load @param {Object} event */ 'load', 'error', /** Dispatched when resize operation is complete. @event resize @param {Object} event */ 'resize', /** Dispatched when visual representation of the image is successfully embedded into the corresponsing container. @event embedded @param {Object} event */ 'embedded' ]; function Image() { RuntimeClient.call(this); Basic.extend(this, { /** Unique id of the component @property uid @type {String} */ uid: Basic.guid('uid_'), /** Unique id of the connected runtime, if any. @property ruid @type {String} */ ruid: null, /** Name of the file, that was used to create an image, if available. If not equals to empty string. @property name @type {String} @default "" */ name: "", /** Size of the image in bytes. Actual value is set only after image is preloaded. @property size @type {Number} @default 0 */ size: 0, /** Width of the image. Actual value is set only after image is preloaded. @property width @type {Number} @default 0 */ width: 0, /** Height of the image. Actual value is set only after image is preloaded. @property height @type {Number} @default 0 */ height: 0, /** Mime type of the image. Currently only image/jpeg and image/png are supported. Actual value is set only after image is preloaded. @property type @type {String} @default "" */ type: "", /** Holds meta info (Exif, GPS). Is populated only for image/jpeg. Actual value is set only after image is preloaded. @property meta @type {Object} @default {} */ meta: {}, /** Alias for load method, that takes another mOxie.Image object as a source (see load). @method clone @param {Image} src Source for the image @param {Boolean} [exact=false] Whether to activate in-depth clone mode */ clone: function() { this.load.apply(this, arguments); }, /** Loads image from various sources. Currently the source for new image can be: mOxie.Image, mOxie.Blob/mOxie.File, native Blob/File, dataUrl or URL. Depending on the type of the source, arguments - differ. When source is URL, Image will be downloaded from remote destination and loaded in memory. @example var img = new mOxie.Image(); img.onload = function() { var blob = img.getAsBlob(); var formData = new mOxie.FormData(); formData.append('file', blob); var xhr = new mOxie.XMLHttpRequest(); xhr.onload = function() { // upload complete }; xhr.open('post', 'upload.php'); xhr.send(formData); }; img.load("http://www.moxiecode.com/images/mox-logo.jpg"); // notice file extension (.jpg) @method load @param {Image|Blob|File|String} src Source for the image @param {Boolean|Object} [mixed] */ load: function() { // this is here because to bind properly we need an uid first, which is created above this.bind('Load Resize', function() { _updateInfo.call(this); }, 999); this.convertEventPropsToHandlers(dispatches); _load.apply(this, arguments); }, /** Downsizes the image to fit the specified width/height. If crop is supplied, image will be cropped to exact dimensions. @method downsize @param {Number} width Resulting width @param {Number} [height=width] Resulting height (optional, if not supplied will default to width) @param {Boolean} [crop=false] Whether to crop the image to exact dimensions @param {Boolean} [preserveHeaders=true] Whether to preserve meta headers (on JPEGs after resize) */ downsize: function(width, height, crop, preserveHeaders) { try { if (!this.size) { // only preloaded image objects can be used as source throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // no way to reliably intercept the crash due to high resolution, so we simply avoid it if (this.width > Image.MAX_RESIZE_WIDTH || this.height > Image.MAX_RESIZE_HEIGHT) { throw new x.ImageError(x.ImageError.MAX_RESOLUTION_ERR); } if (!width && !height || Basic.typeOf(crop) === 'undefined') { crop = false; } width = width || this.width; height = height || this.height; preserveHeaders = (Basic.typeOf(preserveHeaders) === 'undefined' ? true : !!preserveHeaders); this.getRuntime().exec.call(this, 'Image', 'downsize', width, height, crop, preserveHeaders); } catch(ex) { // for now simply trigger error event this.trigger('error', ex); } }, /** Alias for downsize(width, height, true). (see downsize) @method crop @param {Number} width Resulting width @param {Number} [height=width] Resulting height (optional, if not supplied will default to width) @param {Boolean} [preserveHeaders=true] Whether to preserve meta headers (on JPEGs after resize) */ crop: function(width, height, preserveHeaders) { this.downsize(width, height, true, preserveHeaders); }, getAsCanvas: function() { if (!Env.can('create_canvas')) { throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR); } var runtime = this.connectRuntime(this.ruid); return runtime.exec.call(this, 'Image', 'getAsCanvas'); }, /** Retrieves image in it's current state as mOxie.Blob object. Cannot be run on empty or image in progress (throws DOMException.INVALID_STATE_ERR). @method getAsBlob @param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png @param {Number} [quality=90] Applicable only together with mime type image/jpeg @return {Blob} Image as Blob */ getAsBlob: function(type, quality) { if (!this.size) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } if (!type) { type = 'image/jpeg'; } if (type === 'image/jpeg' && !quality) { quality = 90; } return this.getRuntime().exec.call(this, 'Image', 'getAsBlob', type, quality); }, /** Retrieves image in it's current state as dataURL string. Cannot be run on empty or image in progress (throws DOMException.INVALID_STATE_ERR). @method getAsDataURL @param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png @param {Number} [quality=90] Applicable only together with mime type image/jpeg @return {String} Image as dataURL string */ getAsDataURL: function(type, quality) { if (!this.size) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } return this.getRuntime().exec.call(this, 'Image', 'getAsDataURL', type, quality); }, /** Retrieves image in it's current state as binary string. Cannot be run on empty or image in progress (throws DOMException.INVALID_STATE_ERR). @method getAsBinaryString @param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png @param {Number} [quality=90] Applicable only together with mime type image/jpeg @return {String} Image as binary string */ getAsBinaryString: function(type, quality) { var dataUrl = this.getAsDataURL(type, quality); return Encode.atob(dataUrl.substring(dataUrl.indexOf('base64,') + 7)); }, /** Embeds the image, or better to say, it's visual representation into the specified node. Depending on the runtime in use, might be a canvas, or image (actual ) element or shim object (Flash or SilverLight - very rare, used for legacy browsers that do not have canvas or proper dataURI support). @method embed @param {DOMElement} el DOM element to insert the image object into @param {Object} options Set of key/value pairs controlling the mime type, dimensions and cropping factor of resulting representation */ embed: function(el) { var self = this , imgCopy , type, quality, crop , options = arguments[1] || {} , width = this.width , height = this.height , runtime // this has to be outside of all the closures to contain proper runtime ; function onResize() { // if possible, embed a canvas element directly if (Env.can('create_canvas')) { var canvas = imgCopy.getAsCanvas(); if (canvas) { el.appendChild(canvas); canvas = null; imgCopy.destroy(); self.trigger('embedded'); return; } } var dataUrl = imgCopy.getAsDataURL(type, quality); if (!dataUrl) { throw new x.ImageError(x.ImageError.WRONG_FORMAT); } if (Env.can('use_data_uri_of', dataUrl.length)) { el.innerHTML = '<img src="' + dataUrl + '" width="' + imgCopy.width + '" height="' + imgCopy.height + '" />'; imgCopy.destroy(); self.trigger('embedded'); } else { var tr = new Transporter(); tr.bind("TransportingComplete", function() { runtime = self.connectRuntime(this.result.ruid); self.bind("Embedded", function() { // position and size properly Basic.extend(runtime.getShimContainer().style, { //position: 'relative', top: '0px', left: '0px', width: imgCopy.width + 'px', height: imgCopy.height + 'px' }); // some shims (Flash/SilverLight) reinitialize, if parent element is hidden, reordered or it's // position type changes (in Gecko), but since we basically need this only in IEs 6/7 and // sometimes 8 and they do not have this problem, we can comment this for now /*tr.bind("RuntimeInit", function(e, runtime) { tr.destroy(); runtime.destroy(); onResize.call(self); // re-feed our image data });*/ runtime = null; }, 999); runtime.exec.call(self, "ImageView", "display", this.result.uid, width, height); imgCopy.destroy(); }); tr.transport(Encode.atob(dataUrl.substring(dataUrl.indexOf('base64,') + 7)), type, Basic.extend({}, options, { required_caps: { display_media: true }, runtime_order: 'flash,silverlight', container: el })); } } try { if (!(el = Dom.get(el))) { throw new x.DOMException(x.DOMException.INVALID_NODE_TYPE_ERR); } if (!this.size) { // only preloaded image objects can be used as source throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } if (this.width > Image.MAX_RESIZE_WIDTH || this.height > Image.MAX_RESIZE_HEIGHT) { throw new x.ImageError(x.ImageError.MAX_RESOLUTION_ERR); } type = options.type || this.type || 'image/jpeg'; quality = options.quality || 90; crop = Basic.typeOf(options.crop) !== 'undefined' ? options.crop : false; // figure out dimensions for the thumb if (options.width) { width = options.width; height = options.height || width; } else { // if container element has > 0 dimensions, take them var dimensions = Dom.getSize(el); if (dimensions.w && dimensions.h) { // both should be > 0 width = dimensions.w; height = dimensions.h; } } imgCopy = new Image(); imgCopy.bind("Resize", function() { onResize.call(self); }); imgCopy.bind("Load", function() { imgCopy.downsize(width, height, crop, false); }); imgCopy.clone(this, false); return imgCopy; } catch(ex) { // for now simply trigger error event this.trigger('error', ex); } }, /** Properly destroys the image and frees resources in use. If any. Recommended way to dispose mOxie.Image object. @method destroy */ destroy: function() { if (this.ruid) { this.getRuntime().exec.call(this, 'Image', 'destroy'); this.disconnectRuntime(); } this.unbindAll(); } }); function _updateInfo(info) { if (!info) { info = this.getRuntime().exec.call(this, 'Image', 'getInfo'); } if (info) { if (Basic.typeOf(info.meta) === 'string') { // might be a JSON string try { this.meta = parseJSON(info.meta); } catch(ex) {} } else { this.meta = info.meta; } } Basic.extend(this, { // info object might be non-enumerable (as returned from SilverLight for example) size: parseInt(info.size, 10), width: parseInt(info.width, 10), height: parseInt(info.height, 10), type: info.type }); // update file name, only if empty if (this.name === '') { this.name = info.name; } } function _load(src) { var srcType = Basic.typeOf(src); try { // if source is Image if (src instanceof Image) { if (!src.size) { // only preloaded image objects can be used as source throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } _loadFromImage.apply(this, arguments); } // if source is o.Blob/o.File else if (src instanceof Blob) { if (!~Basic.inArray(src.type, ['image/jpeg', 'image/png'])) { throw new x.ImageError(x.ImageError.WRONG_FORMAT); } _loadFromBlob.apply(this, arguments); } // if native blob/file else if (Basic.inArray(srcType, ['blob', 'file']) !== -1) { _load.call(this, new File(null, src), arguments[1]); } // if String else if (srcType === 'string') { // if dataUrl String if (/^data:[^;]*;base64,/.test(src)) { _load.call(this, new Blob(null, { data: src }), arguments[1]); } // else assume Url, either relative or absolute else { _loadFromUrl.apply(this, arguments); } } // if source seems to be an img node else if (srcType === 'node' && src.nodeName.toLowerCase() === 'img') { _load.call(this, src.src, arguments[1]); } else { throw new x.DOMException(x.DOMException.TYPE_MISMATCH_ERR); } } catch(ex) { // for now simply trigger error event this.trigger('error', ex); } } function _loadFromImage(img, exact) { var runtime = this.connectRuntime(img.ruid); this.ruid = runtime.uid; runtime.exec.call(this, 'Image', 'loadFromImage', img, (Basic.typeOf(exact) === 'undefined' ? true : exact)); } function _loadFromBlob(blob, options) { var self = this; self.name = blob.name || ''; function exec(runtime) { self.ruid = runtime.uid; runtime.exec.call(self, 'Image', 'loadFromBlob', blob); } if (blob.isDetached()) { this.bind('RuntimeInit', function(e, runtime) { exec(runtime); }); // convert to object representation if (options && typeof(options.required_caps) === 'string') { options.required_caps = Runtime.parseCaps(options.required_caps); } this.connectRuntime(Basic.extend({ required_caps: { access_image_binary: true, resize_image: true } }, options)); } else { exec(this.connectRuntime(blob.ruid)); } } function _loadFromUrl(url, options) { var self = this, xhr; xhr = new XMLHttpRequest(); xhr.open('get', url); xhr.responseType = 'blob'; xhr.onprogress = function(e) { self.trigger(e); }; xhr.onload = function() { _loadFromBlob.call(self, xhr.response, true); }; xhr.onerror = function(e) { self.trigger(e); }; xhr.onloadend = function() { xhr.destroy(); }; xhr.bind('RuntimeError', function(e, err) { self.trigger('RuntimeError', err); }); xhr.send(null, options); } } // virtual world will crash on you if image has a resolution higher than this: Image.MAX_RESIZE_WIDTH = 6500; Image.MAX_RESIZE_HEIGHT = 6500; Image.prototype = EventTarget.instance; return Image; }); // Included from: src/javascript/runtime/html5/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global File:true */ /** Defines constructor for HTML5 runtime. @class moxie/runtime/html5/Runtime @private */ define("moxie/runtime/html5/Runtime", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/runtime/Runtime", "moxie/core/utils/Env" ], function(Basic, x, Runtime, Env) { var type = "html5", extensions = {}; function Html5Runtime(options) { var I = this , Test = Runtime.capTest , True = Runtime.capTrue ; var caps = Basic.extend({ access_binary: Test(window.FileReader || window.File && window.File.getAsDataURL), access_image_binary: function() { return I.can('access_binary') && !!extensions.Image; }, display_media: Test(Env.can('create_canvas') || Env.can('use_data_uri_over32kb')), do_cors: Test(window.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest()), drag_and_drop: Test(function() { // this comes directly from Modernizr: http://www.modernizr.com/ var div = document.createElement('div'); // IE has support for drag and drop since version 5, but doesn't support dropping files from desktop return (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div)) && (Env.browser !== 'IE' || Env.version > 9); }()), filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest return (Env.browser === 'Chrome' && Env.version >= 28) || (Env.browser === 'IE' && Env.version >= 10); }()), return_response_headers: True, return_response_type: function(responseType) { if (responseType === 'json') { return true; // we can fake this one even if it's not supported } else { return Env.can('return_response_type', responseType); } }, return_status_code: True, report_upload_progress: Test(window.XMLHttpRequest && new XMLHttpRequest().upload), resize_image: function() { return I.can('access_binary') && Env.can('create_canvas'); }, select_file: function() { return Env.can('use_fileinput') && window.File; }, select_folder: function() { return I.can('select_file') && Env.browser === 'Chrome' && Env.version >= 21; }, select_multiple: function() { return I.can('select_file') && !(Env.browser === 'Safari' && Env.OS === 'Windows'); }, send_binary_string: Test(window.XMLHttpRequest && (new XMLHttpRequest().sendAsBinary || (window.Uint8Array && window.ArrayBuffer))), send_custom_headers: Test(window.XMLHttpRequest), send_multipart: function() { return !!(window.XMLHttpRequest && new XMLHttpRequest().upload && window.FormData) || I.can('send_binary_string'); }, slice_blob: Test(window.File && (File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice)), stream_upload: function(){ return I.can('slice_blob') && I.can('send_multipart'); }, summon_file_dialog: Test(function() { // yeah... some dirty sniffing here... return (Env.browser === 'Firefox' && Env.version >= 4) || (Env.browser === 'Opera' && Env.version >= 12) || (Env.browser === 'IE' && Env.version >= 10) || !!~Basic.inArray(Env.browser, ['Chrome', 'Safari']); }()), upload_filesize: True }, arguments[2] ); Runtime.call(this, options, (arguments[1] || type), caps); Basic.extend(this, { init : function() { this.trigger("Init"); }, destroy: (function(destroy) { // extend default destroy method return function() { destroy.call(I); destroy = I = null; }; }(this.destroy)) }); Basic.extend(this.getShim(), extensions); } Runtime.addConstructor(type, Html5Runtime); return extensions; }); // Included from: src/javascript/runtime/html5/file/Blob.js /** * Blob.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/file/Blob @private */ define("moxie/runtime/html5/file/Blob", [ "moxie/runtime/html5/Runtime", "moxie/file/Blob" ], function(extensions, Blob) { function HTML5Blob() { function w3cBlobSlice(blob, start, end) { var blobSlice; if (window.File.prototype.slice) { try { blob.slice(); // depricated version will throw WRONG_ARGUMENTS_ERR exception return blob.slice(start, end); } catch (e) { // depricated slice method return blob.slice(start, end - start); } // slice method got prefixed: https://bugzilla.mozilla.org/show_bug.cgi?id=649672 } else if ((blobSlice = window.File.prototype.webkitSlice || window.File.prototype.mozSlice)) { return blobSlice.call(blob, start, end); } else { return null; // or throw some exception } } this.slice = function() { return new Blob(this.getRuntime().uid, w3cBlobSlice.apply(this, arguments)); }; } return (extensions.Blob = HTML5Blob); }); // Included from: src/javascript/core/utils/Events.js /** * Events.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Events', [ 'moxie/core/utils/Basic' ], function(Basic) { var eventhash = {}, uid = 'moxie_' + Basic.guid(); // IE W3C like event funcs function preventDefault() { this.returnValue = false; } function stopPropagation() { this.cancelBubble = true; } /** Adds an event handler to the specified object and store reference to the handler in objects internal Plupload registry (@see removeEvent). @method addEvent @for Utils @static @param {Object} obj DOM element like object to add handler to. @param {String} name Name to add event listener to. @param {Function} callback Function to call when event occurs. @param {String} [key] that might be used to add specifity to the event record. */ var addEvent = function(obj, name, callback, key) { var func, events; name = name.toLowerCase(); // Add event listener if (obj.addEventListener) { func = callback; obj.addEventListener(name, func, false); } else if (obj.attachEvent) { func = function() { var evt = window.event; if (!evt.target) { evt.target = evt.srcElement; } evt.preventDefault = preventDefault; evt.stopPropagation = stopPropagation; callback(evt); }; obj.attachEvent('on' + name, func); } // Log event handler to objects internal mOxie registry if (!obj[uid]) { obj[uid] = Basic.guid(); } if (!eventhash.hasOwnProperty(obj[uid])) { eventhash[obj[uid]] = {}; } events = eventhash[obj[uid]]; if (!events.hasOwnProperty(name)) { events[name] = []; } events[name].push({ func: func, orig: callback, // store original callback for IE key: key }); }; /** Remove event handler from the specified object. If third argument (callback) is not specified remove all events with the specified name. @method removeEvent @static @param {Object} obj DOM element to remove event listener(s) from. @param {String} name Name of event listener to remove. @param {Function|String} [callback] might be a callback or unique key to match. */ var removeEvent = function(obj, name, callback) { var type, undef; name = name.toLowerCase(); if (obj[uid] && eventhash[obj[uid]] && eventhash[obj[uid]][name]) { type = eventhash[obj[uid]][name]; } else { return; } for (var i = type.length - 1; i >= 0; i--) { // undefined or not, key should match if (type[i].orig === callback || type[i].key === callback) { if (obj.removeEventListener) { obj.removeEventListener(name, type[i].func, false); } else if (obj.detachEvent) { obj.detachEvent('on'+name, type[i].func); } type[i].orig = null; type[i].func = null; type.splice(i, 1); // If callback was passed we are done here, otherwise proceed if (callback !== undef) { break; } } } // If event array got empty, remove it if (!type.length) { delete eventhash[obj[uid]][name]; } // If mOxie registry has become empty, remove it if (Basic.isEmptyObj(eventhash[obj[uid]])) { delete eventhash[obj[uid]]; // IE doesn't let you remove DOM object property with - delete try { delete obj[uid]; } catch(e) { obj[uid] = undef; } } }; /** Remove all kind of events from the specified object @method removeAllEvents @static @param {Object} obj DOM element to remove event listeners from. @param {String} [key] unique key to match, when removing events. */ var removeAllEvents = function(obj, key) { if (!obj || !obj[uid]) { return; } Basic.each(eventhash[obj[uid]], function(events, name) { removeEvent(obj, name, key); }); }; return { addEvent: addEvent, removeEvent: removeEvent, removeAllEvents: removeAllEvents }; }); // Included from: src/javascript/runtime/html5/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/file/FileInput @private */ define("moxie/runtime/html5/file/FileInput", [ "moxie/runtime/html5/Runtime", "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/utils/Events", "moxie/core/utils/Mime", "moxie/core/utils/Env" ], function(extensions, Basic, Dom, Events, Mime, Env) { function FileInput() { var _files = [], _options; Basic.extend(this, { init: function(options) { var comp = this, I = comp.getRuntime(), input, shimContainer, mimes, browseButton, zIndex, top; _options = options; _files = []; // figure out accept string mimes = _options.accept.mimes || Mime.extList2mimes(_options.accept, I.can('filter_by_extension')); shimContainer = I.getShimContainer(); shimContainer.innerHTML = '<input id="' + I.uid +'" type="file" style="font-size:999px;opacity:0;"' + (_options.multiple && I.can('select_multiple') ? 'multiple' : '') + (_options.directory && I.can('select_folder') ? 'webkitdirectory directory' : '') + // Chrome 11+ (mimes ? ' accept="' + mimes.join(',') + '"' : '') + ' />'; input = Dom.get(I.uid); // prepare file input to be placed underneath the browse_button element Basic.extend(input.style, { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }); browseButton = Dom.get(_options.browse_button); // Route click event to the input[type=file] element for browsers that support such behavior if (I.can('summon_file_dialog')) { if (Dom.getStyle(browseButton, 'position') === 'static') { browseButton.style.position = 'relative'; } zIndex = parseInt(Dom.getStyle(browseButton, 'z-index'), 10) || 1; browseButton.style.zIndex = zIndex; shimContainer.style.zIndex = zIndex - 1; Events.addEvent(browseButton, 'click', function(e) { var input = Dom.get(I.uid); if (input && !input.disabled) { // for some reason FF (up to 8.0.1 so far) lets to click disabled input[type=file] input.click(); } e.preventDefault(); }, comp.uid); } /* Since we have to place input[type=file] on top of the browse_button for some browsers, browse_button loses interactivity, so we restore it here */ top = I.can('summon_file_dialog') ? browseButton : shimContainer; Events.addEvent(top, 'mouseover', function() { comp.trigger('mouseenter'); }, comp.uid); Events.addEvent(top, 'mouseout', function() { comp.trigger('mouseleave'); }, comp.uid); Events.addEvent(top, 'mousedown', function() { comp.trigger('mousedown'); }, comp.uid); Events.addEvent(Dom.get(_options.container), 'mouseup', function() { comp.trigger('mouseup'); }, comp.uid); input.onchange = function onChange() { // there should be only one handler for this _files = []; if (_options.directory) { // folders are represented by dots, filter them out (Chrome 11+) Basic.each(this.files, function(file) { if (file.name !== ".") { // if it doesn't looks like a folder _files.push(file); } }); } else { _files = [].slice.call(this.files); } // clearing the value enables the user to select the same file again if they want to if (Env.browser !== 'IE') { this.value = ''; } else { // in IE input[type="file"] is read-only so the only way to reset it is to re-insert it var clone = this.cloneNode(true); this.parentNode.replaceChild(clone, this); clone.onchange = onChange; } comp.trigger('change'); }; // ready event is perfectly asynchronous comp.trigger({ type: 'ready', async: true }); shimContainer = null; }, getFiles: function() { return _files; }, disable: function(state) { var I = this.getRuntime(), input; if ((input = Dom.get(I.uid))) { input.disabled = !!state; } }, destroy: function() { var I = this.getRuntime(), shimContainer = I.getShimContainer(); Events.removeAllEvents(shimContainer, this.uid); Events.removeAllEvents(_options && Dom.get(_options.container), this.uid); Events.removeAllEvents(_options && Dom.get(_options.browse_button), this.uid); if (shimContainer) { shimContainer.innerHTML = ''; } _files = _options = null; } }); } return (extensions.FileInput = FileInput); }); // Included from: src/javascript/runtime/html5/file/FileDrop.js /** * FileDrop.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/file/FileDrop @private */ define("moxie/runtime/html5/file/FileDrop", [ "moxie/runtime/html5/Runtime", "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/utils/Events", "moxie/core/utils/Mime" ], function(extensions, Basic, Dom, Events, Mime) { function FileDrop() { var _files = [], _allowedExts = [], _options; Basic.extend(this, { init: function(options) { var comp = this, dropZone; _options = options; _allowedExts = _extractExts(_options.accept); dropZone = _options.container; Events.addEvent(dropZone, 'dragover', function(e) { e.preventDefault(); e.stopPropagation(); e.dataTransfer.dropEffect = 'copy'; }, comp.uid); Events.addEvent(dropZone, 'drop', function(e) { e.preventDefault(); e.stopPropagation(); _files = []; // Chrome 21+ accepts folders via Drag'n'Drop if (e.dataTransfer.items && e.dataTransfer.items[0].webkitGetAsEntry) { var entries = []; Basic.each(e.dataTransfer.items, function(item) { entries.push(item.webkitGetAsEntry()); }); _readEntries(entries, function() { comp.trigger("drop"); }); } else { Basic.each(e.dataTransfer.files, function(file) { if (_isAcceptable(file)) { _files.push(file); } }); comp.trigger("drop"); } }, comp.uid); Events.addEvent(dropZone, 'dragenter', function(e) { e.preventDefault(); e.stopPropagation(); comp.trigger("dragenter"); }, comp.uid); Events.addEvent(dropZone, 'dragleave', function(e) { e.preventDefault(); e.stopPropagation(); comp.trigger("dragleave"); }, comp.uid); }, getFiles: function() { return _files; }, destroy: function() { Events.removeAllEvents(_options && Dom.get(_options.container), this.uid); _files = _allowedExts = _options = null; } }); function _extractExts(accept) { var exts = []; for (var i = 0; i < accept.length; i++) { [].push.apply(exts, accept[i].extensions.split(/\s*,\s*/)); } return Basic.inArray('*', exts) === -1 ? exts : []; } function _isAcceptable(file) { var ext = Mime.getFileExtension(file.name); return !ext || !_allowedExts.length || Basic.inArray(ext, _allowedExts) !== -1; } function _readEntries(entries, cb) { var queue = []; Basic.each(entries, function(entry) { queue.push(function(cbcb) { _readEntry(entry, cbcb); }); }); Basic.inSeries(queue, function() { cb(); }); } function _readEntry(entry, cb) { if (entry.isFile) { entry.file(function(file) { if (_isAcceptable(file)) { _files.push(file); } cb(); }, function() { // fire an error event maybe cb(); }); } else if (entry.isDirectory) { _readDirEntry(entry, cb); } else { cb(); // not file, not directory? what then?.. } } function _readDirEntry(dirEntry, cb) { var entries = [], dirReader = dirEntry.createReader(); // keep quering recursively till no more entries function getEntries(cbcb) { dirReader.readEntries(function(moreEntries) { if (moreEntries.length) { [].push.apply(entries, moreEntries); getEntries(cbcb); } else { cbcb(); } }, cbcb); } // ...and you thought FileReader was crazy... getEntries(function() { _readEntries(entries, cb); }); } } return (extensions.FileDrop = FileDrop); }); // Included from: src/javascript/runtime/html5/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/file/FileReader @private */ define("moxie/runtime/html5/file/FileReader", [ "moxie/runtime/html5/Runtime", "moxie/core/utils/Encode", "moxie/core/utils/Basic" ], function(extensions, Encode, Basic) { function FileReader() { var _fr, _convertToBinary = false; Basic.extend(this, { read: function(op, blob) { var target = this; _fr = new window.FileReader(); _fr.addEventListener('progress', function(e) { target.trigger(e); }); _fr.addEventListener('load', function(e) { target.trigger(e); }); _fr.addEventListener('error', function(e) { target.trigger(e, _fr.error); }); _fr.addEventListener('loadend', function() { _fr = null; }); if (Basic.typeOf(_fr[op]) === 'function') { _convertToBinary = false; _fr[op](blob.getSource()); } else if (op === 'readAsBinaryString') { // readAsBinaryString is depricated in general and never existed in IE10+ _convertToBinary = true; _fr.readAsDataURL(blob.getSource()); } }, getResult: function() { return _fr && _fr.result ? (_convertToBinary ? _toBinary(_fr.result) : _fr.result) : null; }, abort: function() { if (_fr) { _fr.abort(); } }, destroy: function() { _fr = null; } }); function _toBinary(str) { return Encode.atob(str.substring(str.indexOf('base64,') + 7)); } } return (extensions.FileReader = FileReader); }); // Included from: src/javascript/runtime/html5/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global ActiveXObject:true */ /** @class moxie/runtime/html5/xhr/XMLHttpRequest @private */ define("moxie/runtime/html5/xhr/XMLHttpRequest", [ "moxie/runtime/html5/Runtime", "moxie/core/utils/Basic", "moxie/core/utils/Mime", "moxie/core/utils/Url", "moxie/file/File", "moxie/file/Blob", "moxie/xhr/FormData", "moxie/core/Exceptions", "moxie/core/utils/Env", "moxie/core/JSON" ], function(extensions, Basic, Mime, Url, File, Blob, FormData, x, Env, parseJSON) { function XMLHttpRequest() { var _xhr , _filename ; Basic.extend(this, { send: function(meta, data) { var target = this , isGecko2_5_6 = (Env.browser === 'Mozilla' && Env.version >= 4 && Env.version < 7) , isAndroidBrowser = Env.browser === 'Android Browser' , mustSendAsBinary = false ; // extract file name _filename = meta.url.replace(/^.+?\/([\w\-\.]+)$/, '$1').toLowerCase(); _xhr = _getNativeXHR(); _xhr.open(meta.method, meta.url, meta.async, meta.user, meta.password); // prepare data to be sent if (data instanceof Blob) { if (data.isDetached()) { mustSendAsBinary = true; } data = data.getSource(); } else if (data instanceof FormData) { if (data.hasBlob()) { if (data.getBlob().isDetached()) { data = _prepareMultipart.call(target, data); // _xhr must be instantiated and be in OPENED state mustSendAsBinary = true; } else if ((isGecko2_5_6 || isAndroidBrowser) && Basic.typeOf(data.getBlob().getSource()) === 'blob' && window.FileReader) { // Gecko 2/5/6 can't send blob in FormData: https://bugzilla.mozilla.org/show_bug.cgi?id=649150 // Android browsers (default one and Dolphin) seem to have the same issue, see: #613 _preloadAndSend.call(target, meta, data); return; // _preloadAndSend will reinvoke send() with transmutated FormData =%D } } // transfer fields to real FormData if (data instanceof FormData) { // if still a FormData, e.g. not mangled by _prepareMultipart() var fd = new window.FormData(); data.each(function(value, name) { if (value instanceof Blob) { fd.append(name, value.getSource()); } else { fd.append(name, value); } }); data = fd; } } // if XHR L2 if (_xhr.upload) { if (meta.withCredentials) { _xhr.withCredentials = true; } _xhr.addEventListener('load', function(e) { target.trigger(e); }); _xhr.addEventListener('error', function(e) { target.trigger(e); }); // additionally listen to progress events _xhr.addEventListener('progress', function(e) { target.trigger(e); }); _xhr.upload.addEventListener('progress', function(e) { target.trigger({ type: 'UploadProgress', loaded: e.loaded, total: e.total }); }); // ... otherwise simulate XHR L2 } else { _xhr.onreadystatechange = function onReadyStateChange() { // fake Level 2 events switch (_xhr.readyState) { case 1: // XMLHttpRequest.OPENED // readystatechanged is fired twice for OPENED state (in IE and Mozilla) - neu break; // looks like HEADERS_RECEIVED (state 2) is not reported in Opera (or it's old versions) - neu case 2: // XMLHttpRequest.HEADERS_RECEIVED break; case 3: // XMLHttpRequest.LOADING // try to fire progress event for not XHR L2 var total, loaded; try { if (Url.hasSameOrigin(meta.url)) { // Content-Length not accessible for cross-domain on some browsers total = _xhr.getResponseHeader('Content-Length') || 0; // old Safari throws an exception here } if (_xhr.responseText) { // responseText was introduced in IE7 loaded = _xhr.responseText.length; } } catch(ex) { total = loaded = 0; } target.trigger({ type: 'progress', lengthComputable: !!total, total: parseInt(total, 10), loaded: loaded }); break; case 4: // XMLHttpRequest.DONE // release readystatechange handler (mostly for IE) _xhr.onreadystatechange = function() {}; // usually status 0 is returned when server is unreachable, but FF also fails to status 0 for 408 timeout if (_xhr.status === 0) { target.trigger('error'); } else { target.trigger('load'); } break; } }; } // set request headers if (!Basic.isEmptyObj(meta.headers)) { Basic.each(meta.headers, function(value, header) { _xhr.setRequestHeader(header, value); }); } // request response type if ("" !== meta.responseType && 'responseType' in _xhr) { if ('json' === meta.responseType && !Env.can('return_response_type', 'json')) { // we can fake this one _xhr.responseType = 'text'; } else { _xhr.responseType = meta.responseType; } } // send ... if (!mustSendAsBinary) { _xhr.send(data); } else { if (_xhr.sendAsBinary) { // Gecko _xhr.sendAsBinary(data); } else { // other browsers having support for typed arrays (function() { // mimic Gecko's sendAsBinary var ui8a = new Uint8Array(data.length); for (var i = 0; i < data.length; i++) { ui8a[i] = (data.charCodeAt(i) & 0xff); } _xhr.send(ui8a.buffer); }()); } } target.trigger('loadstart'); }, getStatus: function() { // according to W3C spec it should return 0 for readyState < 3, but instead it throws an exception try { if (_xhr) { return _xhr.status; } } catch(ex) {} return 0; }, getResponse: function(responseType) { var I = this.getRuntime(); try { switch (responseType) { case 'blob': var file = new File(I.uid, _xhr.response); // try to extract file name from content-disposition if possible (might be - not, if CORS for example) var disposition = _xhr.getResponseHeader('Content-Disposition'); if (disposition) { // extract filename from response header if available var match = disposition.match(/filename=([\'\"'])([^\1]+)\1/); if (match) { _filename = match[2]; } } file.name = _filename; // pre-webkit Opera doesn't set type property on the blob response if (!file.type) { file.type = Mime.getFileMime(_filename); } return file; case 'json': if (!Env.can('return_response_type', 'json')) { return _xhr.status === 200 ? parseJSON(_xhr.responseText) : null; } return _xhr.response; case 'document': return _getDocument(_xhr); default: return _xhr.responseText !== '' ? _xhr.responseText : null; // against the specs, but for consistency across the runtimes } } catch(ex) { return null; } }, getAllResponseHeaders: function() { try { return _xhr.getAllResponseHeaders(); } catch(ex) {} return ''; }, abort: function() { if (_xhr) { _xhr.abort(); } }, destroy: function() { self = _filename = null; } }); // here we go... ugly fix for ugly bug function _preloadAndSend(meta, data) { var target = this, blob, fr; // get original blob blob = data.getBlob().getSource(); // preload blob in memory to be sent as binary string fr = new window.FileReader(); fr.onload = function() { // overwrite original blob data.append(data.getBlobName(), new Blob(null, { type: blob.type, data: fr.result })); // invoke send operation again self.send.call(target, meta, data); }; fr.readAsBinaryString(blob); } function _getNativeXHR() { if (window.XMLHttpRequest && !(Env.browser === 'IE' && Env.version < 8)) { // IE7 has native XHR but it's buggy return new window.XMLHttpRequest(); } else { return (function() { var progIDs = ['Msxml2.XMLHTTP.6.0', 'Microsoft.XMLHTTP']; // if 6.0 available, use it, otherwise failback to default 3.0 for (var i = 0; i < progIDs.length; i++) { try { return new ActiveXObject(progIDs[i]); } catch (ex) {} } })(); } } // @credits Sergey Ilinsky (http://www.ilinsky.com/) function _getDocument(xhr) { var rXML = xhr.responseXML; var rText = xhr.responseText; // Try parsing responseText (@see: http://www.ilinsky.com/articles/XMLHttpRequest/#bugs-ie-responseXML-content-type) if (Env.browser === 'IE' && rText && rXML && !rXML.documentElement && /[^\/]+\/[^\+]+\+xml/.test(xhr.getResponseHeader("Content-Type"))) { rXML = new window.ActiveXObject("Microsoft.XMLDOM"); rXML.async = false; rXML.validateOnParse = false; rXML.loadXML(rText); } // Check if there is no error in document if (rXML) { if ((Env.browser === 'IE' && rXML.parseError !== 0) || !rXML.documentElement || rXML.documentElement.tagName === "parsererror") { return null; } } return rXML; } function _prepareMultipart(fd) { var boundary = '----moxieboundary' + new Date().getTime() , dashdash = '--' , crlf = '\r\n' , multipart = '' , I = this.getRuntime() ; if (!I.can('send_binary_string')) { throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR); } _xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary); // append multipart parameters fd.each(function(value, name) { // Firefox 3.6 failed to convert multibyte characters to UTF-8 in sendAsBinary(), // so we try it here ourselves with: unescape(encodeURIComponent(value)) if (value instanceof Blob) { // Build RFC2388 blob multipart += dashdash + boundary + crlf + 'Content-Disposition: form-data; name="' + name + '"; filename="' + unescape(encodeURIComponent(value.name || 'blob')) + '"' + crlf + 'Content-Type: ' + value.type + crlf + crlf + value.getSource() + crlf; } else { multipart += dashdash + boundary + crlf + 'Content-Disposition: form-data; name="' + name + '"' + crlf + crlf + unescape(encodeURIComponent(value)) + crlf; } }); multipart += dashdash + boundary + dashdash + crlf; return multipart; } } return (extensions.XMLHttpRequest = XMLHttpRequest); }); // Included from: src/javascript/runtime/html5/utils/BinaryReader.js /** * BinaryReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/utils/BinaryReader @private */ define("moxie/runtime/html5/utils/BinaryReader", [], function() { return function() { var II = false, bin; // Private functions function read(idx, size) { var mv = II ? 0 : -8 * (size - 1), sum = 0, i; for (i = 0; i < size; i++) { sum |= (bin.charCodeAt(idx + i) << Math.abs(mv + i*8)); } return sum; } function putstr(segment, idx, length) { length = arguments.length === 3 ? length : bin.length - idx - 1; bin = bin.substr(0, idx) + segment + bin.substr(length + idx); } function write(idx, num, size) { var str = '', mv = II ? 0 : -8 * (size - 1), i; for (i = 0; i < size; i++) { str += String.fromCharCode((num >> Math.abs(mv + i*8)) & 255); } putstr(str, idx, size); } // Public functions return { II: function(order) { if (order === undefined) { return II; } else { II = order; } }, init: function(binData) { II = false; bin = binData; }, SEGMENT: function(idx, length, segment) { switch (arguments.length) { case 1: return bin.substr(idx, bin.length - idx - 1); case 2: return bin.substr(idx, length); case 3: putstr(segment, idx, length); break; default: return bin; } }, BYTE: function(idx) { return read(idx, 1); }, SHORT: function(idx) { return read(idx, 2); }, LONG: function(idx, num) { if (num === undefined) { return read(idx, 4); } else { write(idx, num, 4); } }, SLONG: function(idx) { // 2's complement notation var num = read(idx, 4); return (num > 2147483647 ? num - 4294967296 : num); }, STRING: function(idx, size) { var str = ''; for (size += idx; idx < size; idx++) { str += String.fromCharCode(read(idx, 1)); } return str; } }; }; }); // Included from: src/javascript/runtime/html5/image/JPEGHeaders.js /** * JPEGHeaders.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/JPEGHeaders @private */ define("moxie/runtime/html5/image/JPEGHeaders", [ "moxie/runtime/html5/utils/BinaryReader" ], function(BinaryReader) { return function JPEGHeaders(data) { var headers = [], read, idx, marker, length = 0; read = new BinaryReader(); read.init(data); // Check if data is jpeg if (read.SHORT(0) !== 0xFFD8) { return; } idx = 2; while (idx <= data.length) { marker = read.SHORT(idx); // omit RST (restart) markers if (marker >= 0xFFD0 && marker <= 0xFFD7) { idx += 2; continue; } // no headers allowed after SOS marker if (marker === 0xFFDA || marker === 0xFFD9) { break; } length = read.SHORT(idx + 2) + 2; // APPn marker detected if (marker >= 0xFFE1 && marker <= 0xFFEF) { headers.push({ hex: marker, name: 'APP' + (marker & 0x000F), start: idx, length: length, segment: read.SEGMENT(idx, length) }); } idx += length; } read.init(null); // free memory return { headers: headers, restore: function(data) { var max, i; read.init(data); idx = read.SHORT(2) == 0xFFE0 ? 4 + read.SHORT(4) : 2; for (i = 0, max = headers.length; i < max; i++) { read.SEGMENT(idx, 0, headers[i].segment); idx += headers[i].length; } data = read.SEGMENT(); read.init(null); return data; }, strip: function(data) { var headers, jpegHeaders, i; jpegHeaders = new JPEGHeaders(data); headers = jpegHeaders.headers; jpegHeaders.purge(); read.init(data); i = headers.length; while (i--) { read.SEGMENT(headers[i].start, headers[i].length, ''); } data = read.SEGMENT(); read.init(null); return data; }, get: function(name) { var array = []; for (var i = 0, max = headers.length; i < max; i++) { if (headers[i].name === name.toUpperCase()) { array.push(headers[i].segment); } } return array; }, set: function(name, segment) { var array = [], i, ii, max; if (typeof(segment) === 'string') { array.push(segment); } else { array = segment; } for (i = ii = 0, max = headers.length; i < max; i++) { if (headers[i].name === name.toUpperCase()) { headers[i].segment = array[ii]; headers[i].length = array[ii].length; ii++; } if (ii >= array.length) { break; } } }, purge: function() { headers = []; read.init(null); read = null; } }; }; }); // Included from: src/javascript/runtime/html5/image/ExifParser.js /** * ExifParser.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/ExifParser @private */ define("moxie/runtime/html5/image/ExifParser", [ "moxie/core/utils/Basic", "moxie/runtime/html5/utils/BinaryReader" ], function(Basic, BinaryReader) { return function ExifParser() { // Private ExifParser fields var data, tags, Tiff, offsets = {}, tagDescs; data = new BinaryReader(); tags = { tiff : { /* The image orientation viewed in terms of rows and columns. 1 = The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side. 2 = The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side. 3 = The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side. 4 = The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side. 5 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual top. 6 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual top. 7 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom. 8 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom. */ 0x0112: 'Orientation', 0x010E: 'ImageDescription', 0x010F: 'Make', 0x0110: 'Model', 0x0131: 'Software', 0x8769: 'ExifIFDPointer', 0x8825: 'GPSInfoIFDPointer' }, exif : { 0x9000: 'ExifVersion', 0xA001: 'ColorSpace', 0xA002: 'PixelXDimension', 0xA003: 'PixelYDimension', 0x9003: 'DateTimeOriginal', 0x829A: 'ExposureTime', 0x829D: 'FNumber', 0x8827: 'ISOSpeedRatings', 0x9201: 'ShutterSpeedValue', 0x9202: 'ApertureValue' , 0x9207: 'MeteringMode', 0x9208: 'LightSource', 0x9209: 'Flash', 0x920A: 'FocalLength', 0xA402: 'ExposureMode', 0xA403: 'WhiteBalance', 0xA406: 'SceneCaptureType', 0xA404: 'DigitalZoomRatio', 0xA408: 'Contrast', 0xA409: 'Saturation', 0xA40A: 'Sharpness' }, gps : { 0x0000: 'GPSVersionID', 0x0001: 'GPSLatitudeRef', 0x0002: 'GPSLatitude', 0x0003: 'GPSLongitudeRef', 0x0004: 'GPSLongitude' } }; tagDescs = { 'ColorSpace': { 1: 'sRGB', 0: 'Uncalibrated' }, 'MeteringMode': { 0: 'Unknown', 1: 'Average', 2: 'CenterWeightedAverage', 3: 'Spot', 4: 'MultiSpot', 5: 'Pattern', 6: 'Partial', 255: 'Other' }, 'LightSource': { 1: 'Daylight', 2: 'Fliorescent', 3: 'Tungsten', 4: 'Flash', 9: 'Fine weather', 10: 'Cloudy weather', 11: 'Shade', 12: 'Daylight fluorescent (D 5700 - 7100K)', 13: 'Day white fluorescent (N 4600 -5400K)', 14: 'Cool white fluorescent (W 3900 - 4500K)', 15: 'White fluorescent (WW 3200 - 3700K)', 17: 'Standard light A', 18: 'Standard light B', 19: 'Standard light C', 20: 'D55', 21: 'D65', 22: 'D75', 23: 'D50', 24: 'ISO studio tungsten', 255: 'Other' }, 'Flash': { 0x0000: 'Flash did not fire.', 0x0001: 'Flash fired.', 0x0005: 'Strobe return light not detected.', 0x0007: 'Strobe return light detected.', 0x0009: 'Flash fired, compulsory flash mode', 0x000D: 'Flash fired, compulsory flash mode, return light not detected', 0x000F: 'Flash fired, compulsory flash mode, return light detected', 0x0010: 'Flash did not fire, compulsory flash mode', 0x0018: 'Flash did not fire, auto mode', 0x0019: 'Flash fired, auto mode', 0x001D: 'Flash fired, auto mode, return light not detected', 0x001F: 'Flash fired, auto mode, return light detected', 0x0020: 'No flash function', 0x0041: 'Flash fired, red-eye reduction mode', 0x0045: 'Flash fired, red-eye reduction mode, return light not detected', 0x0047: 'Flash fired, red-eye reduction mode, return light detected', 0x0049: 'Flash fired, compulsory flash mode, red-eye reduction mode', 0x004D: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected', 0x004F: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light detected', 0x0059: 'Flash fired, auto mode, red-eye reduction mode', 0x005D: 'Flash fired, auto mode, return light not detected, red-eye reduction mode', 0x005F: 'Flash fired, auto mode, return light detected, red-eye reduction mode' }, 'ExposureMode': { 0: 'Auto exposure', 1: 'Manual exposure', 2: 'Auto bracket' }, 'WhiteBalance': { 0: 'Auto white balance', 1: 'Manual white balance' }, 'SceneCaptureType': { 0: 'Standard', 1: 'Landscape', 2: 'Portrait', 3: 'Night scene' }, 'Contrast': { 0: 'Normal', 1: 'Soft', 2: 'Hard' }, 'Saturation': { 0: 'Normal', 1: 'Low saturation', 2: 'High saturation' }, 'Sharpness': { 0: 'Normal', 1: 'Soft', 2: 'Hard' }, // GPS related 'GPSLatitudeRef': { N: 'North latitude', S: 'South latitude' }, 'GPSLongitudeRef': { E: 'East longitude', W: 'West longitude' } }; function extractTags(IFD_offset, tags2extract) { var length = data.SHORT(IFD_offset), i, ii, tag, type, count, tagOffset, offset, value, values = [], hash = {}; for (i = 0; i < length; i++) { // Set binary reader pointer to beginning of the next tag offset = tagOffset = IFD_offset + 12 * i + 2; tag = tags2extract[data.SHORT(offset)]; if (tag === undefined) { continue; // Not the tag we requested } type = data.SHORT(offset+=2); count = data.LONG(offset+=2); offset += 4; values = []; switch (type) { case 1: // BYTE case 7: // UNDEFINED if (count > 4) { offset = data.LONG(offset) + offsets.tiffHeader; } for (ii = 0; ii < count; ii++) { values[ii] = data.BYTE(offset + ii); } break; case 2: // STRING if (count > 4) { offset = data.LONG(offset) + offsets.tiffHeader; } hash[tag] = data.STRING(offset, count - 1); continue; case 3: // SHORT if (count > 2) { offset = data.LONG(offset) + offsets.tiffHeader; } for (ii = 0; ii < count; ii++) { values[ii] = data.SHORT(offset + ii*2); } break; case 4: // LONG if (count > 1) { offset = data.LONG(offset) + offsets.tiffHeader; } for (ii = 0; ii < count; ii++) { values[ii] = data.LONG(offset + ii*4); } break; case 5: // RATIONAL offset = data.LONG(offset) + offsets.tiffHeader; for (ii = 0; ii < count; ii++) { values[ii] = data.LONG(offset + ii*4) / data.LONG(offset + ii*4 + 4); } break; case 9: // SLONG offset = data.LONG(offset) + offsets.tiffHeader; for (ii = 0; ii < count; ii++) { values[ii] = data.SLONG(offset + ii*4); } break; case 10: // SRATIONAL offset = data.LONG(offset) + offsets.tiffHeader; for (ii = 0; ii < count; ii++) { values[ii] = data.SLONG(offset + ii*4) / data.SLONG(offset + ii*4 + 4); } break; default: continue; } value = (count == 1 ? values[0] : values); if (tagDescs.hasOwnProperty(tag) && typeof value != 'object') { hash[tag] = tagDescs[tag][value]; } else { hash[tag] = value; } } return hash; } function getIFDOffsets() { var idx = offsets.tiffHeader; // Set read order of multi-byte data data.II(data.SHORT(idx) == 0x4949); // Check if always present bytes are indeed present if (data.SHORT(idx+=2) !== 0x002A) { return false; } offsets.IFD0 = offsets.tiffHeader + data.LONG(idx += 2); Tiff = extractTags(offsets.IFD0, tags.tiff); if ('ExifIFDPointer' in Tiff) { offsets.exifIFD = offsets.tiffHeader + Tiff.ExifIFDPointer; delete Tiff.ExifIFDPointer; } if ('GPSInfoIFDPointer' in Tiff) { offsets.gpsIFD = offsets.tiffHeader + Tiff.GPSInfoIFDPointer; delete Tiff.GPSInfoIFDPointer; } return true; } // At the moment only setting of simple (LONG) values, that do not require offset recalculation, is supported function setTag(ifd, tag, value) { var offset, length, tagOffset, valueOffset = 0; // If tag name passed translate into hex key if (typeof(tag) === 'string') { var tmpTags = tags[ifd.toLowerCase()]; for (var hex in tmpTags) { if (tmpTags[hex] === tag) { tag = hex; break; } } } offset = offsets[ifd.toLowerCase() + 'IFD']; length = data.SHORT(offset); for (var i = 0; i < length; i++) { tagOffset = offset + 12 * i + 2; if (data.SHORT(tagOffset) == tag) { valueOffset = tagOffset + 8; break; } } if (!valueOffset) { return false; } data.LONG(valueOffset, value); return true; } // Public functions return { init: function(segment) { // Reset internal data offsets = { tiffHeader: 10 }; if (segment === undefined || !segment.length) { return false; } data.init(segment); // Check if that's APP1 and that it has EXIF if (data.SHORT(0) === 0xFFE1 && data.STRING(4, 5).toUpperCase() === "EXIF\0") { return getIFDOffsets(); } return false; }, TIFF: function() { return Tiff; }, EXIF: function() { var Exif; // Populate EXIF hash Exif = extractTags(offsets.exifIFD, tags.exif); // Fix formatting of some tags if (Exif.ExifVersion && Basic.typeOf(Exif.ExifVersion) === 'array') { for (var i = 0, exifVersion = ''; i < Exif.ExifVersion.length; i++) { exifVersion += String.fromCharCode(Exif.ExifVersion[i]); } Exif.ExifVersion = exifVersion; } return Exif; }, GPS: function() { var GPS; GPS = extractTags(offsets.gpsIFD, tags.gps); // iOS devices (and probably some others) do not put in GPSVersionID tag (why?..) if (GPS.GPSVersionID && Basic.typeOf(GPS.GPSVersionID) === 'array') { GPS.GPSVersionID = GPS.GPSVersionID.join('.'); } return GPS; }, setExif: function(tag, value) { // Right now only setting of width/height is possible if (tag !== 'PixelXDimension' && tag !== 'PixelYDimension') {return false;} return setTag('exif', tag, value); }, getBinary: function() { return data.SEGMENT(); }, purge: function() { data.init(null); data = Tiff = null; offsets = {}; } }; }; }); // Included from: src/javascript/runtime/html5/image/JPEG.js /** * JPEG.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/JPEG @private */ define("moxie/runtime/html5/image/JPEG", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/runtime/html5/image/JPEGHeaders", "moxie/runtime/html5/utils/BinaryReader", "moxie/runtime/html5/image/ExifParser" ], function(Basic, x, JPEGHeaders, BinaryReader, ExifParser) { function JPEG(binstr) { var _binstr, _br, _hm, _ep, _info, hasExif; function _getDimensions() { var idx = 0, marker, length; // examine all through the end, since some images might have very large APP segments while (idx <= _binstr.length) { marker = _br.SHORT(idx += 2); if (marker >= 0xFFC0 && marker <= 0xFFC3) { // SOFn idx += 5; // marker (2 bytes) + length (2 bytes) + Sample precision (1 byte) return { height: _br.SHORT(idx), width: _br.SHORT(idx += 2) }; } length = _br.SHORT(idx += 2); idx += length - 2; } return null; } _binstr = binstr; _br = new BinaryReader(); _br.init(_binstr); // check if it is jpeg if (_br.SHORT(0) !== 0xFFD8) { throw new x.ImageError(x.ImageError.WRONG_FORMAT); } // backup headers _hm = new JPEGHeaders(binstr); // extract exif info _ep = new ExifParser(); hasExif = !!_ep.init(_hm.get('app1')[0]); // get dimensions _info = _getDimensions.call(this); Basic.extend(this, { type: 'image/jpeg', size: _binstr.length, width: _info && _info.width || 0, height: _info && _info.height || 0, setExif: function(tag, value) { if (!hasExif) { return false; // or throw an exception } if (Basic.typeOf(tag) === 'object') { Basic.each(tag, function(value, tag) { _ep.setExif(tag, value); }); } else { _ep.setExif(tag, value); } // update internal headers _hm.set('app1', _ep.getBinary()); }, writeHeaders: function() { if (!arguments.length) { // if no arguments passed, update headers internally return (_binstr = _hm.restore(_binstr)); } return _hm.restore(arguments[0]); }, stripHeaders: function(binstr) { return _hm.strip(binstr); }, purge: function() { _purge.call(this); } }); if (hasExif) { this.meta = { tiff: _ep.TIFF(), exif: _ep.EXIF(), gps: _ep.GPS() }; } function _purge() { if (!_ep || !_hm || !_br) { return; // ignore any repeating purge requests } _ep.purge(); _hm.purge(); _br.init(null); _binstr = _info = _hm = _ep = _br = null; } } return JPEG; }); // Included from: src/javascript/runtime/html5/image/PNG.js /** * PNG.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/PNG @private */ define("moxie/runtime/html5/image/PNG", [ "moxie/core/Exceptions", "moxie/core/utils/Basic", "moxie/runtime/html5/utils/BinaryReader" ], function(x, Basic, BinaryReader) { function PNG(binstr) { var _binstr, _br, _hm, _ep, _info; _binstr = binstr; _br = new BinaryReader(); _br.init(_binstr); // check if it's png (function() { var idx = 0, i = 0 , signature = [0x8950, 0x4E47, 0x0D0A, 0x1A0A] ; for (i = 0; i < signature.length; i++, idx += 2) { if (signature[i] != _br.SHORT(idx)) { throw new x.ImageError(x.ImageError.WRONG_FORMAT); } } }()); function _getDimensions() { var chunk, idx; chunk = _getChunkAt.call(this, 8); if (chunk.type == 'IHDR') { idx = chunk.start; return { width: _br.LONG(idx), height: _br.LONG(idx += 4) }; } return null; } function _purge() { if (!_br) { return; // ignore any repeating purge requests } _br.init(null); _binstr = _info = _hm = _ep = _br = null; } _info = _getDimensions.call(this); Basic.extend(this, { type: 'image/png', size: _binstr.length, width: _info.width, height: _info.height, purge: function() { _purge.call(this); } }); // for PNG we can safely trigger purge automatically, as we do not keep any data for later _purge.call(this); function _getChunkAt(idx) { var length, type, start, CRC; length = _br.LONG(idx); type = _br.STRING(idx += 4, 4); start = idx += 4; CRC = _br.LONG(idx + length); return { length: length, type: type, start: start, CRC: CRC }; } } return PNG; }); // Included from: src/javascript/runtime/html5/image/ImageInfo.js /** * ImageInfo.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/ImageInfo @private */ define("moxie/runtime/html5/image/ImageInfo", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/runtime/html5/image/JPEG", "moxie/runtime/html5/image/PNG" ], function(Basic, x, JPEG, PNG) { /** Optional image investigation tool for HTML5 runtime. Provides the following features: - ability to distinguish image type (JPEG or PNG) by signature - ability to extract image width/height directly from it's internals, without preloading in memory (fast) - ability to extract APP headers from JPEGs (Exif, GPS, etc) - ability to replace width/height tags in extracted JPEG headers - ability to restore APP headers, that were for example stripped during image manipulation @class ImageInfo @constructor @param {String} binstr Image source as binary string */ return function(binstr) { var _cs = [JPEG, PNG], _img; // figure out the format, throw: ImageError.WRONG_FORMAT if not supported _img = (function() { for (var i = 0; i < _cs.length; i++) { try { return new _cs[i](binstr); } catch (ex) { // //console.info(ex); } } throw new x.ImageError(x.ImageError.WRONG_FORMAT); }()); Basic.extend(this, { /** Image Mime Type extracted from it's depths @property type @type {String} @default '' */ type: '', /** Image size in bytes @property size @type {Number} @default 0 */ size: 0, /** Image width extracted from image source @property width @type {Number} @default 0 */ width: 0, /** Image height extracted from image source @property height @type {Number} @default 0 */ height: 0, /** Sets Exif tag. Currently applicable only for width and height tags. Obviously works only with JPEGs. @method setExif @param {String} tag Tag to set @param {Mixed} value Value to assign to the tag */ setExif: function() {}, /** Restores headers to the source. @method writeHeaders @param {String} data Image source as binary string @return {String} Updated binary string */ writeHeaders: function(data) { return data; }, /** Strip all headers from the source. @method stripHeaders @param {String} data Image source as binary string @return {String} Updated binary string */ stripHeaders: function(data) { return data; }, /** Dispose resources. @method purge */ purge: function() {} }); Basic.extend(this, _img); this.purge = function() { _img.purge(); _img = null; }; }; }); // Included from: src/javascript/runtime/html5/image/MegaPixel.js /** (The MIT License) Copyright (c) 2012 Shinichi Tomita <[email protected]>; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * Mega pixel image rendering library for iOS6 Safari * * Fixes iOS6 Safari's image file rendering issue for large size image (over mega-pixel), * which causes unexpected subsampling when drawing it in canvas. * By using this library, you can safely render the image with proper stretching. * * Copyright (c) 2012 Shinichi Tomita <[email protected]> * Released under the MIT license */ /** @class moxie/runtime/html5/image/MegaPixel @private */ define("moxie/runtime/html5/image/MegaPixel", [], function() { /** * Rendering image element (with resizing) into the canvas element */ function renderImageToCanvas(img, canvas, options) { var iw = img.naturalWidth, ih = img.naturalHeight; var width = options.width, height = options.height; var x = options.x || 0, y = options.y || 0; var ctx = canvas.getContext('2d'); if (detectSubsampling(img)) { iw /= 2; ih /= 2; } var d = 1024; // size of tiling canvas var tmpCanvas = document.createElement('canvas'); tmpCanvas.width = tmpCanvas.height = d; var tmpCtx = tmpCanvas.getContext('2d'); var vertSquashRatio = detectVerticalSquash(img, iw, ih); var sy = 0; while (sy < ih) { var sh = sy + d > ih ? ih - sy : d; var sx = 0; while (sx < iw) { var sw = sx + d > iw ? iw - sx : d; tmpCtx.clearRect(0, 0, d, d); tmpCtx.drawImage(img, -sx, -sy); var dx = (sx * width / iw + x) << 0; var dw = Math.ceil(sw * width / iw); var dy = (sy * height / ih / vertSquashRatio + y) << 0; var dh = Math.ceil(sh * height / ih / vertSquashRatio); ctx.drawImage(tmpCanvas, 0, 0, sw, sh, dx, dy, dw, dh); sx += d; } sy += d; } tmpCanvas = tmpCtx = null; } /** * Detect subsampling in loaded image. * In iOS, larger images than 2M pixels may be subsampled in rendering. */ function detectSubsampling(img) { var iw = img.naturalWidth, ih = img.naturalHeight; if (iw * ih > 1024 * 1024) { // subsampling may happen over megapixel image var canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; var ctx = canvas.getContext('2d'); ctx.drawImage(img, -iw + 1, 0); // subsampled image becomes half smaller in rendering size. // check alpha channel value to confirm image is covering edge pixel or not. // if alpha value is 0 image is not covering, hence subsampled. return ctx.getImageData(0, 0, 1, 1).data[3] === 0; } else { return false; } } /** * Detecting vertical squash in loaded image. * Fixes a bug which squash image vertically while drawing into canvas for some images. */ function detectVerticalSquash(img, iw, ih) { var canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = ih; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); var data = ctx.getImageData(0, 0, 1, ih).data; // search image edge pixel position in case it is squashed vertically. var sy = 0; var ey = ih; var py = ih; while (py > sy) { var alpha = data[(py - 1) * 4 + 3]; if (alpha === 0) { ey = py; } else { sy = py; } py = (ey + sy) >> 1; } canvas = null; var ratio = (py / ih); return (ratio === 0) ? 1 : ratio; } return { isSubsampled: detectSubsampling, renderTo: renderImageToCanvas }; }); // Included from: src/javascript/runtime/html5/image/Image.js /** * Image.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/Image @private */ define("moxie/runtime/html5/image/Image", [ "moxie/runtime/html5/Runtime", "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/core/utils/Encode", "moxie/file/Blob", "moxie/runtime/html5/image/ImageInfo", "moxie/runtime/html5/image/MegaPixel", "moxie/core/utils/Mime", "moxie/core/utils/Env" ], function(extensions, Basic, x, Encode, Blob, ImageInfo, MegaPixel, Mime, Env) { function HTML5Image() { var me = this , _img, _imgInfo, _canvas, _binStr, _blob , _modified = false // is set true whenever image is modified , _preserveHeaders = true ; Basic.extend(this, { loadFromBlob: function(blob) { var comp = this, I = comp.getRuntime() , asBinary = arguments.length > 1 ? arguments[1] : true ; if (!I.can('access_binary')) { throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR); } _blob = blob; if (blob.isDetached()) { _binStr = blob.getSource(); _preload.call(this, _binStr); return; } else { _readAsDataUrl.call(this, blob.getSource(), function(dataUrl) { if (asBinary) { _binStr = _toBinary(dataUrl); } _preload.call(comp, dataUrl); }); } }, loadFromImage: function(img, exact) { this.meta = img.meta; _blob = new Blob(null, { name: img.name, size: img.size, type: img.type }); _preload.call(this, exact ? (_binStr = img.getAsBinaryString()) : img.getAsDataURL()); }, getInfo: function() { var I = this.getRuntime(), info; if (!_imgInfo && _binStr && I.can('access_image_binary')) { _imgInfo = new ImageInfo(_binStr); } info = { width: _getImg().width || 0, height: _getImg().height || 0, type: _blob.type || Mime.getFileMime(_blob.name), size: _binStr && _binStr.length || _blob.size || 0, name: _blob.name || '', meta: _imgInfo && _imgInfo.meta || this.meta || {} }; return info; }, downsize: function() { _downsize.apply(this, arguments); }, getAsCanvas: function() { if (_canvas) { _canvas.id = this.uid + '_canvas'; } return _canvas; }, getAsBlob: function(type, quality) { if (type !== this.type) { // if different mime type requested prepare image for conversion _downsize.call(this, this.width, this.height, false); } return new Blob(null, { type: type, data: me.getAsBinaryString.call(this, type, quality) }); }, getAsDataURL: function(type) { var quality = arguments[1] || 90; // if image has not been modified, return the source right away if (!_modified) { return _img.src; } if ('image/jpeg' !== type) { return _canvas.toDataURL('image/png'); } else { try { // older Geckos used to result in an exception on quality argument return _canvas.toDataURL('image/jpeg', quality/100); } catch (ex) { return _canvas.toDataURL('image/jpeg'); } } }, getAsBinaryString: function(type, quality) { // if image has not been modified, return the source right away if (!_modified) { // if image was not loaded from binary string if (!_binStr) { _binStr = _toBinary(me.getAsDataURL(type, quality)); } return _binStr; } if ('image/jpeg' !== type) { _binStr = _toBinary(me.getAsDataURL(type, quality)); } else { var dataUrl; // if jpeg if (!quality) { quality = 90; } try { // older Geckos used to result in an exception on quality argument dataUrl = _canvas.toDataURL('image/jpeg', quality/100); } catch (ex) { dataUrl = _canvas.toDataURL('image/jpeg'); } _binStr = _toBinary(dataUrl); if (_imgInfo) { _binStr = _imgInfo.stripHeaders(_binStr); if (_preserveHeaders) { // update dimensions info in exif if (_imgInfo.meta && _imgInfo.meta.exif) { _imgInfo.setExif({ PixelXDimension: this.width, PixelYDimension: this.height }); } // re-inject the headers _binStr = _imgInfo.writeHeaders(_binStr); } // will be re-created from fresh on next getInfo call _imgInfo.purge(); _imgInfo = null; } } _modified = false; return _binStr; }, destroy: function() { me = null; _purge.call(this); this.getRuntime().getShim().removeInstance(this.uid); } }); function _getImg() { if (!_canvas && !_img) { throw new x.ImageError(x.DOMException.INVALID_STATE_ERR); } return _canvas || _img; } function _toBinary(str) { return Encode.atob(str.substring(str.indexOf('base64,') + 7)); } function _toDataUrl(str, type) { return 'data:' + (type || '') + ';base64,' + Encode.btoa(str); } function _preload(str) { var comp = this; _img = new Image(); _img.onerror = function() { _purge.call(this); comp.trigger('error', new x.ImageError(x.ImageError.WRONG_FORMAT)); }; _img.onload = function() { comp.trigger('load'); }; _img.src = /^data:[^;]*;base64,/.test(str) ? str : _toDataUrl(str, _blob.type); } function _readAsDataUrl(file, callback) { var comp = this, fr; // use FileReader if it's available if (window.FileReader) { fr = new FileReader(); fr.onload = function() { callback(this.result); }; fr.onerror = function() { comp.trigger('error', new x.FileException(x.FileException.NOT_READABLE_ERR)); }; fr.readAsDataURL(file); } else { return callback(file.getAsDataURL()); } } function _downsize(width, height, crop, preserveHeaders) { var self = this, ctx, scale, mathFn, x, y, img, imgWidth, imgHeight, orientation; _preserveHeaders = preserveHeaders; // we will need to check this on export // take into account orientation tag orientation = (this.meta && this.meta.tiff && this.meta.tiff.Orientation) || 1; if (Basic.inArray(orientation, [5,6,7,8]) !== -1) { // values that require 90 degree rotation // swap dimensions var mem = width; width = height; height = mem; } img = _getImg(); // unify dimensions mathFn = !crop ? Math.min : Math.max; scale = mathFn(width/img.width, height/img.height); // we only downsize here if (scale > 1 && (!crop || preserveHeaders)) { // when cropping one of dimensions may still exceed max, so process it anyway this.trigger('Resize'); return; } imgWidth = Math.round(img.width * scale); imgHeight = Math.round(img.height * scale); // prepare canvas if necessary if (!_canvas) { _canvas = document.createElement("canvas"); } ctx = _canvas.getContext('2d'); // scale image and canvas if (crop) { _canvas.width = width; _canvas.height = height; } else { _canvas.width = imgWidth; _canvas.height = imgHeight; } // if dimensions of the resulting image still larger than canvas, center it x = imgWidth > _canvas.width ? Math.round((imgWidth - _canvas.width) / 2) : 0; y = imgHeight > _canvas.height ? Math.round((imgHeight - _canvas.height) / 2) : 0; if (!_preserveHeaders) { _rotateToOrientaion(_canvas.width, _canvas.height, orientation); } _drawToCanvas.call(this, img, _canvas, -x, -y, imgWidth, imgHeight); this.width = _canvas.width; this.height = _canvas.height; _modified = true; self.trigger('Resize'); } function _drawToCanvas(img, canvas, x, y, w, h) { if (Env.OS === 'iOS') { // avoid squish bug in iOS6 MegaPixel.renderTo(img, canvas, { width: w, height: h, x: x, y: y }); } else { var ctx = canvas.getContext('2d'); ctx.drawImage(img, x, y, w, h); } } /** * Transform canvas coordination according to specified frame size and orientation * Orientation value is from EXIF tag * @author Shinichi Tomita <[email protected]> */ function _rotateToOrientaion(width, height, orientation) { switch (orientation) { case 5: case 6: case 7: case 8: _canvas.width = height; _canvas.height = width; break; default: _canvas.width = width; _canvas.height = height; } /** 1 = The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side. 2 = The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side. 3 = The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side. 4 = The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side. 5 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual top. 6 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual top. 7 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom. 8 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom. */ var ctx = _canvas.getContext('2d'); switch (orientation) { case 2: // horizontal flip ctx.translate(width, 0); ctx.scale(-1, 1); break; case 3: // 180 rotate left ctx.translate(width, height); ctx.rotate(Math.PI); break; case 4: // vertical flip ctx.translate(0, height); ctx.scale(1, -1); break; case 5: // vertical flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.scale(1, -1); break; case 6: // 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(0, -height); break; case 7: // horizontal flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(width, -height); ctx.scale(-1, 1); break; case 8: // 90 rotate left ctx.rotate(-0.5 * Math.PI); ctx.translate(-width, 0); break; } } function _purge() { if (_imgInfo) { _imgInfo.purge(); _imgInfo = null; } _binStr = _img = _canvas = _blob = null; _modified = false; } } return (extensions.Image = HTML5Image); }); // Included from: src/javascript/runtime/flash/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global ActiveXObject:true */ /** Defines constructor for Flash runtime. @class moxie/runtime/flash/Runtime @private */ define("moxie/runtime/flash/Runtime", [ "moxie/core/utils/Basic", "moxie/core/utils/Env", "moxie/core/utils/Dom", "moxie/core/Exceptions", "moxie/runtime/Runtime" ], function(Basic, Env, Dom, x, Runtime) { var type = 'flash', extensions = {}; /** Get the version of the Flash Player @method getShimVersion @private @return {Number} Flash Player version */ function getShimVersion() { var version; try { version = navigator.plugins['Shockwave Flash']; version = version.description; } catch (e1) { try { version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version'); } catch (e2) { version = '0.0'; } } version = version.match(/\d+/g); return parseFloat(version[0] + '.' + version[1]); } /** Constructor for the Flash Runtime @class FlashRuntime @extends Runtime */ function FlashRuntime(options) { var I = this, initTimer; options = Basic.extend({ swf_url: Env.swf_url }, options); Runtime.call(this, options, type, { access_binary: function(value) { return value && I.mode === 'browser'; }, access_image_binary: function(value) { return value && I.mode === 'browser'; }, display_media: Runtime.capTrue, do_cors: Runtime.capTrue, drag_and_drop: false, report_upload_progress: function() { return I.mode === 'client'; }, resize_image: Runtime.capTrue, return_response_headers: false, return_response_type: function(responseType) { return !Basic.arrayDiff(responseType, ['', 'text', 'json', 'document']) || I.mode === 'browser'; }, return_status_code: function(code) { return I.mode === 'browser' || !Basic.arrayDiff(code, [200, 404]); }, select_file: Runtime.capTrue, select_multiple: Runtime.capTrue, send_binary_string: function(value) { return value && I.mode === 'browser'; }, send_browser_cookies: function(value) { return value && I.mode === 'browser'; }, send_custom_headers: function(value) { return value && I.mode === 'browser'; }, send_multipart: Runtime.capTrue, slice_blob: Runtime.capTrue, stream_upload: function(value) { return value && I.mode === 'browser'; }, summon_file_dialog: false, upload_filesize: function(size) { return Basic.parseSizeStr(size) <= 2097152 || I.mode === 'client'; }, use_http_method: function(methods) { return !Basic.arrayDiff(methods, ['GET', 'POST']); } }, { // capabilities that require specific mode access_binary: function(value) { return value ? 'browser' : 'client'; }, access_image_binary: function(value) { return value ? 'browser' : 'client'; }, report_upload_progress: function(value) { return value ? 'browser' : 'client'; }, return_response_type: function(responseType) { return Basic.arrayDiff(responseType, ['', 'text', 'json', 'document']) ? 'browser' : ['client', 'browser']; }, return_status_code: function(code) { return Basic.arrayDiff(code, [200, 404]) ? 'browser' : ['client', 'browser']; }, send_binary_string: function(value) { return value ? 'browser' : 'client'; }, send_browser_cookies: function(value) { return value ? 'browser' : 'client'; }, send_custom_headers: function(value) { return value ? 'browser' : 'client'; }, stream_upload: function(value) { return value ? 'client' : 'browser'; }, upload_filesize: function(size) { return Basic.parseSizeStr(size) >= 2097152 ? 'client' : 'browser'; } }, 'client'); // minimal requirement Flash Player 10 if (getShimVersion() < 10) { this.mode = false; // with falsy mode, runtime won't operable, no matter what the mode was before } Basic.extend(this, { getShim: function() { return Dom.get(this.uid); }, shimExec: function(component, action) { var args = [].slice.call(arguments, 2); return I.getShim().exec(this.uid, component, action, args); }, init: function() { var html, el, container; container = this.getShimContainer(); // if not the minimal height, shims are not initialized in older browsers (e.g FF3.6, IE6,7,8, Safari 4.0,5.0, etc) Basic.extend(container.style, { position: 'absolute', top: '-8px', left: '-8px', width: '9px', height: '9px', overflow: 'hidden' }); // insert flash object html = '<object id="' + this.uid + '" type="application/x-shockwave-flash" data="' + options.swf_url + '" '; if (Env.browser === 'IE') { html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '; } html += 'width="100%" height="100%" style="outline:0">' + '<param name="movie" value="' + options.swf_url + '" />' + '<param name="flashvars" value="uid=' + escape(this.uid) + '&target=' + Env.global_event_dispatcher + '" />' + '<param name="wmode" value="transparent" />' + '<param name="allowscriptaccess" value="always" />' + '</object>'; if (Env.browser === 'IE') { el = document.createElement('div'); container.appendChild(el); el.outerHTML = html; el = container = null; // just in case } else { container.innerHTML = html; } // Init is dispatched by the shim initTimer = setTimeout(function() { if (I && !I.initialized) { // runtime might be already destroyed by this moment I.trigger("Error", new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR)); } }, 5000); }, destroy: (function(destroy) { // extend default destroy method return function() { destroy.call(I); clearTimeout(initTimer); // initialization check might be still onwait options = initTimer = destroy = I = null; }; }(this.destroy)) }, extensions); } Runtime.addConstructor(type, FlashRuntime); return extensions; }); // Included from: src/javascript/runtime/flash/file/Blob.js /** * Blob.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/file/Blob @private */ define("moxie/runtime/flash/file/Blob", [ "moxie/runtime/flash/Runtime", "moxie/file/Blob" ], function(extensions, Blob) { var FlashBlob = { slice: function(blob, start, end, type) { var self = this.getRuntime(); if (start < 0) { start = Math.max(blob.size + start, 0); } else if (start > 0) { start = Math.min(start, blob.size); } if (end < 0) { end = Math.max(blob.size + end, 0); } else if (end > 0) { end = Math.min(end, blob.size); } blob = self.shimExec.call(this, 'Blob', 'slice', start, end, type || ''); if (blob) { blob = new Blob(self.uid, blob); } return blob; } }; return (extensions.Blob = FlashBlob); }); // Included from: src/javascript/runtime/flash/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/file/FileInput @private */ define("moxie/runtime/flash/file/FileInput", [ "moxie/runtime/flash/Runtime" ], function(extensions) { var FileInput = { init: function(options) { this.getRuntime().shimExec.call(this, 'FileInput', 'init', { name: options.name, accept: options.accept, multiple: options.multiple }); this.trigger('ready'); } }; return (extensions.FileInput = FileInput); }); // Included from: src/javascript/runtime/flash/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/file/FileReader @private */ define("moxie/runtime/flash/file/FileReader", [ "moxie/runtime/flash/Runtime", "moxie/core/utils/Encode" ], function(extensions, Encode) { var _result = ''; function _formatData(data, op) { switch (op) { case 'readAsText': return Encode.atob(data, 'utf8'); case 'readAsBinaryString': return Encode.atob(data); case 'readAsDataURL': return data; } return null; } var FileReader = { read: function(op, blob) { var target = this, self = target.getRuntime(); // special prefix for DataURL read mode if (op === 'readAsDataURL') { _result = 'data:' + (blob.type || '') + ';base64,'; } target.bind('Progress', function(e, data) { if (data) { _result += _formatData(data, op); } }); return self.shimExec.call(this, 'FileReader', 'readAsBase64', blob.uid); }, getResult: function() { return _result; }, destroy: function() { _result = null; } }; return (extensions.FileReader = FileReader); }); // Included from: src/javascript/runtime/flash/file/FileReaderSync.js /** * FileReaderSync.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/file/FileReaderSync @private */ define("moxie/runtime/flash/file/FileReaderSync", [ "moxie/runtime/flash/Runtime", "moxie/core/utils/Encode" ], function(extensions, Encode) { function _formatData(data, op) { switch (op) { case 'readAsText': return Encode.atob(data, 'utf8'); case 'readAsBinaryString': return Encode.atob(data); case 'readAsDataURL': return data; } return null; } var FileReaderSync = { read: function(op, blob) { var result, self = this.getRuntime(); result = self.shimExec.call(this, 'FileReaderSync', 'readAsBase64', blob.uid); if (!result) { return null; // or throw ex } // special prefix for DataURL read mode if (op === 'readAsDataURL') { result = 'data:' + (blob.type || '') + ';base64,' + result; } return _formatData(result, op, blob.type); } }; return (extensions.FileReaderSync = FileReaderSync); }); // Included from: src/javascript/runtime/flash/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/xhr/XMLHttpRequest @private */ define("moxie/runtime/flash/xhr/XMLHttpRequest", [ "moxie/runtime/flash/Runtime", "moxie/core/utils/Basic", "moxie/file/Blob", "moxie/file/File", "moxie/file/FileReaderSync", "moxie/xhr/FormData", "moxie/runtime/Transporter", "moxie/core/JSON" ], function(extensions, Basic, Blob, File, FileReaderSync, FormData, Transporter, parseJSON) { var XMLHttpRequest = { send: function(meta, data) { var target = this, self = target.getRuntime(); function send() { meta.transport = self.mode; self.shimExec.call(target, 'XMLHttpRequest', 'send', meta, data); } function appendBlob(name, blob) { self.shimExec.call(target, 'XMLHttpRequest', 'appendBlob', name, blob.uid); data = null; send(); } function attachBlob(blob, cb) { var tr = new Transporter(); tr.bind("TransportingComplete", function() { cb(this.result); }); tr.transport(blob.getSource(), blob.type, { ruid: self.uid }); } // copy over the headers if any if (!Basic.isEmptyObj(meta.headers)) { Basic.each(meta.headers, function(value, header) { self.shimExec.call(target, 'XMLHttpRequest', 'setRequestHeader', header, value.toString()); // Silverlight doesn't accept integers into the arguments of type object }); } // transfer over multipart params and blob itself if (data instanceof FormData) { var blobField; data.each(function(value, name) { if (value instanceof Blob) { blobField = name; } else { self.shimExec.call(target, 'XMLHttpRequest', 'append', name, value); } }); if (!data.hasBlob()) { data = null; send(); } else { var blob = data.getBlob(); if (blob.isDetached()) { attachBlob(blob, function(attachedBlob) { blob.destroy(); appendBlob(blobField, attachedBlob); }); } else { appendBlob(blobField, blob); } } } else if (data instanceof Blob) { if (data.isDetached()) { attachBlob(data, function(attachedBlob) { data.destroy(); data = attachedBlob.uid; send(); }); } else { data = data.uid; send(); } } else { send(); } }, getResponse: function(responseType) { var frs, blob, self = this.getRuntime(); blob = self.shimExec.call(this, 'XMLHttpRequest', 'getResponseAsBlob'); if (blob) { blob = new File(self.uid, blob); if ('blob' === responseType) { return blob; } else if (!!~Basic.inArray(responseType, ["", "text"])) { frs = new FileReaderSync(); return frs.readAsText(blob); } else if ('arraybuffer' === responseType) { // do something } else if ('json' === responseType) { frs = new FileReaderSync(); try { return parseJSON(frs.readAsText(blob)); } catch (ex) { return null; } } } return null; }, abort: function(upload_complete_flag) { var self = this.getRuntime(); self.shimExec.call(this, 'XMLHttpRequest', 'abort'); this.dispatchEvent('readystatechange'); // this.dispatchEvent('progress'); this.dispatchEvent('abort'); if (!upload_complete_flag) { // this.dispatchEvent('uploadprogress'); } } }; return (extensions.XMLHttpRequest = XMLHttpRequest); }); // Included from: src/javascript/runtime/flash/runtime/Transporter.js /** * Transporter.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/runtime/Transporter @private */ define("moxie/runtime/flash/runtime/Transporter", [ "moxie/runtime/flash/Runtime", "moxie/file/Blob" ], function(extensions, Blob) { var Transporter = { getAsBlob: function(type) { var self = this.getRuntime() , blob = self.shimExec.call(this, 'Transporter', 'getAsBlob', type) ; if (blob) { return new Blob(self.uid, blob); } return null; } }; return (extensions.Transporter = Transporter); }); // Included from: src/javascript/runtime/flash/image/Image.js /** * Image.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/image/Image @private */ define("moxie/runtime/flash/image/Image", [ "moxie/runtime/flash/Runtime", "moxie/core/utils/Basic", "moxie/runtime/Transporter", "moxie/file/Blob", "moxie/file/FileReaderSync" ], function(extensions, Basic, Transporter, Blob, FileReaderSync) { var Image = { loadFromBlob: function(blob) { var comp = this, self = comp.getRuntime(); function exec(srcBlob) { self.shimExec.call(comp, 'Image', 'loadFromBlob', srcBlob.uid); comp = self = null; } if (blob.isDetached()) { // binary string var tr = new Transporter(); tr.bind("TransportingComplete", function() { exec(tr.result.getSource()); }); tr.transport(blob.getSource(), blob.type, { ruid: self.uid }); } else { exec(blob.getSource()); } }, loadFromImage: function(img) { var self = this.getRuntime(); return self.shimExec.call(this, 'Image', 'loadFromImage', img.uid); }, getAsBlob: function(type, quality) { var self = this.getRuntime() , blob = self.shimExec.call(this, 'Image', 'getAsBlob', type, quality) ; if (blob) { return new Blob(self.uid, blob); } return null; }, getAsDataURL: function() { var self = this.getRuntime() , blob = self.Image.getAsBlob.apply(this, arguments) , frs ; if (!blob) { return null; } frs = new FileReaderSync(); return frs.readAsDataURL(blob); } }; return (extensions.Image = Image); }); // Included from: src/javascript/runtime/silverlight/Runtime.js /** * RunTime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global ActiveXObject:true */ /** Defines constructor for Silverlight runtime. @class moxie/runtime/silverlight/Runtime @private */ define("moxie/runtime/silverlight/Runtime", [ "moxie/core/utils/Basic", "moxie/core/utils/Env", "moxie/core/utils/Dom", "moxie/core/Exceptions", "moxie/runtime/Runtime" ], function(Basic, Env, Dom, x, Runtime) { var type = "silverlight", extensions = {}; function isInstalled(version) { var isVersionSupported = false, control = null, actualVer, actualVerArray, reqVerArray, requiredVersionPart, actualVersionPart, index = 0; try { try { control = new ActiveXObject('AgControl.AgControl'); if (control.IsVersionSupported(version)) { isVersionSupported = true; } control = null; } catch (e) { var plugin = navigator.plugins["Silverlight Plug-In"]; if (plugin) { actualVer = plugin.description; if (actualVer === "1.0.30226.2") { actualVer = "2.0.30226.2"; } actualVerArray = actualVer.split("."); while (actualVerArray.length > 3) { actualVerArray.pop(); } while ( actualVerArray.length < 4) { actualVerArray.push(0); } reqVerArray = version.split("."); while (reqVerArray.length > 4) { reqVerArray.pop(); } do { requiredVersionPart = parseInt(reqVerArray[index], 10); actualVersionPart = parseInt(actualVerArray[index], 10); index++; } while (index < reqVerArray.length && requiredVersionPart === actualVersionPart); if (requiredVersionPart <= actualVersionPart && !isNaN(requiredVersionPart)) { isVersionSupported = true; } } } } catch (e2) { isVersionSupported = false; } return isVersionSupported; } /** Constructor for the Silverlight Runtime @class SilverlightRuntime @extends Runtime */ function SilverlightRuntime(options) { var I = this, initTimer; options = Basic.extend({ xap_url: Env.xap_url }, options); Runtime.call(this, options, type, { access_binary: Runtime.capTrue, access_image_binary: Runtime.capTrue, display_media: Runtime.capTrue, do_cors: Runtime.capTrue, drag_and_drop: false, report_upload_progress: Runtime.capTrue, resize_image: Runtime.capTrue, return_response_headers: function(value) { return value && I.mode === 'client'; }, return_response_type: Runtime.capTrue, return_status_code: function(code) { return I.mode === 'client' || !Basic.arrayDiff(code, [200, 404]); }, select_file: Runtime.capTrue, select_multiple: Runtime.capTrue, send_binary_string: Runtime.capTrue, send_browser_cookies: function(value) { return value && I.mode === 'browser'; }, send_custom_headers: function(value) { return value && I.mode === 'client'; }, send_multipart: Runtime.capTrue, slice_blob: Runtime.capTrue, stream_upload: true, summon_file_dialog: false, upload_filesize: Runtime.capTrue, use_http_method: function(methods) { return I.mode === 'client' || !Basic.arrayDiff(methods, ['GET', 'POST']); } }, { // capabilities that require specific mode return_response_headers: function(value) { return value ? 'client' : 'browser'; }, return_status_code: function(code) { return Basic.arrayDiff(code, [200, 404]) ? 'client' : ['client', 'browser']; }, send_browser_cookies: function(value) { return value ? 'browser' : 'client'; }, send_custom_headers: function(value) { return value ? 'client' : 'browser'; }, use_http_method: function(methods) { return Basic.arrayDiff(methods, ['GET', 'POST']) ? 'client' : ['client', 'browser']; } }); // minimal requirement if (!isInstalled('2.0.31005.0') || Env.browser === 'Opera') { this.mode = false; } Basic.extend(this, { getShim: function() { return Dom.get(this.uid).content.Moxie; }, shimExec: function(component, action) { var args = [].slice.call(arguments, 2); return I.getShim().exec(this.uid, component, action, args); }, init : function() { var container; container = this.getShimContainer(); container.innerHTML = '<object id="' + this.uid + '" data="data:application/x-silverlight," type="application/x-silverlight-2" width="100%" height="100%" style="outline:none;">' + '<param name="source" value="' + options.xap_url + '"/>' + '<param name="background" value="Transparent"/>' + '<param name="windowless" value="true"/>' + '<param name="enablehtmlaccess" value="true"/>' + '<param name="initParams" value="uid=' + this.uid + ',target=' + Env.global_event_dispatcher + '"/>' + '</object>'; // Init is dispatched by the shim initTimer = setTimeout(function() { if (I && !I.initialized) { // runtime might be already destroyed by this moment I.trigger("Error", new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR)); } }, Env.OS !== 'Windows'? 10000 : 5000); // give it more time to initialize in non Windows OS (like Mac) }, destroy: (function(destroy) { // extend default destroy method return function() { destroy.call(I); clearTimeout(initTimer); // initialization check might be still onwait options = initTimer = destroy = I = null; }; }(this.destroy)) }, extensions); } Runtime.addConstructor(type, SilverlightRuntime); return extensions; }); // Included from: src/javascript/runtime/silverlight/file/Blob.js /** * Blob.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/Blob @private */ define("moxie/runtime/silverlight/file/Blob", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/file/Blob" ], function(extensions, Basic, Blob) { return (extensions.Blob = Basic.extend({}, Blob)); }); // Included from: src/javascript/runtime/silverlight/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/FileInput @private */ define("moxie/runtime/silverlight/file/FileInput", [ "moxie/runtime/silverlight/Runtime" ], function(extensions) { var FileInput = { init: function(options) { function toFilters(accept) { var filter = ''; for (var i = 0; i < accept.length; i++) { filter += (filter !== '' ? '|' : '') + accept[i].title + " | *." + accept[i].extensions.replace(/,/g, ';*.'); } return filter; } this.getRuntime().shimExec.call(this, 'FileInput', 'init', toFilters(options.accept), options.name, options.multiple); this.trigger('ready'); } }; return (extensions.FileInput = FileInput); }); // Included from: src/javascript/runtime/silverlight/file/FileDrop.js /** * FileDrop.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/FileDrop @private */ define("moxie/runtime/silverlight/file/FileDrop", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Dom", "moxie/core/utils/Events" ], function(extensions, Dom, Events) { // not exactly useful, since works only in safari (...crickets...) var FileDrop = { init: function() { var comp = this, self = comp.getRuntime(), dropZone; dropZone = self.getShimContainer(); Events.addEvent(dropZone, 'dragover', function(e) { e.preventDefault(); e.stopPropagation(); e.dataTransfer.dropEffect = 'copy'; }, comp.uid); Events.addEvent(dropZone, 'dragenter', function(e) { e.preventDefault(); var flag = Dom.get(self.uid).dragEnter(e); // If handled, then stop propagation of event in DOM if (flag) { e.stopPropagation(); } }, comp.uid); Events.addEvent(dropZone, 'drop', function(e) { e.preventDefault(); var flag = Dom.get(self.uid).dragDrop(e); // If handled, then stop propagation of event in DOM if (flag) { e.stopPropagation(); } }, comp.uid); return self.shimExec.call(this, 'FileDrop', 'init'); } }; return (extensions.FileDrop = FileDrop); }); // Included from: src/javascript/runtime/silverlight/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/FileReader @private */ define("moxie/runtime/silverlight/file/FileReader", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/file/FileReader" ], function(extensions, Basic, FileReader) { return (extensions.FileReader = Basic.extend({}, FileReader)); }); // Included from: src/javascript/runtime/silverlight/file/FileReaderSync.js /** * FileReaderSync.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/FileReaderSync @private */ define("moxie/runtime/silverlight/file/FileReaderSync", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/file/FileReaderSync" ], function(extensions, Basic, FileReaderSync) { return (extensions.FileReaderSync = Basic.extend({}, FileReaderSync)); }); // Included from: src/javascript/runtime/silverlight/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/xhr/XMLHttpRequest @private */ define("moxie/runtime/silverlight/xhr/XMLHttpRequest", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/xhr/XMLHttpRequest" ], function(extensions, Basic, XMLHttpRequest) { return (extensions.XMLHttpRequest = Basic.extend({}, XMLHttpRequest)); }); // Included from: src/javascript/runtime/silverlight/runtime/Transporter.js /** * Transporter.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/runtime/Transporter @private */ define("moxie/runtime/silverlight/runtime/Transporter", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/runtime/Transporter" ], function(extensions, Basic, Transporter) { return (extensions.Transporter = Basic.extend({}, Transporter)); }); // Included from: src/javascript/runtime/silverlight/image/Image.js /** * Image.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/image/Image @private */ define("moxie/runtime/silverlight/image/Image", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/image/Image" ], function(extensions, Basic, Image) { return (extensions.Image = Basic.extend({}, Image)); }); // Included from: src/javascript/runtime/html4/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global File:true */ /** Defines constructor for HTML4 runtime. @class moxie/runtime/html4/Runtime @private */ define("moxie/runtime/html4/Runtime", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/runtime/Runtime", "moxie/core/utils/Env" ], function(Basic, x, Runtime, Env) { var type = 'html4', extensions = {}; function Html4Runtime(options) { var I = this , Test = Runtime.capTest , True = Runtime.capTrue ; Runtime.call(this, options, type, { access_binary: Test(window.FileReader || window.File && File.getAsDataURL), access_image_binary: false, display_media: Test(extensions.Image && (Env.can('create_canvas') || Env.can('use_data_uri_over32kb'))), do_cors: false, drag_and_drop: false, filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest return (Env.browser === 'Chrome' && Env.version >= 28) || (Env.browser === 'IE' && Env.version >= 10); }()), resize_image: function() { return extensions.Image && I.can('access_binary') && Env.can('create_canvas'); }, report_upload_progress: false, return_response_headers: false, return_response_type: function(responseType) { return !!~Basic.inArray(responseType, ['json', 'text', 'document', '']); }, return_status_code: function(code) { return !Basic.arrayDiff(code, [200, 404]); }, select_file: function() { return Env.can('use_fileinput'); }, select_multiple: false, send_binary_string: false, send_custom_headers: false, send_multipart: true, slice_blob: false, stream_upload: function() { return I.can('select_file'); }, summon_file_dialog: Test(function() { // yeah... some dirty sniffing here... return (Env.browser === 'Firefox' && Env.version >= 4) || (Env.browser === 'Opera' && Env.version >= 12) || (Env.browser === 'IE' && Env.version >= 10) || !!~Basic.inArray(Env.browser, ['Chrome', 'Safari']); }()), upload_filesize: True, use_http_method: function(methods) { return !Basic.arrayDiff(methods, ['GET', 'POST']); } }); Basic.extend(this, { init : function() { this.trigger("Init"); }, destroy: (function(destroy) { // extend default destroy method return function() { destroy.call(I); destroy = I = null; }; }(this.destroy)) }); Basic.extend(this.getShim(), extensions); } Runtime.addConstructor(type, Html4Runtime); return extensions; }); // Included from: src/javascript/runtime/html4/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html4/file/FileInput @private */ define("moxie/runtime/html4/file/FileInput", [ "moxie/runtime/html4/Runtime", "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/utils/Events", "moxie/core/utils/Mime", "moxie/core/utils/Env" ], function(extensions, Basic, Dom, Events, Mime, Env) { function FileInput() { var _uid, _files = [], _mimes = [], _options; function addInput() { var comp = this, I = comp.getRuntime(), shimContainer, browseButton, currForm, form, input, uid; uid = Basic.guid('uid_'); shimContainer = I.getShimContainer(); // we get new ref everytime to avoid memory leaks in IE if (_uid) { // move previous form out of the view currForm = Dom.get(_uid + '_form'); if (currForm) { Basic.extend(currForm.style, { top: '100%' }); } } // build form in DOM, since innerHTML version not able to submit file for some reason form = document.createElement('form'); form.setAttribute('id', uid + '_form'); form.setAttribute('method', 'post'); form.setAttribute('enctype', 'multipart/form-data'); form.setAttribute('encoding', 'multipart/form-data'); Basic.extend(form.style, { overflow: 'hidden', position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }); input = document.createElement('input'); input.setAttribute('id', uid); input.setAttribute('type', 'file'); input.setAttribute('name', 'Filedata'); input.setAttribute('accept', _mimes.join(',')); Basic.extend(input.style, { fontSize: '999px', opacity: 0 }); form.appendChild(input); shimContainer.appendChild(form); // prepare file input to be placed underneath the browse_button element Basic.extend(input.style, { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }); if (Env.browser === 'IE' && Env.version < 10) { Basic.extend(input.style, { filter : "progid:DXImageTransform.Microsoft.Alpha(opacity=0)" }); } input.onchange = function() { // there should be only one handler for this var file; if (!this.value) { return; } if (this.files) { file = this.files[0]; } else { file = { name: this.value }; } _files = [file]; this.onchange = function() {}; // clear event handler addInput.call(comp); // after file is initialized as o.File, we need to update form and input ids comp.bind('change', function() { var input = Dom.get(uid), form = Dom.get(uid + '_form'), file; if (comp.files.length && input && form) { file = comp.files[0]; input.setAttribute('id', file.uid); form.setAttribute('id', file.uid + '_form'); // set upload target form.setAttribute('target', file.uid + '_iframe'); } input = form = null; }, 998); input = form = null; comp.trigger('change'); }; // route click event to the input if (I.can('summon_file_dialog')) { browseButton = Dom.get(_options.browse_button); Events.removeEvent(browseButton, 'click', comp.uid); Events.addEvent(browseButton, 'click', function(e) { if (input && !input.disabled) { // for some reason FF (up to 8.0.1 so far) lets to click disabled input[type=file] input.click(); } e.preventDefault(); }, comp.uid); } _uid = uid; shimContainer = currForm = browseButton = null; // trigger ready event asynchronously comp.trigger({ type: 'ready', async: true }); } Basic.extend(this, { init: function(options) { var comp = this, I = comp.getRuntime(), shimContainer; // figure out accept string _options = options; _mimes = options.accept.mimes || Mime.extList2mimes(options.accept, I.can('filter_by_extension')); shimContainer = I.getShimContainer(); (function() { var browseButton, zIndex, top; browseButton = Dom.get(options.browse_button); // Route click event to the input[type=file] element for browsers that support such behavior if (I.can('summon_file_dialog')) { if (Dom.getStyle(browseButton, 'position') === 'static') { browseButton.style.position = 'relative'; } zIndex = parseInt(Dom.getStyle(browseButton, 'z-index'), 10) || 1; browseButton.style.zIndex = zIndex; shimContainer.style.zIndex = zIndex - 1; } /* Since we have to place input[type=file] on top of the browse_button for some browsers, browse_button loses interactivity, so we restore it here */ top = I.can('summon_file_dialog') ? browseButton : shimContainer; Events.addEvent(top, 'mouseover', function() { comp.trigger('mouseenter'); }, comp.uid); Events.addEvent(top, 'mouseout', function() { comp.trigger('mouseleave'); }, comp.uid); Events.addEvent(top, 'mousedown', function() { comp.trigger('mousedown'); }, comp.uid); Events.addEvent(Dom.get(options.container), 'mouseup', function() { comp.trigger('mouseup'); }, comp.uid); browseButton = null; }()); addInput.call(this); shimContainer = null; }, getFiles: function() { return _files; }, disable: function(state) { var input; if ((input = Dom.get(_uid))) { input.disabled = !!state; } }, destroy: function() { var I = this.getRuntime(), shimContainer = I.getShimContainer(); Events.removeAllEvents(shimContainer, this.uid); Events.removeAllEvents(_options && Dom.get(_options.container), this.uid); Events.removeAllEvents(_options && Dom.get(_options.browse_button), this.uid); if (shimContainer) { shimContainer.innerHTML = ''; } _uid = _files = _mimes = _options = null; } }); } return (extensions.FileInput = FileInput); }); // Included from: src/javascript/runtime/html4/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html4/file/FileReader @private */ define("moxie/runtime/html4/file/FileReader", [ "moxie/runtime/html4/Runtime", "moxie/runtime/html5/file/FileReader" ], function(extensions, FileReader) { return (extensions.FileReader = FileReader); }); // Included from: src/javascript/runtime/html4/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html4/xhr/XMLHttpRequest @private */ define("moxie/runtime/html4/xhr/XMLHttpRequest", [ "moxie/runtime/html4/Runtime", "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/utils/Url", "moxie/core/Exceptions", "moxie/core/utils/Events", "moxie/file/Blob", "moxie/xhr/FormData", "moxie/core/JSON" ], function(extensions, Basic, Dom, Url, x, Events, Blob, FormData, parseJSON) { function XMLHttpRequest() { var _status, _response, _iframe; function cleanup(cb) { var target = this, uid, form, inputs, i, hasFile = false; if (!_iframe) { return; } uid = _iframe.id.replace(/_iframe$/, ''); form = Dom.get(uid + '_form'); if (form) { inputs = form.getElementsByTagName('input'); i = inputs.length; while (i--) { switch (inputs[i].getAttribute('type')) { case 'hidden': inputs[i].parentNode.removeChild(inputs[i]); break; case 'file': hasFile = true; // flag the case for later break; } } inputs = []; if (!hasFile) { // we need to keep the form for sake of possible retries form.parentNode.removeChild(form); } form = null; } // without timeout, request is marked as canceled (in console) setTimeout(function() { Events.removeEvent(_iframe, 'load', target.uid); if (_iframe.parentNode) { // #382 _iframe.parentNode.removeChild(_iframe); } // check if shim container has any other children, if - not, remove it as well var shimContainer = target.getRuntime().getShimContainer(); if (!shimContainer.children.length) { shimContainer.parentNode.removeChild(shimContainer); } shimContainer = _iframe = null; cb(); }, 1); } Basic.extend(this, { send: function(meta, data) { var target = this, I = target.getRuntime(), uid, form, input, blob; _status = _response = null; function createIframe() { var container = I.getShimContainer() || document.body , temp = document.createElement('div') ; // IE 6 won't be able to set the name using setAttribute or iframe.name temp.innerHTML = '<iframe id="' + uid + '_iframe" name="' + uid + '_iframe" src="javascript:&quot;&quot;" style="display:none"></iframe>'; _iframe = temp.firstChild; container.appendChild(_iframe); /* _iframe.onreadystatechange = function() { //console.info(_iframe.readyState); };*/ Events.addEvent(_iframe, 'load', function() { // _iframe.onload doesn't work in IE lte 8 var el; try { el = _iframe.contentWindow.document || _iframe.contentDocument || window.frames[_iframe.id].document; // try to detect some standard error pages if (/^4\d{2}\s/.test(el.title) && el.getElementsByTagName('address').length) { // standard Apache style _status = el.title.replace(/^(\d+).*$/, '$1'); } else { _status = 200; // get result _response = Basic.trim(el.body.innerHTML); // we need to fire these at least once target.trigger({ type: 'progress', loaded: _response.length, total: _response.length }); if (blob) { // if we were uploading a file target.trigger({ type: 'uploadprogress', loaded: blob.size || 1025, total: blob.size || 1025 }); } } } catch (ex) { if (Url.hasSameOrigin(meta.url)) { // if response is sent with error code, iframe in IE gets redirected to res://ieframe.dll/http_x.htm // which obviously results to cross domain error (wtf?) _status = 404; } else { cleanup.call(target, function() { target.trigger('error'); }); return; } } cleanup.call(target, function() { target.trigger('load'); }); }, target.uid); } // end createIframe // prepare data to be sent and convert if required if (data instanceof FormData && data.hasBlob()) { blob = data.getBlob(); uid = blob.uid; input = Dom.get(uid); form = Dom.get(uid + '_form'); if (!form) { throw new x.DOMException(x.DOMException.NOT_FOUND_ERR); } } else { uid = Basic.guid('uid_'); form = document.createElement('form'); form.setAttribute('id', uid + '_form'); form.setAttribute('method', meta.method); form.setAttribute('enctype', 'multipart/form-data'); form.setAttribute('encoding', 'multipart/form-data'); form.setAttribute('target', uid + '_iframe'); I.getShimContainer().appendChild(form); } if (data instanceof FormData) { data.each(function(value, name) { if (value instanceof Blob) { if (input) { input.setAttribute('name', name); } } else { var hidden = document.createElement('input'); Basic.extend(hidden, { type : 'hidden', name : name, value : value }); form.appendChild(hidden); } }); } // set destination url form.setAttribute("action", meta.url); createIframe(); form.submit(); target.trigger('loadstart'); }, getStatus: function() { return _status; }, getResponse: function(responseType) { if ('json' === responseType) { // strip off <pre>..</pre> tags that might be enclosing the response if (Basic.typeOf(_response) === 'string') { try { return parseJSON(_response.replace(/^\s*<pre[^>]*>/, '').replace(/<\/pre>\s*$/, '')); } catch (ex) { return null; } } } else if ('document' === responseType) { } return _response; }, abort: function() { var target = this; if (_iframe && _iframe.contentWindow) { if (_iframe.contentWindow.stop) { // FireFox/Safari/Chrome _iframe.contentWindow.stop(); } else if (_iframe.contentWindow.document.execCommand) { // IE _iframe.contentWindow.document.execCommand('Stop'); } else { _iframe.src = "about:blank"; } } cleanup.call(this, function() { // target.dispatchEvent('readystatechange'); target.dispatchEvent('abort'); }); } }); } return (extensions.XMLHttpRequest = XMLHttpRequest); }); // Included from: src/javascript/runtime/html4/image/Image.js /** * Image.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html4/image/Image @private */ define("moxie/runtime/html4/image/Image", [ "moxie/runtime/html4/Runtime", "moxie/runtime/html5/image/Image" ], function(extensions, Image) { return (extensions.Image = Image); }); expose(["moxie/core/utils/Basic","moxie/core/I18n","moxie/core/utils/Mime","moxie/core/utils/Env","moxie/core/utils/Dom","moxie/core/Exceptions","moxie/core/EventTarget","moxie/core/utils/Encode","moxie/runtime/Runtime","moxie/runtime/RuntimeClient","moxie/file/Blob","moxie/file/File","moxie/file/FileInput","moxie/file/FileDrop","moxie/runtime/RuntimeTarget","moxie/file/FileReader","moxie/core/utils/Url","moxie/file/FileReaderSync","moxie/xhr/FormData","moxie/xhr/XMLHttpRequest","moxie/runtime/Transporter","moxie/core/JSON","moxie/image/Image","moxie/core/utils/Events"]); })(this);/** * o.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global moxie:true */ /** Globally exposed namespace with the most frequently used public classes and handy methods. @class o @static @private */ (function() { "use strict"; var o = {}, inArray = moxie.core.utils.Basic.inArray; // directly add some public classes // (we do it dynamically here, since for custom builds we cannot know beforehand what modules were included) (function addAlias(ns) { var name, itemType; for (name in ns) { itemType = typeof(ns[name]); if (itemType === 'object' && !~inArray(name, ['Exceptions', 'Env', 'Mime'])) { addAlias(ns[name]); } else if (itemType === 'function') { o[name] = ns[name]; } } })(window.moxie); // add some manually o.Env = window.moxie.core.utils.Env; o.Mime = window.moxie.core.utils.Mime; o.Exceptions = window.moxie.core.Exceptions; // expose globally window.mOxie = o; if (!window.o) { window.o = o; } return o; })();
web/js/lib/jquery/moxie.js
/** * mOxie - multi-runtime File API & XMLHttpRequest L2 Polyfill * v1.0.0 * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing * * Date: 2013-09-23 */ /** * Compiled inline version. (Library mode) */ /*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */ /*globals $code */ (function(exports, undefined) { "use strict"; var modules = {}; function require(ids, callback) { var module, defs = []; for (var i = 0; i < ids.length; ++i) { module = modules[ids[i]] || resolve(ids[i]); if (!module) { throw 'module definition dependecy not found: ' + ids[i]; } defs.push(module); } callback.apply(null, defs); } function define(id, dependencies, definition) { if (typeof id !== 'string') { throw 'invalid module definition, module id must be defined and be a string'; } if (dependencies === undefined) { throw 'invalid module definition, dependencies must be specified'; } if (definition === undefined) { throw 'invalid module definition, definition function must be specified'; } require(dependencies, function() { modules[id] = definition.apply(null, arguments); }); } function defined(id) { return !!modules[id]; } function resolve(id) { var target = exports; var fragments = id.split(/[.\/]/); for (var fi = 0; fi < fragments.length; ++fi) { if (!target[fragments[fi]]) { return; } target = target[fragments[fi]]; } return target; } function expose(ids) { for (var i = 0; i < ids.length; i++) { var target = exports; var id = ids[i]; var fragments = id.split(/[.\/]/); for (var fi = 0; fi < fragments.length - 1; ++fi) { if (target[fragments[fi]] === undefined) { target[fragments[fi]] = {}; } target = target[fragments[fi]]; } target[fragments[fragments.length - 1]] = modules[id]; } } // Included from: src/javascript/core/utils/Basic.js /** * Basic.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Basic', [], function() { /** Gets the true type of the built-in object (better version of typeof). @author Angus Croll (http://javascriptweblog.wordpress.com/) @method typeOf @for Utils @static @param {Object} o Object to check. @return {String} Object [[Class]] */ var typeOf = function(o) { var undef; if (o === undef) { return 'undefined'; } else if (o === null) { return 'null'; } else if (o.nodeType) { return 'node'; } // the snippet below is awesome, however it fails to detect null, undefined and arguments types in IE lte 8 return ({}).toString.call(o).match(/\s([a-z|A-Z]+)/)[1].toLowerCase(); }; /** Extends the specified object with another object. @method extend @static @param {Object} target Object to extend. @param {Object} [obj]* Multiple objects to extend with. @return {Object} Same as target, the extended object. */ var extend = function(target) { var undef; each(arguments, function(arg, i) { if (i > 0) { each(arg, function(value, key) { if (value !== undef) { if (typeOf(target[key]) === typeOf(value) && !!~inArray(typeOf(value), ['array', 'object'])) { extend(target[key], value); } else { target[key] = value; } } }); } }); return target; }; /** Executes the callback function for each item in array/object. If you return false in the callback it will break the loop. @method each @static @param {Object} obj Object to iterate. @param {function} callback Callback function to execute for each item. */ var each = function(obj, callback) { var length, key, i, undef; if (obj) { try { length = obj.length; } catch(ex) { length = undef; } if (length === undef) { // Loop object items for (key in obj) { if (obj.hasOwnProperty(key)) { if (callback(obj[key], key) === false) { return; } } } } else { // Loop array items for (i = 0; i < length; i++) { if (callback(obj[i], i) === false) { return; } } } } }; /** Checks if object is empty. @method isEmptyObj @static @param {Object} o Object to check. @return {Boolean} */ var isEmptyObj = function(obj) { var prop; if (!obj || typeOf(obj) !== 'object') { return true; } for (prop in obj) { return false; } return true; }; /** Recieve an array of functions (usually async) to call in sequence, each function receives a callback as first argument that it should call, when it completes. Finally, after everything is complete, main callback is called. Passing truthy value to the callback as a first argument will interrupt the sequence and invoke main callback immediately. @method inSeries @static @param {Array} queue Array of functions to call in sequence @param {Function} cb Main callback that is called in the end, or in case of erro */ var inSeries = function(queue, cb) { var i = 0, length = queue.length; if (typeOf(cb) !== 'function') { cb = function() {}; } if (!queue || !queue.length) { cb(); } function callNext(i) { if (typeOf(queue[i]) === 'function') { queue[i](function(error) { /*jshint expr:true */ ++i < length && !error ? callNext(i) : cb(error); }); } } callNext(i); }; /** Find an element in array and return it's index if present, otherwise return -1. @method inArray @static @param {Mixed} needle Element to find @param {Array} array @return {Int} Index of the element, or -1 if not found */ var inArray = function(needle, array) { if (array) { if (Array.prototype.indexOf) { return Array.prototype.indexOf.call(array, needle); } for (var i = 0, length = array.length; i < length; i++) { if (array[i] === needle) { return i; } } } return -1; }; /** Returns elements of first array if they are not present in second. And false - otherwise. @private @method arrayDiff @param {Array} needles @param {Array} array @return {Array|Boolean} */ var arrayDiff = function(needles, array) { var diff = []; if (typeOf(needles) !== 'array') { needles = [needles]; } if (typeOf(array) !== 'array') { array = [array]; } for (var i in needles) { if (inArray(needles[i], array) === -1) { diff.push(needles[i]); } } return diff.length ? diff : false; }; /** Find intersection of two arrays. @private @method arrayIntersect @param {Array} array1 @param {Array} array2 @return {Array} Intersection of two arrays or null if there is none */ var arrayIntersect = function(array1, array2) { var result = []; each(array1, function(item) { if (inArray(item, array2) !== -1) { result.push(item); } }); return result.length ? result : null; }; /** Forces anything into an array. @method toArray @static @param {Object} obj Object with length field. @return {Array} Array object containing all items. */ var toArray = function(obj) { var i, arr = []; for (i = 0; i < obj.length; i++) { arr[i] = obj[i]; } return arr; }; /** Generates an unique ID. This is 99.99% unique since it takes the current time and 5 random numbers. The only way a user would be able to get the same ID is if the two persons at the same exact milisecond manages to get 5 the same random numbers between 0-65535 it also uses a counter so each call will be guaranteed to be page unique. It's more probable for the earth to be hit with an ansteriod. Y @method guid @static @param {String} prefix to prepend (by default 'o' will be prepended). @method guid @return {String} Virtually unique id. */ var guid = (function() { var counter = 0; return function(prefix) { var guid = new Date().getTime().toString(32), i; for (i = 0; i < 5; i++) { guid += Math.floor(Math.random() * 65535).toString(32); } return (prefix || 'o_') + guid + (counter++).toString(32); }; }()); /** Trims white spaces around the string @method trim @static @param {String} str @return {String} */ var trim = function(str) { if (!str) { return str; } return String.prototype.trim ? String.prototype.trim.call(str) : str.toString().replace(/^\s*/, '').replace(/\s*$/, ''); }; /** Parses the specified size string into a byte value. For example 10kb becomes 10240. @method parseSizeStr @static @param {String/Number} size String to parse or number to just pass through. @return {Number} Size in bytes. */ var parseSizeStr = function(size) { if (typeof(size) !== 'string') { return size; } var muls = { t: 1099511627776, g: 1073741824, m: 1048576, k: 1024 }, mul; size = /^([0-9]+)([mgk]?)$/.exec(size.toLowerCase().replace(/[^0-9mkg]/g, '')); mul = size[2]; size = +size[1]; if (muls.hasOwnProperty(mul)) { size *= muls[mul]; } return size; }; return { guid: guid, typeOf: typeOf, extend: extend, each: each, isEmptyObj: isEmptyObj, inSeries: inSeries, inArray: inArray, arrayDiff: arrayDiff, arrayIntersect: arrayIntersect, toArray: toArray, trim: trim, parseSizeStr: parseSizeStr }; }); // Included from: src/javascript/core/I18n.js /** * I18n.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/core/I18n", [ "moxie/core/utils/Basic" ], function(Basic) { var i18n = {}; return { /** * Extends the language pack object with new items. * * @param {Object} pack Language pack items to add. * @return {Object} Extended language pack object. */ addI18n: function(pack) { return Basic.extend(i18n, pack); }, /** * Translates the specified string by checking for the english string in the language pack lookup. * * @param {String} str String to look for. * @return {String} Translated string or the input string if it wasn't found. */ translate: function(str) { return i18n[str] || str; }, /** * Shortcut for translate function * * @param {String} str String to look for. * @return {String} Translated string or the input string if it wasn't found. */ _: function(str) { return this.translate(str); }, /** * Pseudo sprintf implementation - simple way to replace tokens with specified values. * * @param {String} str String with tokens * @return {String} String with replaced tokens */ sprintf: function(str) { var args = [].slice.call(arguments, 1), reStr = ''; Basic.each(str.split(/%[a-z]/), function(part) { reStr += part; if (args.length) { reStr += args.shift(); } }); return reStr; } }; }); // Included from: src/javascript/core/utils/Mime.js /** * Mime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/core/utils/Mime", [ "moxie/core/utils/Basic", "moxie/core/I18n" ], function(Basic, I18n) { var mimeData = "" + "application/msword,doc dot," + "application/pdf,pdf," + "application/pgp-signature,pgp," + "application/postscript,ps ai eps," + "application/rtf,rtf," + "application/vnd.ms-excel,xls xlb," + "application/vnd.ms-powerpoint,ppt pps pot," + "application/zip,zip," + "application/x-shockwave-flash,swf swfl," + "application/vnd.openxmlformats-officedocument.wordprocessingml.document,docx," + "application/vnd.openxmlformats-officedocument.wordprocessingml.template,dotx," + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,xlsx," + "application/vnd.openxmlformats-officedocument.presentationml.presentation,pptx," + "application/vnd.openxmlformats-officedocument.presentationml.template,potx," + "application/vnd.openxmlformats-officedocument.presentationml.slideshow,ppsx," + "application/x-javascript,js," + "application/json,json," + "audio/mpeg,mp3 mpga mpega mp2," + "audio/x-wav,wav," + "audio/mp4,m4a," + "audio/ogg,oga ogg," + "audio/aiff,aiff aif," + "audio/flac,flac," + "audio/aac,aac," + "audio/ac3,ac3," + "audio/x-ms-wma,wma," + "image/bmp,bmp," + "image/gif,gif," + "image/jpeg,jpg jpeg jpe," + "image/photoshop,psd," + "image/png,png," + "image/svg+xml,svg svgz," + "image/tiff,tiff tif," + "text/plain,asc txt text diff log," + "text/html,htm html xhtml," + "text/css,css," + "text/csv,csv," + "text/rtf,rtf," + "video/mpeg,mpeg mpg mpe m2v," + "video/quicktime,qt mov," + "video/mp4,mp4," + "video/x-m4v,m4v," + "video/x-flv,flv," + "video/x-ms-wmv,wmv," + "video/avi,avi," + "video/webm,webm," + "video/3gpp,3gpp 3gp," + "video/3gpp2,3g2," + "video/vnd.rn-realvideo,rv," + "video/ogg,ogv," + "video/x-matroska,mkv," + "application/vnd.oasis.opendocument.formula-template,otf," + "application/octet-stream,exe"; var Mime = { mimes: {}, extensions: {}, // Parses the default mime types string into a mimes and extensions lookup maps addMimeType: function (mimeData) { var items = mimeData.split(/,/), i, ii, ext; for (i = 0; i < items.length; i += 2) { ext = items[i + 1].split(/ /); // extension to mime lookup for (ii = 0; ii < ext.length; ii++) { this.mimes[ext[ii]] = items[i]; } // mime to extension lookup this.extensions[items[i]] = ext; } }, extList2mimes: function (filters, addMissingExtensions) { var self = this, ext, i, ii, type, mimes = []; // convert extensions to mime types list for (i = 0; i < filters.length; i++) { ext = filters[i].extensions.split(/\s*,\s*/); for (ii = 0; ii < ext.length; ii++) { // if there's an asterisk in the list, then accept attribute is not required if (ext[ii] === '*') { return []; } type = self.mimes[ext[ii]]; if (!type) { if (addMissingExtensions && /^\w+$/.test(ext[ii])) { mimes.push('.' + ext[ii]); } else { return []; // accept all } } else if (Basic.inArray(type, mimes) === -1) { mimes.push(type); } } } return mimes; }, mimes2exts: function(mimes) { var self = this, exts = []; Basic.each(mimes, function(mime) { if (mime === '*') { exts = []; return false; } // check if this thing looks like mime type var m = mime.match(/^(\w+)\/(\*|\w+)$/); if (m) { if (m[2] === '*') { // wildcard mime type detected Basic.each(self.extensions, function(arr, mime) { if ((new RegExp('^' + m[1] + '/')).test(mime)) { [].push.apply(exts, self.extensions[mime]); } }); } else if (self.extensions[mime]) { [].push.apply(exts, self.extensions[mime]); } } }); return exts; }, mimes2extList: function(mimes) { var accept = [], exts = []; if (Basic.typeOf(mimes) === 'string') { mimes = Basic.trim(mimes).split(/\s*,\s*/); } exts = this.mimes2exts(mimes); accept.push({ title: I18n.translate('Files'), extensions: exts.length ? exts.join(',') : '*' }); // save original mimes string accept.mimes = mimes; return accept; }, getFileExtension: function(fileName) { var matches = fileName && fileName.match(/\.([^.]+)$/); if (matches) { return matches[1].toLowerCase(); } return ''; }, getFileMime: function(fileName) { return this.mimes[this.getFileExtension(fileName)] || ''; } }; Mime.addMimeType(mimeData); return Mime; }); // Included from: src/javascript/core/utils/Env.js /** * Env.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/core/utils/Env", [ "moxie/core/utils/Basic" ], function(Basic) { var browser = [{ s1: navigator.userAgent, s2: "Android", id: "Android Browser", // default or Dolphin sv: "Version" },{ s1: navigator.userAgent, // string s2: "Chrome", // substring id: "Chrome" // identity },{ s1: navigator.vendor, s2: "Apple", id: "Safari", sv: "Version" // version },{ prop: window.opera && window.opera.buildNumber, id: "Opera", sv: "Version" },{ s1: navigator.vendor, s2: "KDE", id: "Konqueror" },{ s1: navigator.userAgent, s2: "Firefox", id: "Firefox" },{ s1: navigator.vendor, s2: "Camino", id: "Camino" },{ // for newer Netscapes (6+) s1: navigator.userAgent, s2: "Netscape", id: "Netscape" },{ s1: navigator.userAgent, s2: "MSIE", id: "IE", sv: "MSIE" },{ s1: navigator.userAgent, s2: "Gecko", id: "Mozilla", sv: "rv" }], os = [{ s1: navigator.platform, s2: "Win", id: "Windows" },{ s1: navigator.platform, s2: "Mac", id: "Mac" },{ s1: navigator.userAgent, s2: "iPhone", id: "iOS" },{ s1: navigator.userAgent, s2: "iPad", id: "iOS" },{ s1: navigator.userAgent, s2: "Android", id: "Android" },{ s1: navigator.platform, s2: "Linux", id: "Linux" }] , version; function getStr(data) { var str, prop; for (var i = 0; i < data.length; i++) { str = data[i].s1; prop = data[i].prop; version = data[i].sv || data[i].id; if (str) { if (str.indexOf(data[i].s2) != -1) { return data[i].id; } } else if (prop) { return data[i].id; } } } function getVer(str) { var index = str.indexOf(version); if (index == -1) { return; } return parseFloat(str.substring(index + version.length + 1)); } var can = (function() { var caps = { define_property: (function() { /* // currently too much extra code required, not exactly worth it try { // as of IE8, getters/setters are supported only on DOM elements var obj = {}; if (Object.defineProperty) { Object.defineProperty(obj, 'prop', { enumerable: true, configurable: true }); return true; } } catch(ex) {} if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) { return true; }*/ return false; }()), create_canvas: (function() { // On the S60 and BB Storm, getContext exists, but always returns undefined // so we actually have to call getContext() to verify // github.com/Modernizr/Modernizr/issues/issue/97/ var el = document.createElement('canvas'); return !!(el.getContext && el.getContext('2d')); }()), return_response_type: function(responseType) { try { if (Basic.inArray(responseType, ['', 'text', 'document']) !== -1) { return true; } else if (window.XMLHttpRequest){ var xhr = new XMLHttpRequest(); xhr.open('get', '/'); // otherwise Gecko throws an exception if ('responseType' in xhr) { xhr.responseType = responseType; // as of 23.0.1271.64, Chrome switched from throwing exception to merely logging it to the console (why? o why?) if (xhr.responseType !== responseType) { return false; } return true; } } } catch (ex) {} return false; }, // ideas for this heavily come from Modernizr (http://modernizr.com/) use_data_uri: (function() { var du = new Image(); du.onload = function() { caps.use_data_uri = (du.width === 1 && du.height === 1); }; setTimeout(function() { du.src = "data:image/gif;base64,R0lGODlhAQABAIAAAP8AAAAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=="; }, 1); return false; }()), use_data_uri_over32kb: function() { // IE8 return caps.use_data_uri && (Env.browser !== 'IE' || Env.version >= 9); }, use_data_uri_of: function(bytes) { return (caps.use_data_uri && bytes < 33000 || caps.use_data_uri_over32kb()); }, use_fileinput: function() { var el = document.createElement('input'); el.setAttribute('type', 'file'); return !el.disabled; } }; return function(cap) { var args = [].slice.call(arguments); args.shift(); // shift of cap return Basic.typeOf(caps[cap]) === 'function' ? caps[cap].apply(this, args) : !!caps[cap]; }; }()); var Env = { can: can, browser: getStr(browser), version: getVer(navigator.userAgent) || getVer(navigator.appVersion), OS: getStr(os), swf_url: "../flash/Moxie.swf", xap_url: "../silverlight/Moxie.xap", global_event_dispatcher: "moxie.core.EventTarget.instance.dispatchEvent" }; return Env; }); // Included from: src/javascript/core/utils/Dom.js /** * Dom.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Dom', ['moxie/core/utils/Env'], function(Env) { /** Get DOM Element by it's id. @method get @for Utils @param {String} id Identifier of the DOM Element @return {DOMElement} */ var get = function(id) { if (typeof id !== 'string') { return id; } return document.getElementById(id); }; /** Checks if specified DOM element has specified class. @method hasClass @static @param {Object} obj DOM element like object to add handler to. @param {String} name Class name */ var hasClass = function(obj, name) { var regExp; if (obj.className === '') { return false; } regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)"); return regExp.test(obj.className); }; /** Adds specified className to specified DOM element. @method addClass @static @param {Object} obj DOM element like object to add handler to. @param {String} name Class name */ var addClass = function(obj, name) { if (!hasClass(obj, name)) { obj.className = obj.className === '' ? name : obj.className.replace(/\s+$/, '') + ' ' + name; } }; /** Removes specified className from specified DOM element. @method removeClass @static @param {Object} obj DOM element like object to add handler to. @param {String} name Class name */ var removeClass = function(obj, name) { var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)"); obj.className = obj.className.replace(regExp, function($0, $1, $2) { return $1 === ' ' && $2 === ' ' ? ' ' : ''; }); }; /** Returns a given computed style of a DOM element. @method getStyle @static @param {Object} obj DOM element like object. @param {String} name Style you want to get from the DOM element */ var getStyle = function(obj, name) { if (obj.currentStyle) { return obj.currentStyle[name]; } else if (window.getComputedStyle) { return window.getComputedStyle(obj, null)[name]; } }; /** Returns the absolute x, y position of an Element. The position will be returned in a object with x, y fields. @method getPos @static @param {Element} node HTML element or element id to get x, y position from. @param {Element} root Optional root element to stop calculations at. @return {object} Absolute position of the specified element object with x, y fields. */ var getPos = function(node, root) { var x = 0, y = 0, parent, doc = document, nodeRect, rootRect; node = node; root = root || doc.body; // Returns the x, y cordinate for an element on IE 6 and IE 7 function getIEPos(node) { var bodyElm, rect, x = 0, y = 0; if (node) { rect = node.getBoundingClientRect(); bodyElm = doc.compatMode === "CSS1Compat" ? doc.documentElement : doc.body; x = rect.left + bodyElm.scrollLeft; y = rect.top + bodyElm.scrollTop; } return { x : x, y : y }; } // Use getBoundingClientRect on IE 6 and IE 7 but not on IE 8 in standards mode if (node && node.getBoundingClientRect && Env.browser === 'IE' && (!doc.documentMode || doc.documentMode < 8)) { nodeRect = getIEPos(node); rootRect = getIEPos(root); return { x : nodeRect.x - rootRect.x, y : nodeRect.y - rootRect.y }; } parent = node; while (parent && parent != root && parent.nodeType) { x += parent.offsetLeft || 0; y += parent.offsetTop || 0; parent = parent.offsetParent; } parent = node.parentNode; while (parent && parent != root && parent.nodeType) { x -= parent.scrollLeft || 0; y -= parent.scrollTop || 0; parent = parent.parentNode; } return { x : x, y : y }; }; /** Returns the size of the specified node in pixels. @method getSize @static @param {Node} node Node to get the size of. @return {Object} Object with a w and h property. */ var getSize = function(node) { return { w : node.offsetWidth || node.clientWidth, h : node.offsetHeight || node.clientHeight }; }; return { get: get, hasClass: hasClass, addClass: addClass, removeClass: removeClass, getStyle: getStyle, getPos: getPos, getSize: getSize }; }); // Included from: src/javascript/core/Exceptions.js /** * Exceptions.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/Exceptions', [ 'moxie/core/utils/Basic' ], function(Basic) { function _findKey(obj, value) { var key; for (key in obj) { if (obj[key] === value) { return key; } } return null; } return { RuntimeError: (function() { var namecodes = { NOT_INIT_ERR: 1, NOT_SUPPORTED_ERR: 9, JS_ERR: 4 }; function RuntimeError(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": RuntimeError " + this.code; } Basic.extend(RuntimeError, namecodes); RuntimeError.prototype = Error.prototype; return RuntimeError; }()), OperationNotAllowedException: (function() { function OperationNotAllowedException(code) { this.code = code; this.name = 'OperationNotAllowedException'; } Basic.extend(OperationNotAllowedException, { NOT_ALLOWED_ERR: 1 }); OperationNotAllowedException.prototype = Error.prototype; return OperationNotAllowedException; }()), ImageError: (function() { var namecodes = { WRONG_FORMAT: 1, MAX_RESOLUTION_ERR: 2 }; function ImageError(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": ImageError " + this.code; } Basic.extend(ImageError, namecodes); ImageError.prototype = Error.prototype; return ImageError; }()), FileException: (function() { var namecodes = { NOT_FOUND_ERR: 1, SECURITY_ERR: 2, ABORT_ERR: 3, NOT_READABLE_ERR: 4, ENCODING_ERR: 5, NO_MODIFICATION_ALLOWED_ERR: 6, INVALID_STATE_ERR: 7, SYNTAX_ERR: 8 }; function FileException(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": FileException " + this.code; } Basic.extend(FileException, namecodes); FileException.prototype = Error.prototype; return FileException; }()), DOMException: (function() { var namecodes = { INDEX_SIZE_ERR: 1, DOMSTRING_SIZE_ERR: 2, HIERARCHY_REQUEST_ERR: 3, WRONG_DOCUMENT_ERR: 4, INVALID_CHARACTER_ERR: 5, NO_DATA_ALLOWED_ERR: 6, NO_MODIFICATION_ALLOWED_ERR: 7, NOT_FOUND_ERR: 8, NOT_SUPPORTED_ERR: 9, INUSE_ATTRIBUTE_ERR: 10, INVALID_STATE_ERR: 11, SYNTAX_ERR: 12, INVALID_MODIFICATION_ERR: 13, NAMESPACE_ERR: 14, INVALID_ACCESS_ERR: 15, VALIDATION_ERR: 16, TYPE_MISMATCH_ERR: 17, SECURITY_ERR: 18, NETWORK_ERR: 19, ABORT_ERR: 20, URL_MISMATCH_ERR: 21, QUOTA_EXCEEDED_ERR: 22, TIMEOUT_ERR: 23, INVALID_NODE_TYPE_ERR: 24, DATA_CLONE_ERR: 25 }; function DOMException(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": DOMException " + this.code; } Basic.extend(DOMException, namecodes); DOMException.prototype = Error.prototype; return DOMException; }()), EventException: (function() { function EventException(code) { this.code = code; this.name = 'EventException'; } Basic.extend(EventException, { UNSPECIFIED_EVENT_TYPE_ERR: 0 }); EventException.prototype = Error.prototype; return EventException; }()) }; }); // Included from: src/javascript/core/EventTarget.js /** * EventTarget.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/EventTarget', [ 'moxie/core/Exceptions', 'moxie/core/utils/Basic' ], function(x, Basic) { /** Parent object for all event dispatching components and objects @class EventTarget @constructor EventTarget */ function EventTarget() { // hash of event listeners by object uid var eventpool = {}; Basic.extend(this, { /** Unique id of the event dispatcher, usually overriden by children @property uid @type String */ uid: null, /** Can be called from within a child in order to acquire uniqie id in automated manner @method init */ init: function() { if (!this.uid) { this.uid = Basic.guid('uid_'); } }, /** Register a handler to a specific event dispatched by the object @method addEventListener @param {String} type Type or basically a name of the event to subscribe to @param {Function} fn Callback function that will be called when event happens @param {Number} [priority=0] Priority of the event handler - handlers with higher priorities will be called first @param {Object} [scope=this] A scope to invoke event handler in */ addEventListener: function(type, fn, priority, scope) { var self = this, list; type = Basic.trim(type); if (/\s/.test(type)) { // multiple event types were passed for one handler Basic.each(type.split(/\s+/), function(type) { self.addEventListener(type, fn, priority, scope); }); return; } type = type.toLowerCase(); priority = parseInt(priority, 10) || 0; list = eventpool[this.uid] && eventpool[this.uid][type] || []; list.push({fn : fn, priority : priority, scope : scope || this}); if (!eventpool[this.uid]) { eventpool[this.uid] = {}; } eventpool[this.uid][type] = list; }, /** Check if any handlers were registered to the specified event @method hasEventListener @param {String} type Type or basically a name of the event to check @return {Mixed} Returns a handler if it was found and false, if - not */ hasEventListener: function(type) { return type ? !!(eventpool[this.uid] && eventpool[this.uid][type]) : !!eventpool[this.uid]; }, /** Unregister the handler from the event, or if former was not specified - unregister all handlers @method removeEventListener @param {String} type Type or basically a name of the event @param {Function} [fn] Handler to unregister */ removeEventListener: function(type, fn) { type = type.toLowerCase(); var list = eventpool[this.uid] && eventpool[this.uid][type], i; if (list) { if (fn) { for (i = list.length - 1; i >= 0; i--) { if (list[i].fn === fn) { list.splice(i, 1); break; } } } else { list = []; } // delete event list if it has become empty if (!list.length) { delete eventpool[this.uid][type]; // and object specific entry in a hash if it has no more listeners attached if (Basic.isEmptyObj(eventpool[this.uid])) { delete eventpool[this.uid]; } } } }, /** Remove all event handlers from the object @method removeAllEventListeners */ removeAllEventListeners: function() { if (eventpool[this.uid]) { delete eventpool[this.uid]; } }, /** Dispatch the event @method dispatchEvent @param {String/Object} Type of event or event object to dispatch @param {Mixed} [...] Variable number of arguments to be passed to a handlers @return {Boolean} true by default and false if any handler returned false */ dispatchEvent: function(type) { var uid, list, args, tmpEvt, evt = {}; if (Basic.typeOf(type) !== 'string') { // we can't use original object directly (because of Silverlight) tmpEvt = type; if (Basic.typeOf(tmpEvt.type) === 'string') { type = tmpEvt.type; if (tmpEvt.total && tmpEvt.loaded) { // progress event evt.total = tmpEvt.total; evt.loaded = tmpEvt.loaded; } evt.async = tmpEvt.async || false; } else { throw new x.EventException(x.EventException.UNSPECIFIED_EVENT_TYPE_ERR); } } // check if event is meant to be dispatched on an object having specific uid if (type.indexOf('::') !== -1) { (function(arr) { uid = arr[0]; type = arr[1]; }(type.split('::'))); } else { uid = this.uid; } type = type.toLowerCase(); list = eventpool[uid] && eventpool[uid][type]; if (list) { // sort event list by prority list.sort(function(a, b) { return b.priority - a.priority; }); args = [].slice.call(arguments); // first argument will be pseudo-event object args.shift(); evt.type = type; args.unshift(evt); // Dispatch event to all listeners var queue = []; Basic.each(list, function(handler) { // explicitly set the target, otherwise events fired from shims do not get it args[0].target = handler.scope; // if event is marked as async, detach the handler if (evt.async) { queue.push(function(cb) { setTimeout(function() { cb(handler.fn.apply(handler.scope, args) === false); }, 1); }); } else { queue.push(function(cb) { cb(handler.fn.apply(handler.scope, args) === false); // if handler returns false stop propagation }); } }); if (queue.length) { Basic.inSeries(queue); } } return true; }, /** Alias for addEventListener @method bind @protected */ bind: function() { this.addEventListener.apply(this, arguments); }, /** Alias for removeEventListener @method unbind @protected */ unbind: function() { this.removeEventListener.apply(this, arguments); }, /** Alias for removeAllEventListeners @method unbindAll @protected */ unbindAll: function() { this.removeAllEventListeners.apply(this, arguments); }, /** Alias for dispatchEvent @method trigger @protected */ trigger: function() { this.dispatchEvent.apply(this, arguments); }, /** Converts properties of on[event] type to corresponding event handlers, is used to avoid extra hassle around the process of calling them back @method convertEventPropsToHandlers @private */ convertEventPropsToHandlers: function(handlers) { var h; if (Basic.typeOf(handlers) !== 'array') { handlers = [handlers]; } for (var i = 0; i < handlers.length; i++) { h = 'on' + handlers[i]; if (Basic.typeOf(this[h]) === 'function') { this.addEventListener(handlers[i], this[h]); } else if (Basic.typeOf(this[h]) === 'undefined') { this[h] = null; // object must have defined event properties, even if it doesn't make use of them } } } }); } EventTarget.instance = new EventTarget(); return EventTarget; }); // Included from: src/javascript/core/utils/Encode.js /** * Encode.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Encode', [], function() { /** Encode string with UTF-8 @method utf8_encode @for Utils @static @param {String} str String to encode @return {String} UTF-8 encoded string */ var utf8_encode = function(str) { return unescape(encodeURIComponent(str)); }; /** Decode UTF-8 encoded string @method utf8_decode @static @param {String} str String to decode @return {String} Decoded string */ var utf8_decode = function(str_data) { return decodeURIComponent(escape(str_data)); }; /** Decode Base64 encoded string (uses browser's default method if available), from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_decode.js @method atob @static @param {String} data String to decode @return {String} Decoded string */ var atob = function(data, utf8) { if (typeof(window.atob) === 'function') { return utf8 ? utf8_decode(window.atob(data)) : window.atob(data); } // http://kevin.vanzonneveld.net // + original by: Tyler Akins (http://rumkin.com) // + improved by: Thunder.m // + input by: Aman Gupta // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Onno Marsman // + bugfixed by: Pellentesque Malesuada // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // * example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA=='); // * returns 1: 'Kevin van Zonneveld' // mozilla has this native // - but breaks in 2.0.0.12! //if (typeof this.window.atob == 'function') { // return atob(data); //} var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = []; if (!data) { return data; } data += ''; do { // unpack four hexets into three octets using index points in b64 h1 = b64.indexOf(data.charAt(i++)); h2 = b64.indexOf(data.charAt(i++)); h3 = b64.indexOf(data.charAt(i++)); h4 = b64.indexOf(data.charAt(i++)); bits = h1 << 18 | h2 << 12 | h3 << 6 | h4; o1 = bits >> 16 & 0xff; o2 = bits >> 8 & 0xff; o3 = bits & 0xff; if (h3 == 64) { tmp_arr[ac++] = String.fromCharCode(o1); } else if (h4 == 64) { tmp_arr[ac++] = String.fromCharCode(o1, o2); } else { tmp_arr[ac++] = String.fromCharCode(o1, o2, o3); } } while (i < data.length); dec = tmp_arr.join(''); return utf8 ? utf8_decode(dec) : dec; }; /** Base64 encode string (uses browser's default method if available), from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_encode.js @method btoa @static @param {String} data String to encode @return {String} Base64 encoded string */ var btoa = function(data, utf8) { if (utf8) { utf8_encode(data); } if (typeof(window.btoa) === 'function') { return window.btoa(data); } // http://kevin.vanzonneveld.net // + original by: Tyler Akins (http://rumkin.com) // + improved by: Bayron Guevara // + improved by: Thunder.m // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Pellentesque Malesuada // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Rafał Kukawski (http://kukawski.pl) // * example 1: base64_encode('Kevin van Zonneveld'); // * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA==' // mozilla has this native // - but breaks in 2.0.0.12! var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc = "", tmp_arr = []; if (!data) { return data; } do { // pack three octets into four hexets o1 = data.charCodeAt(i++); o2 = data.charCodeAt(i++); o3 = data.charCodeAt(i++); bits = o1 << 16 | o2 << 8 | o3; h1 = bits >> 18 & 0x3f; h2 = bits >> 12 & 0x3f; h3 = bits >> 6 & 0x3f; h4 = bits & 0x3f; // use hexets to index into b64, and append result to encoded string tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); } while (i < data.length); enc = tmp_arr.join(''); var r = data.length % 3; return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3); }; return { utf8_encode: utf8_encode, utf8_decode: utf8_decode, atob: atob, btoa: btoa }; }); // Included from: src/javascript/runtime/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/runtime/Runtime', [ "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/EventTarget" ], function(Basic, Dom, EventTarget) { var runtimeConstructors = {}, runtimes = {}; /** Common set of methods and properties for every runtime instance @class Runtime @param {Object} options @param {String} type Sanitized name of the runtime @param {Object} [caps] Set of capabilities that differentiate specified runtime @param {Object} [modeCaps] Set of capabilities that do require specific operational mode @param {String} [defaultMode='browser'] Default operational mode to choose if no required capabilities were requested */ function Runtime(options, type, caps, modeCaps, defaultMode) { /** Dispatched when runtime is initialized and ready. Results in RuntimeInit on a connected component. @event Init */ /** Dispatched when runtime fails to initialize. Results in RuntimeError on a connected component. @event Error */ var self = this , _shim , _uid = Basic.guid(type + '_') ; /** Runtime (not native one) may operate in browser or client mode. @method _setMode @private @param {Object} [modeCaps] Set of capabilities that do require specific operational mode @param {Object} [defaultMode] The mode to switch to if modeCaps or requiredCaps are empty */ function _setMode(modeCaps, defaultMode) { var mode = null , rc = options && options.required_caps ; defaultMode = defaultMode || 'browser'; // mode can be effectively set only once if (this.mode !== null) { return this.mode; } if (rc && !Basic.isEmptyObj(modeCaps)) { // loop over required caps and check if they do require the same mode Basic.each(rc, function(value, cap) { if (modeCaps.hasOwnProperty(cap)) { var capMode = modeCaps[cap](value); // make sure we always have an array if (typeof(capMode) === 'string') { capMode = [capMode]; } if (!mode) { mode = capMode; } else if (!(mode = Basic.arrayIntersect(mode, capMode))) { // if cap requires conflicting mode - runtime cannot fulfill required caps return (mode = false); } } }); if (mode) { this.mode = Basic.inArray(defaultMode, mode) !== -1 ? defaultMode : mode[0]; } else if (mode === false) { this.mode = false; } } // if mode still not defined if (this.mode === null) { this.mode = defaultMode; } // once we got the mode, test against all caps if (this.mode && rc && !this.can(rc)) { this.mode = false; } } // register runtime in private hash runtimes[_uid] = this; /** Default set of capabilities, which can be redifined later by specific runtime @private @property caps @type Object */ caps = Basic.extend({ // Runtime can: // provide access to raw binary data of the file access_binary: false, // provide access to raw binary data of the image (image extension is optional) access_image_binary: false, // display binary data as thumbs for example display_media: false, // make cross-domain requests do_cors: false, // accept files dragged and dropped from the desktop drag_and_drop: false, // filter files in selection dialog by their extensions filter_by_extension: true, // resize image (and manipulate it raw data of any file in general) resize_image: false, // periodically report how many bytes of total in the file were uploaded (loaded) report_upload_progress: false, // provide access to the headers of http response return_response_headers: false, // support response of specific type, which should be passed as an argument // e.g. runtime.can('return_response_type', 'blob') return_response_type: false, // return http status code of the response return_status_code: true, // send custom http header with the request send_custom_headers: false, // pick up the files from a dialog select_file: false, // select whole folder in file browse dialog select_folder: false, // select multiple files at once in file browse dialog select_multiple: true, // send raw binary data, that is generated after image resizing or manipulation of other kind send_binary_string: false, // send cookies with http request and therefore retain session send_browser_cookies: true, // send data formatted as multipart/form-data send_multipart: true, // slice the file or blob to smaller parts slice_blob: false, // upload file without preloading it to memory, stream it out directly from disk stream_upload: false, // programmatically trigger file browse dialog summon_file_dialog: false, // upload file of specific size, size should be passed as argument // e.g. runtime.can('upload_filesize', '500mb') upload_filesize: true, // initiate http request with specific http method, method should be passed as argument // e.g. runtime.can('use_http_method', 'put') use_http_method: true }, caps); // small extension factory here (is meant to be extended with actual extensions constructors) _shim = (function() { var objpool = {}; return { exec: function(uid, comp, fn, args) { if (_shim[comp]) { if (!objpool[uid]) { objpool[uid] = { context: this, instance: new _shim[comp]() }; } if (objpool[uid].instance[fn]) { return objpool[uid].instance[fn].apply(this, args); } } }, removeInstance: function(uid) { delete objpool[uid]; }, removeAllInstances: function() { var self = this; Basic.each(objpool, function(obj, uid) { if (Basic.typeOf(obj.instance.destroy) === 'function') { obj.instance.destroy.call(obj.context); } self.removeInstance(uid); }); } }; }()); // public methods Basic.extend(this, { /** Specifies whether runtime instance was initialized or not @property initialized @type {Boolean} @default false */ initialized: false, // shims require this flag to stop initialization retries /** Unique ID of the runtime @property uid @type {String} */ uid: _uid, /** Runtime type (e.g. flash, html5, etc) @property type @type {String} */ type: type, /** Runtime (not native one) may operate in browser or client mode. @property mode @private @type {String|Boolean} current mode or false, if none possible */ mode: null, /** id of the DOM container for the runtime (if available) @property shimid @type {String} */ shimid: _uid + '_container', /** Number of connected clients. If equal to zero, runtime can be destroyed @property clients @type {Number} */ clients: 0, /** Runtime initialization options @property options @type {Object} */ options: options, /** Checks if the runtime has specific capability @method can @param {String} cap Name of capability to check @param {Mixed} [value] If passed, capability should somehow correlate to the value @param {Object} [refCaps] Set of capabilities to check the specified cap against (defaults to internal set) @return {Boolean} true if runtime has such capability and false, if - not */ can: function(cap, value) { var refCaps = arguments[2] || caps; // if cap var is a comma-separated list of caps, convert it to object (key/value) if (Basic.typeOf(cap) === 'string' && Basic.typeOf(value) === 'undefined') { cap = Runtime.parseCaps(cap); } if (Basic.typeOf(cap) === 'object') { for (var key in cap) { if (!this.can(key, cap[key], refCaps)) { return false; } } return true; } // check the individual cap if (Basic.typeOf(refCaps[cap]) === 'function') { return refCaps[cap].call(this, value); } else { return (value === refCaps[cap]); } }, /** Returns container for the runtime as DOM element @method getShimContainer @return {DOMElement} */ getShimContainer: function() { var container, shimContainer = Dom.get(this.shimid); // if no container for shim, create one if (!shimContainer) { container = this.options.container ? Dom.get(this.options.container) : document.body; // create shim container and insert it at an absolute position into the outer container shimContainer = document.createElement('div'); shimContainer.id = this.shimid; shimContainer.className = 'moxie-shim moxie-shim-' + this.type; Basic.extend(shimContainer.style, { position: 'absolute', top: '0px', left: '0px', width: '1px', height: '1px', overflow: 'hidden' }); container.appendChild(shimContainer); container = null; } return shimContainer; }, /** Returns runtime as DOM element (if appropriate) @method getShim @return {DOMElement} */ getShim: function() { return _shim; }, /** Invokes a method within the runtime itself (might differ across the runtimes) @method shimExec @param {Mixed} [] @protected @return {Mixed} Depends on the action and component */ shimExec: function(component, action) { var args = [].slice.call(arguments, 2); return self.getShim().exec.call(this, this.uid, component, action, args); }, /** Operaional interface that is used by components to invoke specific actions on the runtime (is invoked in the scope of component) @method exec @param {Mixed} []* @protected @return {Mixed} Depends on the action and component */ exec: function(component, action) { // this is called in the context of component, not runtime var args = [].slice.call(arguments, 2); if (self[component] && self[component][action]) { return self[component][action].apply(this, args); } return self.shimExec.apply(this, arguments); }, /** Destroys the runtime (removes all events and deletes DOM structures) @method destroy */ destroy: function() { if (!self) { return; // obviously already destroyed } var shimContainer = Dom.get(this.shimid); if (shimContainer) { shimContainer.parentNode.removeChild(shimContainer); } if (_shim) { _shim.removeAllInstances(); } this.unbindAll(); delete runtimes[this.uid]; this.uid = null; // mark this runtime as destroyed _uid = self = _shim = shimContainer = null; } }); _setMode.call(this, modeCaps, defaultMode); } /** Default order to try different runtime types @property order @type String @static */ Runtime.order = 'html5,flash,silverlight,html4'; /** Retrieves runtime from private hash by it's uid @method getRuntime @private @static @param {String} uid Unique identifier of the runtime @return {Runtime|Boolean} Returns runtime, if it exists and false, if - not */ Runtime.getRuntime = function(uid) { return runtimes[uid] ? runtimes[uid] : false; }; /** Register constructor for the Runtime of new (or perhaps modified) type @method addConstructor @static @param {String} type Runtime type (e.g. flash, html5, etc) @param {Function} construct Constructor for the Runtime type */ Runtime.addConstructor = function(type, constructor) { constructor.prototype = EventTarget.instance; runtimeConstructors[type] = constructor; }; /** Get the constructor for the specified type. method getConstructor @static @param {String} type Runtime type (e.g. flash, html5, etc) @return {Function} Constructor for the Runtime type */ Runtime.getConstructor = function(type) { return runtimeConstructors[type] || null; }; /** Get info about the runtime (uid, type, capabilities) @method getInfo @static @param {String} uid Unique identifier of the runtime @return {Mixed} Info object or null if runtime doesn't exist */ Runtime.getInfo = function(uid) { var runtime = Runtime.getRuntime(uid); if (runtime) { return { uid: runtime.uid, type: runtime.type, can: function() { return runtime.can.apply(runtime, arguments); } }; } return null; }; /** Convert caps represented by a comma-separated string to the object representation. @method parseCaps @static @param {String} capStr Comma-separated list of capabilities @return {Object} */ Runtime.parseCaps = function(capStr) { var capObj = {}; if (Basic.typeOf(capStr) !== 'string') { return capStr || {}; } Basic.each(capStr.split(','), function(key) { capObj[key] = true; // we assume it to be - true }); return capObj; }; /** Test the specified runtime for specific capabilities. @method can @static @param {String} type Runtime type (e.g. flash, html5, etc) @param {String|Object} caps Set of capabilities to check @return {Boolean} Result of the test */ Runtime.can = function(type, caps) { var runtime , constructor = Runtime.getConstructor(type) , mode ; if (constructor) { runtime = new constructor({ required_caps: caps }); mode = runtime.mode; runtime.destroy(); return !!mode; } return false; }; /** Figure out a runtime that supports specified capabilities. @method thatCan @static @param {String|Object} caps Set of capabilities to check @param {String} [runtimeOrder] Comma-separated list of runtimes to check against @return {String} Usable runtime identifier or null */ Runtime.thatCan = function(caps, runtimeOrder) { var types = (runtimeOrder || Runtime.order).split(/\s*,\s*/); for (var i in types) { if (Runtime.can(types[i], caps)) { return types[i]; } } return null; }; /** Capability check that always returns true @private @static @return {True} */ Runtime.capTrue = function() { return true; }; /** Capability check that always returns false @private @static @return {False} */ Runtime.capFalse = function() { return false; }; /** Evaluate the expression to boolean value and create a function that always returns it. @private @static @param {Mixed} expr Expression to evaluate @return {Function} Function returning the result of evaluation */ Runtime.capTest = function(expr) { return function() { return !!expr; }; }; return Runtime; }); // Included from: src/javascript/runtime/RuntimeClient.js /** * RuntimeClient.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/runtime/RuntimeClient', [ 'moxie/core/Exceptions', 'moxie/core/utils/Basic', 'moxie/runtime/Runtime' ], function(x, Basic, Runtime) { /** Set of methods and properties, required by a component to acquire ability to connect to a runtime @class RuntimeClient */ return function RuntimeClient() { var runtime; Basic.extend(this, { /** Connects to the runtime specified by the options. Will either connect to existing runtime or create a new one. Increments number of clients connected to the specified runtime. @method connectRuntime @param {Mixed} options Can be a runtme uid or a set of key-value pairs defining requirements and pre-requisites */ connectRuntime: function(options) { var comp = this, ruid; function initialize(items) { var type, constructor; // if we ran out of runtimes if (!items.length) { comp.trigger('RuntimeError', new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR)); runtime = null; return; } type = items.shift(); constructor = Runtime.getConstructor(type); if (!constructor) { initialize(items); return; } // try initializing the runtime runtime = new constructor(options); //alert(runtime); runtime.bind('Init', function() { // mark runtime as initialized runtime.initialized = true; // jailbreak ... setTimeout(function() { runtime.clients++; // this will be triggered on component comp.trigger('RuntimeInit', runtime); }, 200); }); runtime.bind('Error', function() { runtime.destroy(); // runtime cannot destroy itself from inside at a right moment, thus we do it here initialize(items); }); /*runtime.bind('Exception', function() { });*/ // check if runtime managed to pick-up operational mode if (!runtime.mode) { runtime.trigger('Error'); return; } setTimeout(function(){ runtime.init(); },200); } // check if a particular runtime was requested if (Basic.typeOf(options) === 'string') { ruid = options; } else if (Basic.typeOf(options.ruid) === 'string') { ruid = options.ruid; } if (ruid) { runtime = Runtime.getRuntime(ruid); if (runtime) { runtime.clients++; return runtime; } else { // there should be a runtime and there's none - weird case throw new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR); } } // initialize a fresh one, that fits runtime list and required features best initialize((options.runtime_order || Runtime.order).split(/\s*,\s*/)); }, /** Returns the runtime to which the client is currently connected. @method getRuntime @return {Runtime} Runtime or null if client is not connected */ getRuntime: function() { if (runtime && runtime.uid) { return runtime; } runtime = null; // make sure we do not leave zombies rambling around return null; }, /** Disconnects from the runtime. Decrements number of clients connected to the specified runtime. @method disconnectRuntime */ disconnectRuntime: function() { if (runtime && --runtime.clients <= 0) { runtime.destroy(); runtime = null; } } }); }; }); // Included from: src/javascript/file/Blob.js /** * Blob.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/Blob', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Encode', 'moxie/runtime/RuntimeClient' ], function(Basic, Encode, RuntimeClient) { var blobpool = {}; /** @class Blob @constructor @param {String} ruid Unique id of the runtime, to which this blob belongs to @param {Object} blob Object "Native" blob object, as it is represented in the runtime */ function Blob(ruid, blob) { function _sliceDetached(start, end, type) { var blob, data = blobpool[this.uid]; if (Basic.typeOf(data) !== 'string' || !data.length) { return null; // or throw exception } blob = new Blob(null, { type: type, size: end - start }); blob.detach(data.substr(start, blob.size)); return blob; } RuntimeClient.call(this); if (ruid) { this.connectRuntime(ruid); } if (!blob) { blob = {}; } else if (Basic.typeOf(blob) === 'string') { // dataUrl or binary string blob = { data: blob }; } Basic.extend(this, { /** Unique id of the component @property uid @type {String} */ uid: blob.uid || Basic.guid('uid_'), /** Unique id of the connected runtime, if falsy, then runtime will have to be initialized before this Blob can be used, modified or sent @property ruid @type {String} */ ruid: ruid, /** Size of blob @property size @type {Number} @default 0 */ size: blob.size || 0, /** Mime type of blob @property type @type {String} @default '' */ type: blob.type || '', /** @method slice @param {Number} [start=0] */ slice: function(start, end, type) { if (this.isDetached()) { return _sliceDetached.apply(this, arguments); } return this.getRuntime().exec.call(this, 'Blob', 'slice', this.getSource(), start, end, type); }, /** Returns "native" blob object (as it is represented in connected runtime) or null if not found @method getSource @return {Blob} Returns "native" blob object or null if not found */ getSource: function() { if (!blobpool[this.uid]) { return null; } return blobpool[this.uid]; }, /** Detaches blob from any runtime that it depends on and initialize with standalone value @method detach @protected @param {DOMString} [data=''] Standalone value */ detach: function(data) { if (this.ruid) { this.getRuntime().exec.call(this, 'Blob', 'destroy', blobpool[this.uid]); this.disconnectRuntime(); this.ruid = null; } data = data || ''; // if dataUrl, convert to binary string var matches = data.match(/^data:([^;]*);base64,/); if (matches) { this.type = matches[1]; data = Encode.atob(data.substring(data.indexOf('base64,') + 7)); } this.size = data.length; blobpool[this.uid] = data; }, /** Checks if blob is standalone (detached of any runtime) @method isDetached @protected @return {Boolean} */ isDetached: function() { return !this.ruid && Basic.typeOf(blobpool[this.uid]) === 'string'; }, /** Destroy Blob and free any resources it was using @method destroy */ destroy: function() { this.detach(); delete blobpool[this.uid]; } }); if (blob.data) { this.detach(blob.data); // auto-detach if payload has been passed } else { blobpool[this.uid] = blob; } } return Blob; }); // Included from: src/javascript/file/File.js /** * File.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/File', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Mime', 'moxie/file/Blob' ], function(Basic, Mime, Blob) { /** @class File @extends Blob @constructor @param {String} ruid Unique id of the runtime, to which this blob belongs to @param {Object} file Object "Native" file object, as it is represented in the runtime */ function File(ruid, file) { var name, type; if (!file) { // avoid extra errors in case we overlooked something file = {}; } // figure out the type if (file.type && file.type !== '') { type = file.type; } else { type = Mime.getFileMime(file.name); } // sanitize file name or generate new one if (file.name) { name = file.name.replace(/\\/g, '/'); name = name.substr(name.lastIndexOf('/') + 1); } else { var prefix = type.split('/')[0]; name = Basic.guid((prefix !== '' ? prefix : 'file') + '_'); if (Mime.extensions[type]) { name += '.' + Mime.extensions[type][0]; // append proper extension if possible } } Blob.apply(this, arguments); Basic.extend(this, { /** File mime type @property type @type {String} @default '' */ type: type || '', /** File name @property name @type {String} @default UID */ name: name || Basic.guid('file_'), /** Date of last modification @property lastModifiedDate @type {String} @default now */ lastModifiedDate: file.lastModifiedDate || (new Date()).toLocaleString() // Thu Aug 23 2012 19:40:00 GMT+0400 (GET) }); } File.prototype = Blob.prototype; return File; }); // Included from: src/javascript/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/FileInput', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Mime', 'moxie/core/utils/Dom', 'moxie/core/Exceptions', 'moxie/core/EventTarget', 'moxie/core/I18n', 'moxie/file/File', 'moxie/runtime/Runtime', 'moxie/runtime/RuntimeClient' ], function(Basic, Mime, Dom, x, EventTarget, I18n, File, Runtime, RuntimeClient) { /** Provides a convenient way to create cross-browser file-picker. Generates file selection dialog on click, converts selected files to _File_ objects, to be used in conjunction with _Image_, preloaded in memory with _FileReader_ or uploaded to a server through _XMLHttpRequest_. @class FileInput @constructor @extends EventTarget @uses RuntimeClient @param {Object|String|DOMElement} options If options is string or node, argument is considered as _browse\_button_. @param {String|DOMElement} options.browse_button DOM Element to turn into file picker. @param {Array} [options.accept] Array of mime types to accept. By default accepts all. @param {String} [options.file='file'] Name of the file field (not the filename). @param {Boolean} [options.multiple=false] Enable selection of multiple files. @param {Boolean} [options.directory=false] Turn file input into the folder input (cannot be both at the same time). @param {String|DOMElement} [options.container] DOM Element to use as a container for file-picker. Defaults to parentNode for _browse\_button_. @param {Object|String} [options.required_caps] Set of required capabilities, that chosen runtime must support. @example <div id="container"> <a id="file-picker" href="javascript:;">Browse...</a> </div> <script> var fileInput = new mOxie.FileInput({ browse_button: 'file-picker', // or document.getElementById('file-picker') container: 'container', accept: [ {title: "Image files", extensions: "jpg,gif,png"} // accept only images ], multiple: true // allow multiple file selection }); fileInput.onchange = function(e) { // do something to files array //console.info(e.target.files); // or this.files or fileInput.files }; fileInput.init(); // initialize </script> */ var dispatches = [ /** Dispatched when runtime is connected and file-picker is ready to be used. @event ready @param {Object} event */ 'ready', /** Dispatched right after [ready](#event_ready) event, and whenever [refresh()](#method_refresh) is invoked. Check [corresponding documentation entry](#method_refresh) for more info. @event refresh @param {Object} event */ /** Dispatched when selection of files in the dialog is complete. @event change @param {Object} event */ 'change', 'cancel', // TODO: might be useful /** Dispatched when mouse cursor enters file-picker area. Can be used to style element accordingly. @event mouseenter @param {Object} event */ 'mouseenter', /** Dispatched when mouse cursor leaves file-picker area. Can be used to style element accordingly. @event mouseleave @param {Object} event */ 'mouseleave', /** Dispatched when functional mouse button is pressed on top of file-picker area. @event mousedown @param {Object} event */ 'mousedown', /** Dispatched when functional mouse button is released on top of file-picker area. @event mouseup @param {Object} event */ 'mouseup' ]; function FileInput(options) { var self = this, container, browseButton, defaults; // if flat argument passed it should be browse_button id if (Basic.inArray(Basic.typeOf(options), ['string', 'node']) !== -1) { options = { browse_button : options }; } // this will help us to find proper default container browseButton = Dom.get(options.browse_button); if (!browseButton) { // browse button is required throw new x.DOMException(x.DOMException.NOT_FOUND_ERR); } // figure out the options defaults = { accept: [{ title: I18n.translate('All Files'), extensions: '*' }], name: 'file', multiple: false, required_caps: false, container: browseButton.parentNode || document.body }; options = Basic.extend({}, defaults, options); // convert to object representation if (typeof(options.required_caps) === 'string') { options.required_caps = Runtime.parseCaps(options.required_caps); } // normalize accept option (could be list of mime types or array of title/extensions pairs) if (typeof(options.accept) === 'string') { options.accept = Mime.mimes2extList(options.accept); } container = Dom.get(options.container); // make sure we have container if (!container) { container = document.body; } // make container relative, if it's not if (Dom.getStyle(container, 'position') === 'static') { container.style.position = 'relative'; } container = browseButton = null; // IE RuntimeClient.call(self); Basic.extend(self, { /** Unique id of the component @property uid @protected @readOnly @type {String} @default UID */ uid: Basic.guid('uid_'), /** Unique id of the connected runtime, if any. @property ruid @protected @type {String} */ ruid: null, /** Array of selected mOxie.File objects @property files @type {Array} @default null */ files: null, /** Initializes the file-picker, connects it to runtime and dispatches event ready when done. @method init */ init: function() { self.convertEventPropsToHandlers(dispatches); self.bind('RuntimeInit', function(e, runtime) { self.ruid = runtime.uid; self.bind("Ready", function() { self.trigger("Refresh"); }, 999); self.bind("Change", function() { var files = runtime.exec.call(self, 'FileInput', 'getFiles'); self.files = []; Basic.each(files, function(file) { // ignore empty files (IE10 for example hangs if you try to send them via XHR) if (file.size === 0) { return true; } self.files.push(new File(self.ruid, file)); }); }, 999); // re-position and resize shim container self.bind('Refresh', function() { var pos, size, browseButton, shimContainer; browseButton = Dom.get(options.browse_button); shimContainer = Dom.get(runtime.shimid); // do not use runtime.getShimContainer(), since it will create container if it doesn't exist if (browseButton) { pos = Dom.getPos(browseButton, Dom.get(options.container)); size = Dom.getSize(browseButton); if (shimContainer) { Basic.extend(shimContainer.style, { top : pos.y + 'px', left : pos.x + 'px', width : size.w + 'px', height : size.h + 'px' }); } } shimContainer = browseButton = null; }); runtime.exec.call(self, 'FileInput', 'init', options); }); // runtime needs: options.required_features, options.runtime_order and options.container self.connectRuntime(Basic.extend({}, options, { required_caps: { select_file: true } })); }, /** Disables file-picker element, so that it doesn't react to mouse clicks. @method disable @param {Boolean} [state=true] Disable component if - true, enable if - false */ disable: function(state) { var runtime = this.getRuntime(); if (runtime) { runtime.exec.call(this, 'FileInput', 'disable', Basic.typeOf(state) === 'undefined' ? true : state); } }, /** Reposition and resize dialog trigger to match the position and size of browse_button element. @method refresh */ refresh: function() { self.trigger("Refresh"); }, /** Destroy component. @method destroy */ destroy: function() { var runtime = this.getRuntime(); if (runtime) { runtime.exec.call(this, 'FileInput', 'destroy'); this.disconnectRuntime(); } if (Basic.typeOf(this.files) === 'array') { // no sense in leaving associated files behind Basic.each(this.files, function(file) { file.destroy(); }); } this.files = null; } }); } FileInput.prototype = EventTarget.instance; return FileInput; }); // Included from: src/javascript/file/FileDrop.js /** * FileDrop.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/FileDrop', [ 'moxie/core/I18n', 'moxie/core/utils/Dom', 'moxie/core/Exceptions', 'moxie/core/utils/Basic', 'moxie/file/File', 'moxie/runtime/RuntimeClient', 'moxie/core/EventTarget', 'moxie/core/utils/Mime' ], function(I18n, Dom, x, Basic, File, RuntimeClient, EventTarget, Mime) { /** Turn arbitrary DOM element to a drop zone accepting files. Converts selected files to _File_ objects, to be used in conjunction with _Image_, preloaded in memory with _FileReader_ or uploaded to a server through _XMLHttpRequest_. @example <div id="drop_zone"> Drop files here </div> <br /> <div id="filelist"></div> <script type="text/javascript"> var fileDrop = new mOxie.FileDrop('drop_zone'), fileList = mOxie.get('filelist'); fileDrop.ondrop = function() { mOxie.each(this.files, function(file) { fileList.innerHTML += '<div>' + file.name + '</div>'; }); }; fileDrop.init(); </script> @class FileDrop @constructor @extends EventTarget @uses RuntimeClient @param {Object|String} options If options has typeof string, argument is considered as options.drop_zone @param {String|DOMElement} options.drop_zone DOM Element to turn into a drop zone @param {Array} [options.accept] Array of mime types to accept. By default accepts all @param {Object|String} [options.required_caps] Set of required capabilities, that chosen runtime must support */ var dispatches = [ /** Dispatched when runtime is connected and drop zone is ready to accept files. @event ready @param {Object} event */ 'ready', /** Dispatched when dragging cursor enters the drop zone. @event dragenter @param {Object} event */ 'dragenter', /** Dispatched when dragging cursor leaves the drop zone. @event dragleave @param {Object} event */ 'dragleave', /** Dispatched when file is dropped onto the drop zone. @event drop @param {Object} event */ 'drop', /** Dispatched if error occurs. @event error @param {Object} event */ 'error' ]; function FileDrop(options) { var self = this, defaults; // if flat argument passed it should be drop_zone id if (typeof(options) === 'string') { options = { drop_zone : options }; } // figure out the options defaults = { accept: [{ title: I18n.translate('All Files'), extensions: '*' }], required_caps: { drag_and_drop: true } }; options = typeof(options) === 'object' ? Basic.extend({}, defaults, options) : defaults; // this will help us to find proper default container options.container = Dom.get(options.drop_zone) || document.body; // make container relative, if it is not if (Dom.getStyle(options.container, 'position') === 'static') { options.container.style.position = 'relative'; } // normalize accept option (could be list of mime types or array of title/extensions pairs) if (typeof(options.accept) === 'string') { options.accept = Mime.mimes2extList(options.accept); } RuntimeClient.call(self); Basic.extend(self, { uid: Basic.guid('uid_'), ruid: null, files: null, init: function() { self.convertEventPropsToHandlers(dispatches); self.bind('RuntimeInit', function(e, runtime) { self.ruid = runtime.uid; self.bind("Drop", function() { var files = runtime.exec.call(self, 'FileDrop', 'getFiles'); self.files = []; Basic.each(files, function(file) { self.files.push(new File(self.ruid, file)); }); }, 999); runtime.exec.call(self, 'FileDrop', 'init', options); self.dispatchEvent('ready'); }); // runtime needs: options.required_features, options.runtime_order and options.container self.connectRuntime(options); // throws RuntimeError }, destroy: function() { var runtime = this.getRuntime(); if (runtime) { runtime.exec.call(this, 'FileDrop', 'destroy'); this.disconnectRuntime(); } this.files = null; } }); } FileDrop.prototype = EventTarget.instance; return FileDrop; }); // Included from: src/javascript/runtime/RuntimeTarget.js /** * RuntimeTarget.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/runtime/RuntimeTarget', [ 'moxie/core/utils/Basic', 'moxie/runtime/RuntimeClient', "moxie/core/EventTarget" ], function(Basic, RuntimeClient, EventTarget) { /** Instance of this class can be used as a target for the events dispatched by shims, when allowing them onto components is for either reason inappropriate @class RuntimeTarget @constructor @protected @extends EventTarget */ function RuntimeTarget() { this.uid = Basic.guid('uid_'); RuntimeClient.call(this); this.destroy = function() { this.disconnectRuntime(); this.unbindAll(); }; } RuntimeTarget.prototype = EventTarget.instance; return RuntimeTarget; }); // Included from: src/javascript/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/FileReader', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Encode', 'moxie/core/Exceptions', 'moxie/core/EventTarget', 'moxie/file/Blob', 'moxie/file/File', 'moxie/runtime/RuntimeTarget' ], function(Basic, Encode, x, EventTarget, Blob, File, RuntimeTarget) { /** Utility for preloading o.Blob/o.File objects in memory. By design closely follows [W3C FileReader](http://www.w3.org/TR/FileAPI/#dfn-filereader) interface. Where possible uses native FileReader, where - not falls back to shims. @class FileReader @constructor FileReader @extends EventTarget @uses RuntimeClient */ var dispatches = [ /** Dispatched when the read starts. @event loadstart @param {Object} event */ 'loadstart', /** Dispatched while reading (and decoding) blob, and reporting partial Blob data (progess.loaded/progress.total). @event progress @param {Object} event */ 'progress', /** Dispatched when the read has successfully completed. @event load @param {Object} event */ 'load', /** Dispatched when the read has been aborted. For instance, by invoking the abort() method. @event abort @param {Object} event */ 'abort', /** Dispatched when the read has failed. @event error @param {Object} event */ 'error', /** Dispatched when the request has completed (either in success or failure). @event loadend @param {Object} event */ 'loadend' ]; function FileReader() { var self = this, _fr; Basic.extend(this, { /** UID of the component instance. @property uid @type {String} */ uid: Basic.guid('uid_'), /** Contains current state of FileReader object. Can take values of FileReader.EMPTY, FileReader.LOADING and FileReader.DONE. @property readyState @type {Number} @default FileReader.EMPTY */ readyState: FileReader.EMPTY, /** Result of the successful read operation. @property result @type {String} */ result: null, /** Stores the error of failed asynchronous read operation. @property error @type {DOMError} */ error: null, /** Initiates reading of File/Blob object contents to binary string. @method readAsBinaryString @param {Blob|File} blob Object to preload */ readAsBinaryString: function(blob) { _read.call(this, 'readAsBinaryString', blob); }, /** Initiates reading of File/Blob object contents to dataURL string. @method readAsDataURL @param {Blob|File} blob Object to preload */ readAsDataURL: function(blob) { _read.call(this, 'readAsDataURL', blob); }, /** Initiates reading of File/Blob object contents to string. @method readAsText @param {Blob|File} blob Object to preload */ readAsText: function(blob) { _read.call(this, 'readAsText', blob); }, /** Aborts preloading process. @method abort */ abort: function() { this.result = null; if (Basic.inArray(this.readyState, [FileReader.EMPTY, FileReader.DONE]) !== -1) { return; } else if (this.readyState === FileReader.LOADING) { this.readyState = FileReader.DONE; } if (_fr) { _fr.getRuntime().exec.call(this, 'FileReader', 'abort'); } this.trigger('abort'); this.trigger('loadend'); }, /** Destroy component and release resources. @method destroy */ destroy: function() { this.abort(); if (_fr) { _fr.getRuntime().exec.call(this, 'FileReader', 'destroy'); _fr.disconnectRuntime(); } self = _fr = null; } }); function _read(op, blob) { _fr = new RuntimeTarget(); function error(err) { self.readyState = FileReader.DONE; self.error = err; self.trigger('error'); loadEnd(); } function loadEnd() { _fr.destroy(); _fr = null; self.trigger('loadend'); } function exec(runtime) { _fr.bind('Error', function(e, err) { error(err); }); _fr.bind('Progress', function(e) { self.result = runtime.exec.call(_fr, 'FileReader', 'getResult'); self.trigger(e); }); _fr.bind('Load', function(e) { self.readyState = FileReader.DONE; self.result = runtime.exec.call(_fr, 'FileReader', 'getResult'); self.trigger(e); loadEnd(); }); runtime.exec.call(_fr, 'FileReader', 'read', op, blob); } this.convertEventPropsToHandlers(dispatches); if (this.readyState === FileReader.LOADING) { return error(new x.DOMException(x.DOMException.INVALID_STATE_ERR)); } this.readyState = FileReader.LOADING; this.trigger('loadstart'); // if source is o.Blob/o.File if (blob instanceof Blob) { if (blob.isDetached()) { var src = blob.getSource(); switch (op) { case 'readAsText': case 'readAsBinaryString': this.result = src; break; case 'readAsDataURL': this.result = 'data:' + blob.type + ';base64,' + Encode.btoa(src); break; } this.readyState = FileReader.DONE; this.trigger('load'); loadEnd(); } else { exec(_fr.connectRuntime(blob.ruid)); } } else { error(new x.DOMException(x.DOMException.NOT_FOUND_ERR)); } } } /** Initial FileReader state @property EMPTY @type {Number} @final @static @default 0 */ FileReader.EMPTY = 0; /** FileReader switches to this state when it is preloading the source @property LOADING @type {Number} @final @static @default 1 */ FileReader.LOADING = 1; /** Preloading is complete, this is a final state @property DONE @type {Number} @final @static @default 2 */ FileReader.DONE = 2; FileReader.prototype = EventTarget.instance; return FileReader; }); // Included from: src/javascript/core/utils/Url.js /** * Url.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Url', [], function() { /** Parse url into separate components and fill in absent parts with parts from current url, based on https://raw.github.com/kvz/phpjs/master/functions/url/parse_url.js @method parseUrl @for Utils @static @param {String} str Url to parse (defaults to empty string if undefined) @return {Object} Hash containing extracted uri components */ var parseUrl = function(str) { var key = ['source', 'scheme', 'authority', 'userInfo', 'user', 'pass', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'fragment'] , i = key.length , ports = { http: 80, https: 443 } , uri = {} , regex = /^(?:([^:\/?#]+):)?(?:\/\/()(?:(?:()(?:([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?()(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\\?([^#]*))?(?:#(.*))?)/ , m = regex.exec(str || '') // default to empty string if undefined ; while (i--) { if (m[i]) { uri[key[i]] = m[i]; } } if (/^[^\/]/.test(uri.path) && !uri.scheme) { // when url is relative, we need to figure out the path ourselves var path = document.location.pathname; // if path ends with a filename, strip it if (!/(\/|\/[^\.]+)$/.test(path)) { path = path.replace(/[^\/]+$/, ''); } uri.host = document.location.hostname; uri.path = path + (uri.path || ''); // site may reside at domain.com or domain.com/subdir } if (!uri.scheme) { uri.scheme = document.location.protocol.replace(/:$/, ''); } if (!uri.host) { uri.host = document.location.hostname; } if (!uri.port) { uri.port = document.location.port || ports[uri.scheme] || 80; } uri.port = parseInt(uri.port, 10); if (!uri.path) { uri.path = "/"; } delete uri.source; return uri; }; /** Resolve url - among other things will turn relative url to absolute @method resolveUrl @static @param {String} url Either absolute or relative @return {String} Resolved, absolute url */ var resolveUrl = function(url) { var ports = { // we ignore default ports http: 80, https: 443 } , urlp = parseUrl(url) ; return urlp.scheme + '://' + urlp.host + (urlp.port !== ports[urlp.scheme] ? ':' + urlp.port : '') + urlp.path + (urlp.query ? urlp.query : ''); }; /** Check if specified url has the same origin as the current document @method hasSameOrigin @param {String|Object} url @return {Boolean} */ var hasSameOrigin = function(url) { function origin(url) { return [url.scheme, url.host, url.port].join('/'); } if (typeof url === 'string') { url = parseUrl(url); } return origin(parseUrl()) === origin(url); }; return { parseUrl: parseUrl, resolveUrl: resolveUrl, hasSameOrigin: hasSameOrigin }; }); // Included from: src/javascript/file/FileReaderSync.js /** * FileReaderSync.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/FileReaderSync', [ 'moxie/core/utils/Basic', 'moxie/runtime/RuntimeClient', 'moxie/core/utils/Encode' ], function(Basic, RuntimeClient, Encode) { /** Synchronous FileReader implementation. Something like this is available in WebWorkers environment, here it can be used to read only preloaded blobs/files and only below certain size (not yet sure what that'd be, but probably < 1mb). Not meant to be used directly by user. @class FileReaderSync @private @constructor */ return function() { RuntimeClient.call(this); Basic.extend(this, { uid: Basic.guid('uid_'), readAsBinaryString: function(blob) { return _read.call(this, 'readAsBinaryString', blob); }, readAsDataURL: function(blob) { return _read.call(this, 'readAsDataURL', blob); }, /*readAsArrayBuffer: function(blob) { return _read.call(this, 'readAsArrayBuffer', blob); },*/ readAsText: function(blob) { return _read.call(this, 'readAsText', blob); } }); function _read(op, blob) { if (blob.isDetached()) { var src = blob.getSource(); switch (op) { case 'readAsBinaryString': return src; case 'readAsDataURL': return 'data:' + blob.type + ';base64,' + Encode.btoa(src); case 'readAsText': var txt = ''; for (var i = 0, length = src.length; i < length; i++) { txt += String.fromCharCode(src[i]); } return txt; } } else { var result = this.connectRuntime(blob.ruid).exec.call(this, 'FileReaderSync', 'read', op, blob); this.disconnectRuntime(); return result; } } }; }); // Included from: src/javascript/xhr/FormData.js /** * FormData.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/xhr/FormData", [ "moxie/core/Exceptions", "moxie/core/utils/Basic", "moxie/file/Blob" ], function(x, Basic, Blob) { /** FormData @class FormData @constructor */ function FormData() { var _blobField, _fields = {}, _name = ""; Basic.extend(this, { /** Append another key-value pair to the FormData object @method append @param {String} name Name for the new field @param {String|Blob|Array|Object} value Value for the field */ append: function(name, value) { var self = this, valueType = Basic.typeOf(value); if (value instanceof Blob) { if (_blobField) { delete _fields[_blobField]; } _blobField = name; _fields[name] = [value]; // unfortunately we can only send single Blob in one FormData } else if ('array' === valueType) { name += '[]'; Basic.each(value, function(value) { self.append.call(self, name, value); }); } else if ('object' === valueType) { Basic.each(value, function(value, key) { self.append.call(self, name + '[' + key + ']', value); }); } else { value = value.toString(); // according to specs value might be either Blob or String if (!_fields[name]) { _fields[name] = []; } _fields[name].push(value); } }, /** Checks if FormData contains Blob. @method hasBlob @return {Boolean} */ hasBlob: function() { return !!_blobField; }, /** Retrieves blob. @method getBlob @return {Object} Either Blob if found or null */ getBlob: function() { return _fields[_blobField] && _fields[_blobField][0] || null; }, /** Retrieves blob field name. @method getBlobName @return {String} Either Blob field name or null */ getBlobName: function() { return _blobField || null; }, /** Loop over the fields in FormData and invoke the callback for each of them. @method each @param {Function} cb Callback to call for each field */ each: function(cb) { Basic.each(_fields, function(value, name) { Basic.each(value, function(value) { cb(value, name); }); }); }, destroy: function() { _blobField = null; _name = ""; _fields = {}; } }); } return FormData; }); // Included from: src/javascript/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/xhr/XMLHttpRequest", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/core/EventTarget", "moxie/core/utils/Encode", "moxie/core/utils/Url", "moxie/runtime/Runtime", "moxie/runtime/RuntimeTarget", "moxie/file/Blob", "moxie/file/FileReaderSync", "moxie/xhr/FormData", "moxie/core/utils/Env", "moxie/core/utils/Mime" ], function(Basic, x, EventTarget, Encode, Url, Runtime, RuntimeTarget, Blob, FileReaderSync, FormData, Env, Mime) { var httpCode = { 100: 'Continue', 101: 'Switching Protocols', 102: 'Processing', 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-Authoritative Information', 204: 'No Content', 205: 'Reset Content', 206: 'Partial Content', 207: 'Multi-Status', 226: 'IM Used', 300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Found', 303: 'See Other', 304: 'Not Modified', 305: 'Use Proxy', 306: 'Reserved', 307: 'Temporary Redirect', 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Timeout', 409: 'Conflict', 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 413: 'Request Entity Too Large', 414: 'Request-URI Too Long', 415: 'Unsupported Media Type', 416: 'Requested Range Not Satisfiable', 417: 'Expectation Failed', 422: 'Unprocessable Entity', 423: 'Locked', 424: 'Failed Dependency', 426: 'Upgrade Required', 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout', 505: 'HTTP Version Not Supported', 506: 'Variant Also Negotiates', 507: 'Insufficient Storage', 510: 'Not Extended' }; function XMLHttpRequestUpload() { this.uid = Basic.guid('uid_'); } XMLHttpRequestUpload.prototype = EventTarget.instance; /** Implementation of XMLHttpRequest @class XMLHttpRequest @constructor @uses RuntimeClient @extends EventTarget */ var dispatches = ['loadstart', 'progress', 'abort', 'error', 'load', 'timeout', 'loadend']; // & readystatechange (for historical reasons) var NATIVE = 1, RUNTIME = 2; function XMLHttpRequest() { var self = this, // this (together with _p() @see below) is here to gracefully upgrade to setter/getter syntax where possible props = { /** The amount of milliseconds a request can take before being terminated. Initially zero. Zero means there is no timeout. @property timeout @type Number @default 0 */ timeout: 0, /** Current state, can take following values: UNSENT (numeric value 0) The object has been constructed. OPENED (numeric value 1) The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method. HEADERS_RECEIVED (numeric value 2) All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available. LOADING (numeric value 3) The response entity body is being received. DONE (numeric value 4) @property readyState @type Number @default 0 (UNSENT) */ readyState: XMLHttpRequest.UNSENT, /** True when user credentials are to be included in a cross-origin request. False when they are to be excluded in a cross-origin request and when cookies are to be ignored in its response. Initially false. @property withCredentials @type Boolean @default false */ withCredentials: false, /** Returns the HTTP status code. @property status @type Number @default 0 */ status: 0, /** Returns the HTTP status text. @property statusText @type String */ statusText: "", /** Returns the response type. Can be set to change the response type. Values are: the empty string (default), "arraybuffer", "blob", "document", "json", and "text". @property responseType @type String */ responseType: "", /** Returns the document response entity body. Throws an "InvalidStateError" exception if responseType is not the empty string or "document". @property responseXML @type Document */ responseXML: null, /** Returns the text response entity body. Throws an "InvalidStateError" exception if responseType is not the empty string or "text". @property responseText @type String */ responseText: null, /** Returns the response entity body (http://www.w3.org/TR/XMLHttpRequest/#response-entity-body). Can become: ArrayBuffer, Blob, Document, JSON, Text @property response @type Mixed */ response: null }, _async = true, _url, _method, _headers = {}, _user, _password, _encoding = null, _mimeType = null, // flags _sync_flag = false, _send_flag = false, _upload_events_flag = false, _upload_complete_flag = false, _error_flag = false, _same_origin_flag = false, // times _start_time, _timeoutset_time, _finalMime = null, _finalCharset = null, _options = {}, _xhr, _responseHeaders = '', _responseHeadersBag ; Basic.extend(this, props, { /** Unique id of the component @property uid @type String */ uid: Basic.guid('uid_'), /** Target for Upload events @property upload @type XMLHttpRequestUpload */ upload: new XMLHttpRequestUpload(), /** Sets the request method, request URL, synchronous flag, request username, and request password. Throws a "SyntaxError" exception if one of the following is true: method is not a valid HTTP method. url cannot be resolved. url contains the "user:password" format in the userinfo production. Throws a "SecurityError" exception if method is a case-insensitive match for CONNECT, TRACE or TRACK. Throws an "InvalidAccessError" exception if one of the following is true: Either user or password is passed as argument and the origin of url does not match the XMLHttpRequest origin. There is an associated XMLHttpRequest document and either the timeout attribute is not zero, the withCredentials attribute is true, or the responseType attribute is not the empty string. @method open @param {String} method HTTP method to use on request @param {String} url URL to request @param {Boolean} [async=true] If false request will be done in synchronous manner. Asynchronous by default. @param {String} [user] Username to use in HTTP authentication process on server-side @param {String} [password] Password to use in HTTP authentication process on server-side */ open: function(method, url, async, user, password) { var urlp; // first two arguments are required if (!method || !url) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 2 - check if any code point in method is higher than U+00FF or after deflating method it does not match the method if (/[\u0100-\uffff]/.test(method) || Encode.utf8_encode(method) !== method) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 3 if (!!~Basic.inArray(method.toUpperCase(), ['CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'TRACE', 'TRACK'])) { _method = method.toUpperCase(); } // 4 - allowing these methods poses a security risk if (!!~Basic.inArray(_method, ['CONNECT', 'TRACE', 'TRACK'])) { throw new x.DOMException(x.DOMException.SECURITY_ERR); } // 5 url = Encode.utf8_encode(url); // 6 - Resolve url relative to the XMLHttpRequest base URL. If the algorithm returns an error, throw a "SyntaxError". urlp = Url.parseUrl(url); _same_origin_flag = Url.hasSameOrigin(urlp); // 7 - manually build up absolute url _url = Url.resolveUrl(url); // 9-10, 12-13 if ((user || password) && !_same_origin_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } _user = user || urlp.user; _password = password || urlp.pass; // 11 _async = async || true; if (_async === false && (_p('timeout') || _p('withCredentials') || _p('responseType') !== "")) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // 14 - terminate abort() // 15 - terminate send() // 18 _sync_flag = !_async; _send_flag = false; _headers = {}; _reset.call(this); // 19 _p('readyState', XMLHttpRequest.OPENED); // 20 this.convertEventPropsToHandlers(['readystatechange']); // unify event handlers this.dispatchEvent('readystatechange'); }, /** Appends an header to the list of author request headers, or if header is already in the list of author request headers, combines its value with value. Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set. Throws a "SyntaxError" exception if header is not a valid HTTP header field name or if value is not a valid HTTP header field value. @method setRequestHeader @param {String} header @param {String|Number} value */ setRequestHeader: function(header, value) { var uaHeaders = [ // these headers are controlled by the user agent "accept-charset", "accept-encoding", "access-control-request-headers", "access-control-request-method", "connection", "content-length", "cookie", "cookie2", "content-transfer-encoding", "date", "expect", "host", "keep-alive", "origin", "referer", "te", "trailer", "transfer-encoding", "upgrade", "user-agent", "via" ]; // 1-2 if (_p('readyState') !== XMLHttpRequest.OPENED || _send_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 3 if (/[\u0100-\uffff]/.test(header) || Encode.utf8_encode(header) !== header) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 4 /* this step is seemingly bypassed in browsers, probably to allow various unicode characters in header values if (/[\u0100-\uffff]/.test(value) || Encode.utf8_encode(value) !== value) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); }*/ header = Basic.trim(header).toLowerCase(); // setting of proxy-* and sec-* headers is prohibited by spec if (!!~Basic.inArray(header, uaHeaders) || /^(proxy\-|sec\-)/.test(header)) { return false; } // camelize // browsers lowercase header names (at least for custom ones) // header = header.replace(/\b\w/g, function($1) { return $1.toUpperCase(); }); if (!_headers[header]) { _headers[header] = value; } else { // http://tools.ietf.org/html/rfc2616#section-4.2 (last paragraph) _headers[header] += ', ' + value; } return true; }, /** Returns all headers from the response, with the exception of those whose field name is Set-Cookie or Set-Cookie2. @method getAllResponseHeaders @return {String} reponse headers or empty string */ getAllResponseHeaders: function() { return _responseHeaders || ''; }, /** Returns the header field value from the response of which the field name matches header, unless the field name is Set-Cookie or Set-Cookie2. @method getResponseHeader @param {String} header @return {String} value(s) for the specified header or null */ getResponseHeader: function(header) { header = header.toLowerCase(); if (_error_flag || !!~Basic.inArray(header, ['set-cookie', 'set-cookie2'])) { return null; } if (_responseHeaders && _responseHeaders !== '') { // if we didn't parse response headers until now, do it and keep for later if (!_responseHeadersBag) { _responseHeadersBag = {}; Basic.each(_responseHeaders.split(/\r\n/), function(line) { var pair = line.split(/:\s+/); if (pair.length === 2) { // last line might be empty, omit pair[0] = Basic.trim(pair[0]); // just in case _responseHeadersBag[pair[0].toLowerCase()] = { // simply to retain header name in original form header: pair[0], value: Basic.trim(pair[1]) }; } }); } if (_responseHeadersBag.hasOwnProperty(header)) { return _responseHeadersBag[header].header + ': ' + _responseHeadersBag[header].value; } } return null; }, /** Sets the Content-Type header for the response to mime. Throws an "InvalidStateError" exception if the state is LOADING or DONE. Throws a "SyntaxError" exception if mime is not a valid media type. @method overrideMimeType @param String mime Mime type to set */ overrideMimeType: function(mime) { var matches, charset; // 1 if (!!~Basic.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2 mime = Basic.trim(mime.toLowerCase()); if (/;/.test(mime) && (matches = mime.match(/^([^;]+)(?:;\scharset\=)?(.*)$/))) { mime = matches[1]; if (matches[2]) { charset = matches[2]; } } if (!Mime.mimes[mime]) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 3-4 _finalMime = mime; _finalCharset = charset; }, /** Initiates the request. The optional argument provides the request entity body. The argument is ignored if request method is GET or HEAD. Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set. @method send @param {Blob|Document|String|FormData} [data] Request entity body @param {Object} [options] Set of requirements and pre-requisities for runtime initialization */ send: function(data, options) { if (Basic.typeOf(options) === 'string') { _options = { ruid: options }; } else if (!options) { _options = {}; } else { _options = options; } this.convertEventPropsToHandlers(dispatches); this.upload.convertEventPropsToHandlers(dispatches); // 1-2 if (this.readyState !== XMLHttpRequest.OPENED || _send_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 3 // sending Blob if (data instanceof Blob) { _options.ruid = data.ruid; _mimeType = data.type || 'application/octet-stream'; } // FormData else if (data instanceof FormData) { if (data.hasBlob()) { var blob = data.getBlob(); _options.ruid = blob.ruid; _mimeType = blob.type || 'application/octet-stream'; } } // DOMString else if (typeof data === 'string') { _encoding = 'UTF-8'; _mimeType = 'text/plain;charset=UTF-8'; // data should be converted to Unicode and encoded as UTF-8 data = Encode.utf8_encode(data); } // if withCredentials not set, but requested, set it automatically if (!this.withCredentials) { this.withCredentials = (_options.required_caps && _options.required_caps.send_browser_cookies) && !_same_origin_flag; } // 4 - storage mutex // 5 _upload_events_flag = (!_sync_flag && this.upload.hasEventListener()); // DSAP // 6 _error_flag = false; // 7 _upload_complete_flag = !data; // 8 - Asynchronous steps if (!_sync_flag) { // 8.1 _send_flag = true; // 8.2 // this.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr // 8.3 if (!_upload_complete_flag) { // this.upload.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr } } // 8.5 - Return the send() method call, but continue running the steps in this algorithm. _doXHR.call(this, data); }, /** Cancels any network activity. @method abort */ abort: function() { _error_flag = true; _sync_flag = false; if (!~Basic.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED, XMLHttpRequest.DONE])) { _p('readyState', XMLHttpRequest.DONE); _send_flag = false; if (_xhr) { _xhr.getRuntime().exec.call(_xhr, 'XMLHttpRequest', 'abort', _upload_complete_flag); } else { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } _upload_complete_flag = true; } else { _p('readyState', XMLHttpRequest.UNSENT); } }, destroy: function() { if (_xhr) { if (Basic.typeOf(_xhr.destroy) === 'function') { _xhr.destroy(); } _xhr = null; } this.unbindAll(); if (this.upload) { this.upload.unbindAll(); this.upload = null; } } }); /* this is nice, but maybe too lengthy // if supported by JS version, set getters/setters for specific properties o.defineProperty(this, 'readyState', { configurable: false, get: function() { return _p('readyState'); } }); o.defineProperty(this, 'timeout', { configurable: false, get: function() { return _p('timeout'); }, set: function(value) { if (_sync_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // timeout still should be measured relative to the start time of request _timeoutset_time = (new Date).getTime(); _p('timeout', value); } }); // the withCredentials attribute has no effect when fetching same-origin resources o.defineProperty(this, 'withCredentials', { configurable: false, get: function() { return _p('withCredentials'); }, set: function(value) { // 1-2 if (!~o.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED]) || _send_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 3-4 if (_anonymous_flag || _sync_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // 5 _p('withCredentials', value); } }); o.defineProperty(this, 'status', { configurable: false, get: function() { return _p('status'); } }); o.defineProperty(this, 'statusText', { configurable: false, get: function() { return _p('statusText'); } }); o.defineProperty(this, 'responseType', { configurable: false, get: function() { return _p('responseType'); }, set: function(value) { // 1 if (!!~o.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2 if (_sync_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // 3 _p('responseType', value.toLowerCase()); } }); o.defineProperty(this, 'responseText', { configurable: false, get: function() { // 1 if (!~o.inArray(_p('responseType'), ['', 'text'])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2-3 if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } return _p('responseText'); } }); o.defineProperty(this, 'responseXML', { configurable: false, get: function() { // 1 if (!~o.inArray(_p('responseType'), ['', 'document'])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2-3 if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } return _p('responseXML'); } }); o.defineProperty(this, 'response', { configurable: false, get: function() { if (!!~o.inArray(_p('responseType'), ['', 'text'])) { if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) { return ''; } } if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) { return null; } return _p('response'); } }); */ function _p(prop, value) { if (!props.hasOwnProperty(prop)) { return; } if (arguments.length === 1) { // get return Env.can('define_property') ? props[prop] : self[prop]; } else { // set if (Env.can('define_property')) { props[prop] = value; } else { self[prop] = value; } } } /* function _toASCII(str, AllowUnassigned, UseSTD3ASCIIRules) { // TODO: http://tools.ietf.org/html/rfc3490#section-4.1 return str.toLowerCase(); } */ function _doXHR(data) { var self = this; _start_time = new Date().getTime(); _xhr = new RuntimeTarget(); function loadEnd() { _xhr.destroy(); _xhr = null; self.dispatchEvent('loadend'); self = null; } function exec(runtime) { _xhr.bind('LoadStart', function(e) { _p('readyState', XMLHttpRequest.LOADING); self.dispatchEvent('readystatechange'); self.dispatchEvent(e); if (_upload_events_flag) { self.upload.dispatchEvent(e); } }); _xhr.bind('Progress', function(e) { if (_p('readyState') !== XMLHttpRequest.LOADING) { _p('readyState', XMLHttpRequest.LOADING); // LoadStart unreliable (in Flash for example) self.dispatchEvent('readystatechange'); } self.dispatchEvent(e); }); _xhr.bind('UploadProgress', function(e) { if (_upload_events_flag) { self.upload.dispatchEvent({ type: 'progress', lengthComputable: false, total: e.total, loaded: e.loaded }); } }); _xhr.bind('Load', function(e) { _p('readyState', XMLHttpRequest.DONE); _p('status', Number(runtime.exec.call(_xhr, 'XMLHttpRequest', 'getStatus') || 0)); _p('statusText', httpCode[_p('status')] || ""); _p('response', runtime.exec.call(_xhr, 'XMLHttpRequest', 'getResponse', _p('responseType'))); if (!!~Basic.inArray(_p('responseType'), ['text', ''])) { _p('responseText', _p('response')); } else if (_p('responseType') === 'document') { _p('responseXML', _p('response')); } _responseHeaders = runtime.exec.call(_xhr, 'XMLHttpRequest', 'getAllResponseHeaders'); self.dispatchEvent('readystatechange'); if (_p('status') > 0) { // status 0 usually means that server is unreachable if (_upload_events_flag) { self.upload.dispatchEvent(e); } self.dispatchEvent(e); } else { _error_flag = true; self.dispatchEvent('error'); } loadEnd(); }); _xhr.bind('Abort', function(e) { self.dispatchEvent(e); loadEnd(); }); _xhr.bind('Error', function(e) { _error_flag = true; _p('readyState', XMLHttpRequest.DONE); self.dispatchEvent('readystatechange'); _upload_complete_flag = true; self.dispatchEvent(e); loadEnd(); }); runtime.exec.call(_xhr, 'XMLHttpRequest', 'send', { url: _url, method: _method, async: _async, user: _user, password: _password, headers: _headers, mimeType: _mimeType, encoding: _encoding, responseType: self.responseType, withCredentials: self.withCredentials, options: _options }, data); } // clarify our requirements if (typeof(_options.required_caps) === 'string') { _options.required_caps = Runtime.parseCaps(_options.required_caps); } _options.required_caps = Basic.extend({}, _options.required_caps, { return_response_type: self.responseType }); if (data instanceof FormData) { _options.required_caps.send_multipart = true; } if (!_same_origin_flag) { _options.required_caps.do_cors = true; } if (_options.ruid) { // we do not need to wait if we can connect directly exec(_xhr.connectRuntime(_options)); } else { _xhr.bind('RuntimeInit', function(e, runtime) { exec(runtime); }); _xhr.bind('RuntimeError', function(e, err) { self.dispatchEvent('RuntimeError', err); }); _xhr.connectRuntime(_options); } } function _reset() { _p('responseText', ""); _p('responseXML', null); _p('response', null); _p('status', 0); _p('statusText', ""); _start_time = _timeoutset_time = null; } } XMLHttpRequest.UNSENT = 0; XMLHttpRequest.OPENED = 1; XMLHttpRequest.HEADERS_RECEIVED = 2; XMLHttpRequest.LOADING = 3; XMLHttpRequest.DONE = 4; XMLHttpRequest.prototype = EventTarget.instance; return XMLHttpRequest; }); // Included from: src/javascript/runtime/Transporter.js /** * Transporter.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/runtime/Transporter", [ "moxie/core/utils/Basic", "moxie/core/utils/Encode", "moxie/runtime/RuntimeClient", "moxie/core/EventTarget" ], function(Basic, Encode, RuntimeClient, EventTarget) { function Transporter() { var mod, _runtime, _data, _size, _pos, _chunk_size; RuntimeClient.call(this); Basic.extend(this, { uid: Basic.guid('uid_'), state: Transporter.IDLE, result: null, transport: function(data, type, options) { var self = this; options = Basic.extend({ chunk_size: 204798 }, options); // should divide by three, base64 requires this if ((mod = options.chunk_size % 3)) { options.chunk_size += 3 - mod; } _chunk_size = options.chunk_size; _reset.call(this); _data = data; _size = data.length; if (Basic.typeOf(options) === 'string' || options.ruid) { _run.call(self, type, this.connectRuntime(options)); } else { // we require this to run only once var cb = function(e, runtime) { self.unbind("RuntimeInit", cb); _run.call(self, type, runtime); }; this.bind("RuntimeInit", cb); this.connectRuntime(options); } }, abort: function() { var self = this; self.state = Transporter.IDLE; if (_runtime) { _runtime.exec.call(self, 'Transporter', 'clear'); self.trigger("TransportingAborted"); } _reset.call(self); }, destroy: function() { this.unbindAll(); _runtime = null; this.disconnectRuntime(); _reset.call(this); } }); function _reset() { _size = _pos = 0; _data = this.result = null; } function _run(type, runtime) { var self = this; _runtime = runtime; //self.unbind("RuntimeInit"); self.bind("TransportingProgress", function(e) { _pos = e.loaded; if (_pos < _size && Basic.inArray(self.state, [Transporter.IDLE, Transporter.DONE]) === -1) { _transport.call(self); } }, 999); self.bind("TransportingComplete", function() { _pos = _size; self.state = Transporter.DONE; _data = null; // clean a bit self.result = _runtime.exec.call(self, 'Transporter', 'getAsBlob', type || ''); }, 999); self.state = Transporter.BUSY; self.trigger("TransportingStarted"); _transport.call(self); } function _transport() { var self = this, chunk, bytesLeft = _size - _pos; if (_chunk_size > bytesLeft) { _chunk_size = bytesLeft; } chunk = Encode.btoa(_data.substr(_pos, _chunk_size)); _runtime.exec.call(self, 'Transporter', 'receive', chunk, _size); } } Transporter.IDLE = 0; Transporter.BUSY = 1; Transporter.DONE = 2; Transporter.prototype = EventTarget.instance; return Transporter; }); // Included from: src/javascript/core/JSON.js /** * JSON.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*jshint smarttabs:true */ define("moxie/core/JSON", [], function() { /** Parse string into the JSON object in a safe way @credits Douglas Crockford: https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js @method parse @static @protected @param {Object} obj Object to add property to @param {String} prop Property name @param {Object} desc Set of key-value pairs defining descriptor for the property */ return !!window.JSON && JSON.parse || (function() { "use strict"; // This is a function that can parse a JSON text, producing a JavaScript // data structure. It is a simple, recursive descent parser. It does not use // eval or regular expressions, so it can be used as a model for implementing // a JSON parser in other languages. // We are defining the function inside of another function to avoid // creating global variables. var at, // The index of the current character ch, // The current character escapee = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' }, text, error = function (m) { // Call error when something is wrong. throw { name: 'SyntaxError', message: m, at: at, text: text }; }, next = function (c) { // If a c parameter is provided, verify that it matches the current character. if (c && c !== ch) { error("Expected '" + c + "' instead of '" + ch + "'"); } // Get the next character. When there are no more characters, // return the empty string. ch = text.charAt(at); at += 1; return ch; }, number = function () { // Parse a number value. var number, string = ''; if (ch === '-') { string = '-'; next('-'); } while (ch >= '0' && ch <= '9') { string += ch; next(); } if (ch === '.') { string += '.'; while (next() && ch >= '0' && ch <= '9') { string += ch; } } if (ch === 'e' || ch === 'E') { string += ch; next(); if (ch === '-' || ch === '+') { string += ch; next(); } while (ch >= '0' && ch <= '9') { string += ch; next(); } } number = +string; if (!isFinite(number)) { error("Bad number"); } else { return number; } }, string = function () { // Parse a string value. var hex, i, string = '', uffff; // When parsing for string values, we must look for " and \ characters. if (ch === '"') { while (next()) { if (ch === '"') { next(); return string; } else if (ch === '\\') { next(); if (ch === 'u') { uffff = 0; for (i = 0; i < 4; i += 1) { hex = parseInt(next(), 16); if (!isFinite(hex)) { break; } uffff = uffff * 16 + hex; } string += String.fromCharCode(uffff); } else if (typeof escapee[ch] === 'string') { string += escapee[ch]; } else { break; } } else { string += ch; } } } error("Bad string"); }, white = function () { // Skip whitespace. while (ch && ch <= ' ') { next(); } }, word = function () { // true, false, or null. switch (ch) { case 't': next('t'); next('r'); next('u'); next('e'); return true; case 'f': next('f'); next('a'); next('l'); next('s'); next('e'); return false; case 'n': next('n'); next('u'); next('l'); next('l'); return null; } error("Unexpected '" + ch + "'"); }, value, // Place holder for the value function. array = function () { // Parse an array value. var array = []; if (ch === '[') { next('['); white(); if (ch === ']') { next(']'); return array; // empty array } while (ch) { array.push(value()); white(); if (ch === ']') { next(']'); return array; } next(','); white(); } } error("Bad array"); }, object = function () { // Parse an object value. var key, object = {}; if (ch === '{') { next('{'); white(); if (ch === '}') { next('}'); return object; // empty object } while (ch) { key = string(); white(); next(':'); if (Object.hasOwnProperty.call(object, key)) { error('Duplicate key "' + key + '"'); } object[key] = value(); white(); if (ch === '}') { next('}'); return object; } next(','); white(); } } error("Bad object"); }; value = function () { // Parse a JSON value. It could be an object, an array, a string, a number, // or a word. white(); switch (ch) { case '{': return object(); case '[': return array(); case '"': return string(); case '-': return number(); default: return ch >= '0' && ch <= '9' ? number() : word(); } }; // Return the json_parse function. It will have access to all of the above // functions and variables. return function (source, reviver) { var result; text = source; at = 0; ch = ' '; result = value(); white(); if (ch) { error("Syntax error"); } // If there is a reviver function, we recursively walk the new structure, // passing each name/value pair to the reviver function for possible // transformation, starting with a temporary root object that holds the result // in an empty key. If there is not a reviver function, we simply return the // result. return typeof reviver === 'function' ? (function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); }({'': result}, '')) : result; }; }()); }); // Included from: src/javascript/image/Image.js /** * Image.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/image/Image", [ "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/Exceptions", "moxie/file/FileReaderSync", "moxie/xhr/XMLHttpRequest", "moxie/runtime/Runtime", "moxie/runtime/RuntimeClient", "moxie/runtime/Transporter", "moxie/core/utils/Env", "moxie/core/EventTarget", "moxie/file/Blob", "moxie/file/File", "moxie/core/utils/Encode", "moxie/core/JSON" ], function(Basic, Dom, x, FileReaderSync, XMLHttpRequest, Runtime, RuntimeClient, Transporter, Env, EventTarget, Blob, File, Encode, parseJSON) { /** Image preloading and manipulation utility. Additionally it provides access to image meta info (Exif, GPS) and raw binary data. @class Image @constructor @extends EventTarget */ var dispatches = [ 'progress', /** Dispatched when loading is complete. @event load @param {Object} event */ 'load', 'error', /** Dispatched when resize operation is complete. @event resize @param {Object} event */ 'resize', /** Dispatched when visual representation of the image is successfully embedded into the corresponsing container. @event embedded @param {Object} event */ 'embedded' ]; function Image() { RuntimeClient.call(this); Basic.extend(this, { /** Unique id of the component @property uid @type {String} */ uid: Basic.guid('uid_'), /** Unique id of the connected runtime, if any. @property ruid @type {String} */ ruid: null, /** Name of the file, that was used to create an image, if available. If not equals to empty string. @property name @type {String} @default "" */ name: "", /** Size of the image in bytes. Actual value is set only after image is preloaded. @property size @type {Number} @default 0 */ size: 0, /** Width of the image. Actual value is set only after image is preloaded. @property width @type {Number} @default 0 */ width: 0, /** Height of the image. Actual value is set only after image is preloaded. @property height @type {Number} @default 0 */ height: 0, /** Mime type of the image. Currently only image/jpeg and image/png are supported. Actual value is set only after image is preloaded. @property type @type {String} @default "" */ type: "", /** Holds meta info (Exif, GPS). Is populated only for image/jpeg. Actual value is set only after image is preloaded. @property meta @type {Object} @default {} */ meta: {}, /** Alias for load method, that takes another mOxie.Image object as a source (see load). @method clone @param {Image} src Source for the image @param {Boolean} [exact=false] Whether to activate in-depth clone mode */ clone: function() { this.load.apply(this, arguments); }, /** Loads image from various sources. Currently the source for new image can be: mOxie.Image, mOxie.Blob/mOxie.File, native Blob/File, dataUrl or URL. Depending on the type of the source, arguments - differ. When source is URL, Image will be downloaded from remote destination and loaded in memory. @example var img = new mOxie.Image(); img.onload = function() { var blob = img.getAsBlob(); var formData = new mOxie.FormData(); formData.append('file', blob); var xhr = new mOxie.XMLHttpRequest(); xhr.onload = function() { // upload complete }; xhr.open('post', 'upload.php'); xhr.send(formData); }; img.load("http://www.moxiecode.com/images/mox-logo.jpg"); // notice file extension (.jpg) @method load @param {Image|Blob|File|String} src Source for the image @param {Boolean|Object} [mixed] */ load: function() { // this is here because to bind properly we need an uid first, which is created above this.bind('Load Resize', function() { _updateInfo.call(this); }, 999); this.convertEventPropsToHandlers(dispatches); _load.apply(this, arguments); }, /** Downsizes the image to fit the specified width/height. If crop is supplied, image will be cropped to exact dimensions. @method downsize @param {Number} width Resulting width @param {Number} [height=width] Resulting height (optional, if not supplied will default to width) @param {Boolean} [crop=false] Whether to crop the image to exact dimensions @param {Boolean} [preserveHeaders=true] Whether to preserve meta headers (on JPEGs after resize) */ downsize: function(width, height, crop, preserveHeaders) { try { if (!this.size) { // only preloaded image objects can be used as source throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // no way to reliably intercept the crash due to high resolution, so we simply avoid it if (this.width > Image.MAX_RESIZE_WIDTH || this.height > Image.MAX_RESIZE_HEIGHT) { throw new x.ImageError(x.ImageError.MAX_RESOLUTION_ERR); } if (!width && !height || Basic.typeOf(crop) === 'undefined') { crop = false; } width = width || this.width; height = height || this.height; preserveHeaders = (Basic.typeOf(preserveHeaders) === 'undefined' ? true : !!preserveHeaders); this.getRuntime().exec.call(this, 'Image', 'downsize', width, height, crop, preserveHeaders); } catch(ex) { // for now simply trigger error event this.trigger('error', ex); } }, /** Alias for downsize(width, height, true). (see downsize) @method crop @param {Number} width Resulting width @param {Number} [height=width] Resulting height (optional, if not supplied will default to width) @param {Boolean} [preserveHeaders=true] Whether to preserve meta headers (on JPEGs after resize) */ crop: function(width, height, preserveHeaders) { this.downsize(width, height, true, preserveHeaders); }, getAsCanvas: function() { if (!Env.can('create_canvas')) { throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR); } var runtime = this.connectRuntime(this.ruid); return runtime.exec.call(this, 'Image', 'getAsCanvas'); }, /** Retrieves image in it's current state as mOxie.Blob object. Cannot be run on empty or image in progress (throws DOMException.INVALID_STATE_ERR). @method getAsBlob @param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png @param {Number} [quality=90] Applicable only together with mime type image/jpeg @return {Blob} Image as Blob */ getAsBlob: function(type, quality) { if (!this.size) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } if (!type) { type = 'image/jpeg'; } if (type === 'image/jpeg' && !quality) { quality = 90; } return this.getRuntime().exec.call(this, 'Image', 'getAsBlob', type, quality); }, /** Retrieves image in it's current state as dataURL string. Cannot be run on empty or image in progress (throws DOMException.INVALID_STATE_ERR). @method getAsDataURL @param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png @param {Number} [quality=90] Applicable only together with mime type image/jpeg @return {String} Image as dataURL string */ getAsDataURL: function(type, quality) { if (!this.size) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } return this.getRuntime().exec.call(this, 'Image', 'getAsDataURL', type, quality); }, /** Retrieves image in it's current state as binary string. Cannot be run on empty or image in progress (throws DOMException.INVALID_STATE_ERR). @method getAsBinaryString @param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png @param {Number} [quality=90] Applicable only together with mime type image/jpeg @return {String} Image as binary string */ getAsBinaryString: function(type, quality) { var dataUrl = this.getAsDataURL(type, quality); return Encode.atob(dataUrl.substring(dataUrl.indexOf('base64,') + 7)); }, /** Embeds the image, or better to say, it's visual representation into the specified node. Depending on the runtime in use, might be a canvas, or image (actual ) element or shim object (Flash or SilverLight - very rare, used for legacy browsers that do not have canvas or proper dataURI support). @method embed @param {DOMElement} el DOM element to insert the image object into @param {Object} options Set of key/value pairs controlling the mime type, dimensions and cropping factor of resulting representation */ embed: function(el) { var self = this , imgCopy , type, quality, crop , options = arguments[1] || {} , width = this.width , height = this.height , runtime // this has to be outside of all the closures to contain proper runtime ; function onResize() { // if possible, embed a canvas element directly if (Env.can('create_canvas')) { var canvas = imgCopy.getAsCanvas(); if (canvas) { el.appendChild(canvas); canvas = null; imgCopy.destroy(); self.trigger('embedded'); return; } } var dataUrl = imgCopy.getAsDataURL(type, quality); if (!dataUrl) { throw new x.ImageError(x.ImageError.WRONG_FORMAT); } if (Env.can('use_data_uri_of', dataUrl.length)) { el.innerHTML = '<img src="' + dataUrl + '" width="' + imgCopy.width + '" height="' + imgCopy.height + '" />'; imgCopy.destroy(); self.trigger('embedded'); } else { var tr = new Transporter(); tr.bind("TransportingComplete", function() { runtime = self.connectRuntime(this.result.ruid); self.bind("Embedded", function() { // position and size properly Basic.extend(runtime.getShimContainer().style, { //position: 'relative', top: '0px', left: '0px', width: imgCopy.width + 'px', height: imgCopy.height + 'px' }); // some shims (Flash/SilverLight) reinitialize, if parent element is hidden, reordered or it's // position type changes (in Gecko), but since we basically need this only in IEs 6/7 and // sometimes 8 and they do not have this problem, we can comment this for now /*tr.bind("RuntimeInit", function(e, runtime) { tr.destroy(); runtime.destroy(); onResize.call(self); // re-feed our image data });*/ runtime = null; }, 999); runtime.exec.call(self, "ImageView", "display", this.result.uid, width, height); imgCopy.destroy(); }); tr.transport(Encode.atob(dataUrl.substring(dataUrl.indexOf('base64,') + 7)), type, Basic.extend({}, options, { required_caps: { display_media: true }, runtime_order: 'flash,silverlight', container: el })); } } try { if (!(el = Dom.get(el))) { throw new x.DOMException(x.DOMException.INVALID_NODE_TYPE_ERR); } if (!this.size) { // only preloaded image objects can be used as source throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } if (this.width > Image.MAX_RESIZE_WIDTH || this.height > Image.MAX_RESIZE_HEIGHT) { throw new x.ImageError(x.ImageError.MAX_RESOLUTION_ERR); } type = options.type || this.type || 'image/jpeg'; quality = options.quality || 90; crop = Basic.typeOf(options.crop) !== 'undefined' ? options.crop : false; // figure out dimensions for the thumb if (options.width) { width = options.width; height = options.height || width; } else { // if container element has > 0 dimensions, take them var dimensions = Dom.getSize(el); if (dimensions.w && dimensions.h) { // both should be > 0 width = dimensions.w; height = dimensions.h; } } imgCopy = new Image(); imgCopy.bind("Resize", function() { onResize.call(self); }); imgCopy.bind("Load", function() { imgCopy.downsize(width, height, crop, false); }); imgCopy.clone(this, false); return imgCopy; } catch(ex) { // for now simply trigger error event this.trigger('error', ex); } }, /** Properly destroys the image and frees resources in use. If any. Recommended way to dispose mOxie.Image object. @method destroy */ destroy: function() { if (this.ruid) { this.getRuntime().exec.call(this, 'Image', 'destroy'); this.disconnectRuntime(); } this.unbindAll(); } }); function _updateInfo(info) { if (!info) { info = this.getRuntime().exec.call(this, 'Image', 'getInfo'); } if (info) { if (Basic.typeOf(info.meta) === 'string') { // might be a JSON string try { this.meta = parseJSON(info.meta); } catch(ex) {} } else { this.meta = info.meta; } } Basic.extend(this, { // info object might be non-enumerable (as returned from SilverLight for example) size: parseInt(info.size, 10), width: parseInt(info.width, 10), height: parseInt(info.height, 10), type: info.type }); // update file name, only if empty if (this.name === '') { this.name = info.name; } } function _load(src) { var srcType = Basic.typeOf(src); try { // if source is Image if (src instanceof Image) { if (!src.size) { // only preloaded image objects can be used as source throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } _loadFromImage.apply(this, arguments); } // if source is o.Blob/o.File else if (src instanceof Blob) { if (!~Basic.inArray(src.type, ['image/jpeg', 'image/png'])) { throw new x.ImageError(x.ImageError.WRONG_FORMAT); } _loadFromBlob.apply(this, arguments); } // if native blob/file else if (Basic.inArray(srcType, ['blob', 'file']) !== -1) { _load.call(this, new File(null, src), arguments[1]); } // if String else if (srcType === 'string') { // if dataUrl String if (/^data:[^;]*;base64,/.test(src)) { _load.call(this, new Blob(null, { data: src }), arguments[1]); } // else assume Url, either relative or absolute else { _loadFromUrl.apply(this, arguments); } } // if source seems to be an img node else if (srcType === 'node' && src.nodeName.toLowerCase() === 'img') { _load.call(this, src.src, arguments[1]); } else { throw new x.DOMException(x.DOMException.TYPE_MISMATCH_ERR); } } catch(ex) { // for now simply trigger error event this.trigger('error', ex); } } function _loadFromImage(img, exact) { var runtime = this.connectRuntime(img.ruid); this.ruid = runtime.uid; runtime.exec.call(this, 'Image', 'loadFromImage', img, (Basic.typeOf(exact) === 'undefined' ? true : exact)); } function _loadFromBlob(blob, options) { var self = this; self.name = blob.name || ''; function exec(runtime) { self.ruid = runtime.uid; runtime.exec.call(self, 'Image', 'loadFromBlob', blob); } if (blob.isDetached()) { this.bind('RuntimeInit', function(e, runtime) { exec(runtime); }); // convert to object representation if (options && typeof(options.required_caps) === 'string') { options.required_caps = Runtime.parseCaps(options.required_caps); } this.connectRuntime(Basic.extend({ required_caps: { access_image_binary: true, resize_image: true } }, options)); } else { exec(this.connectRuntime(blob.ruid)); } } function _loadFromUrl(url, options) { var self = this, xhr; xhr = new XMLHttpRequest(); xhr.open('get', url); xhr.responseType = 'blob'; xhr.onprogress = function(e) { self.trigger(e); }; xhr.onload = function() { _loadFromBlob.call(self, xhr.response, true); }; xhr.onerror = function(e) { self.trigger(e); }; xhr.onloadend = function() { xhr.destroy(); }; xhr.bind('RuntimeError', function(e, err) { self.trigger('RuntimeError', err); }); xhr.send(null, options); } } // virtual world will crash on you if image has a resolution higher than this: Image.MAX_RESIZE_WIDTH = 6500; Image.MAX_RESIZE_HEIGHT = 6500; Image.prototype = EventTarget.instance; return Image; }); // Included from: src/javascript/runtime/html5/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global File:true */ /** Defines constructor for HTML5 runtime. @class moxie/runtime/html5/Runtime @private */ define("moxie/runtime/html5/Runtime", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/runtime/Runtime", "moxie/core/utils/Env" ], function(Basic, x, Runtime, Env) { var type = "html5", extensions = {}; function Html5Runtime(options) { var I = this , Test = Runtime.capTest , True = Runtime.capTrue ; var caps = Basic.extend({ access_binary: Test(window.FileReader || window.File && window.File.getAsDataURL), access_image_binary: function() { return I.can('access_binary') && !!extensions.Image; }, display_media: Test(Env.can('create_canvas') || Env.can('use_data_uri_over32kb')), do_cors: Test(window.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest()), drag_and_drop: Test(function() { // this comes directly from Modernizr: http://www.modernizr.com/ var div = document.createElement('div'); // IE has support for drag and drop since version 5, but doesn't support dropping files from desktop return (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div)) && (Env.browser !== 'IE' || Env.version > 9); }()), filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest return (Env.browser === 'Chrome' && Env.version >= 28) || (Env.browser === 'IE' && Env.version >= 10); }()), return_response_headers: True, return_response_type: function(responseType) { if (responseType === 'json') { return true; // we can fake this one even if it's not supported } else { return Env.can('return_response_type', responseType); } }, return_status_code: True, report_upload_progress: Test(window.XMLHttpRequest && new XMLHttpRequest().upload), resize_image: function() { return I.can('access_binary') && Env.can('create_canvas'); }, select_file: function() { return Env.can('use_fileinput') && window.File; }, select_folder: function() { return I.can('select_file') && Env.browser === 'Chrome' && Env.version >= 21; }, select_multiple: function() { return I.can('select_file') && !(Env.browser === 'Safari' && Env.OS === 'Windows'); }, send_binary_string: Test(window.XMLHttpRequest && (new XMLHttpRequest().sendAsBinary || (window.Uint8Array && window.ArrayBuffer))), send_custom_headers: Test(window.XMLHttpRequest), send_multipart: function() { return !!(window.XMLHttpRequest && new XMLHttpRequest().upload && window.FormData) || I.can('send_binary_string'); }, slice_blob: Test(window.File && (File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice)), stream_upload: function(){ return I.can('slice_blob') && I.can('send_multipart'); }, summon_file_dialog: Test(function() { // yeah... some dirty sniffing here... return (Env.browser === 'Firefox' && Env.version >= 4) || (Env.browser === 'Opera' && Env.version >= 12) || (Env.browser === 'IE' && Env.version >= 10) || !!~Basic.inArray(Env.browser, ['Chrome', 'Safari']); }()), upload_filesize: True }, arguments[2] ); Runtime.call(this, options, (arguments[1] || type), caps); Basic.extend(this, { init : function() { this.trigger("Init"); }, destroy: (function(destroy) { // extend default destroy method return function() { destroy.call(I); destroy = I = null; }; }(this.destroy)) }); Basic.extend(this.getShim(), extensions); } Runtime.addConstructor(type, Html5Runtime); return extensions; }); // Included from: src/javascript/runtime/html5/file/Blob.js /** * Blob.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/file/Blob @private */ define("moxie/runtime/html5/file/Blob", [ "moxie/runtime/html5/Runtime", "moxie/file/Blob" ], function(extensions, Blob) { function HTML5Blob() { function w3cBlobSlice(blob, start, end) { var blobSlice; if (window.File.prototype.slice) { try { blob.slice(); // depricated version will throw WRONG_ARGUMENTS_ERR exception return blob.slice(start, end); } catch (e) { // depricated slice method return blob.slice(start, end - start); } // slice method got prefixed: https://bugzilla.mozilla.org/show_bug.cgi?id=649672 } else if ((blobSlice = window.File.prototype.webkitSlice || window.File.prototype.mozSlice)) { return blobSlice.call(blob, start, end); } else { return null; // or throw some exception } } this.slice = function() { return new Blob(this.getRuntime().uid, w3cBlobSlice.apply(this, arguments)); }; } return (extensions.Blob = HTML5Blob); }); // Included from: src/javascript/core/utils/Events.js /** * Events.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Events', [ 'moxie/core/utils/Basic' ], function(Basic) { var eventhash = {}, uid = 'moxie_' + Basic.guid(); // IE W3C like event funcs function preventDefault() { this.returnValue = false; } function stopPropagation() { this.cancelBubble = true; } /** Adds an event handler to the specified object and store reference to the handler in objects internal Plupload registry (@see removeEvent). @method addEvent @for Utils @static @param {Object} obj DOM element like object to add handler to. @param {String} name Name to add event listener to. @param {Function} callback Function to call when event occurs. @param {String} [key] that might be used to add specifity to the event record. */ var addEvent = function(obj, name, callback, key) { var func, events; name = name.toLowerCase(); // Add event listener if (obj.addEventListener) { func = callback; obj.addEventListener(name, func, false); } else if (obj.attachEvent) { func = function() { var evt = window.event; if (!evt.target) { evt.target = evt.srcElement; } evt.preventDefault = preventDefault; evt.stopPropagation = stopPropagation; callback(evt); }; obj.attachEvent('on' + name, func); } // Log event handler to objects internal mOxie registry if (!obj[uid]) { obj[uid] = Basic.guid(); } if (!eventhash.hasOwnProperty(obj[uid])) { eventhash[obj[uid]] = {}; } events = eventhash[obj[uid]]; if (!events.hasOwnProperty(name)) { events[name] = []; } events[name].push({ func: func, orig: callback, // store original callback for IE key: key }); }; /** Remove event handler from the specified object. If third argument (callback) is not specified remove all events with the specified name. @method removeEvent @static @param {Object} obj DOM element to remove event listener(s) from. @param {String} name Name of event listener to remove. @param {Function|String} [callback] might be a callback or unique key to match. */ var removeEvent = function(obj, name, callback) { var type, undef; name = name.toLowerCase(); if (obj[uid] && eventhash[obj[uid]] && eventhash[obj[uid]][name]) { type = eventhash[obj[uid]][name]; } else { return; } for (var i = type.length - 1; i >= 0; i--) { // undefined or not, key should match if (type[i].orig === callback || type[i].key === callback) { if (obj.removeEventListener) { obj.removeEventListener(name, type[i].func, false); } else if (obj.detachEvent) { obj.detachEvent('on'+name, type[i].func); } type[i].orig = null; type[i].func = null; type.splice(i, 1); // If callback was passed we are done here, otherwise proceed if (callback !== undef) { break; } } } // If event array got empty, remove it if (!type.length) { delete eventhash[obj[uid]][name]; } // If mOxie registry has become empty, remove it if (Basic.isEmptyObj(eventhash[obj[uid]])) { delete eventhash[obj[uid]]; // IE doesn't let you remove DOM object property with - delete try { delete obj[uid]; } catch(e) { obj[uid] = undef; } } }; /** Remove all kind of events from the specified object @method removeAllEvents @static @param {Object} obj DOM element to remove event listeners from. @param {String} [key] unique key to match, when removing events. */ var removeAllEvents = function(obj, key) { if (!obj || !obj[uid]) { return; } Basic.each(eventhash[obj[uid]], function(events, name) { removeEvent(obj, name, key); }); }; return { addEvent: addEvent, removeEvent: removeEvent, removeAllEvents: removeAllEvents }; }); // Included from: src/javascript/runtime/html5/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/file/FileInput @private */ define("moxie/runtime/html5/file/FileInput", [ "moxie/runtime/html5/Runtime", "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/utils/Events", "moxie/core/utils/Mime", "moxie/core/utils/Env" ], function(extensions, Basic, Dom, Events, Mime, Env) { function FileInput() { var _files = [], _options; Basic.extend(this, { init: function(options) { var comp = this, I = comp.getRuntime(), input, shimContainer, mimes, browseButton, zIndex, top; _options = options; _files = []; // figure out accept string mimes = _options.accept.mimes || Mime.extList2mimes(_options.accept, I.can('filter_by_extension')); shimContainer = I.getShimContainer(); shimContainer.innerHTML = '<input id="' + I.uid +'" type="file" style="font-size:999px;opacity:0;"' + (_options.multiple && I.can('select_multiple') ? 'multiple' : '') + (_options.directory && I.can('select_folder') ? 'webkitdirectory directory' : '') + // Chrome 11+ (mimes ? ' accept="' + mimes.join(',') + '"' : '') + ' />'; input = Dom.get(I.uid); // prepare file input to be placed underneath the browse_button element Basic.extend(input.style, { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }); browseButton = Dom.get(_options.browse_button); // Route click event to the input[type=file] element for browsers that support such behavior if (I.can('summon_file_dialog')) { if (Dom.getStyle(browseButton, 'position') === 'static') { browseButton.style.position = 'relative'; } zIndex = parseInt(Dom.getStyle(browseButton, 'z-index'), 10) || 1; browseButton.style.zIndex = zIndex; shimContainer.style.zIndex = zIndex - 1; Events.addEvent(browseButton, 'click', function(e) { var input = Dom.get(I.uid); if (input && !input.disabled) { // for some reason FF (up to 8.0.1 so far) lets to click disabled input[type=file] input.click(); } e.preventDefault(); }, comp.uid); } /* Since we have to place input[type=file] on top of the browse_button for some browsers, browse_button loses interactivity, so we restore it here */ top = I.can('summon_file_dialog') ? browseButton : shimContainer; Events.addEvent(top, 'mouseover', function() { comp.trigger('mouseenter'); }, comp.uid); Events.addEvent(top, 'mouseout', function() { comp.trigger('mouseleave'); }, comp.uid); Events.addEvent(top, 'mousedown', function() { comp.trigger('mousedown'); }, comp.uid); Events.addEvent(Dom.get(_options.container), 'mouseup', function() { comp.trigger('mouseup'); }, comp.uid); input.onchange = function onChange() { // there should be only one handler for this _files = []; if (_options.directory) { // folders are represented by dots, filter them out (Chrome 11+) Basic.each(this.files, function(file) { if (file.name !== ".") { // if it doesn't looks like a folder _files.push(file); } }); } else { _files = [].slice.call(this.files); } // clearing the value enables the user to select the same file again if they want to if (Env.browser !== 'IE') { this.value = ''; } else { // in IE input[type="file"] is read-only so the only way to reset it is to re-insert it var clone = this.cloneNode(true); this.parentNode.replaceChild(clone, this); clone.onchange = onChange; } comp.trigger('change'); }; // ready event is perfectly asynchronous comp.trigger({ type: 'ready', async: true }); shimContainer = null; }, getFiles: function() { return _files; }, disable: function(state) { var I = this.getRuntime(), input; if ((input = Dom.get(I.uid))) { input.disabled = !!state; } }, destroy: function() { var I = this.getRuntime(), shimContainer = I.getShimContainer(); Events.removeAllEvents(shimContainer, this.uid); Events.removeAllEvents(_options && Dom.get(_options.container), this.uid); Events.removeAllEvents(_options && Dom.get(_options.browse_button), this.uid); if (shimContainer) { shimContainer.innerHTML = ''; } _files = _options = null; } }); } return (extensions.FileInput = FileInput); }); // Included from: src/javascript/runtime/html5/file/FileDrop.js /** * FileDrop.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/file/FileDrop @private */ define("moxie/runtime/html5/file/FileDrop", [ "moxie/runtime/html5/Runtime", "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/utils/Events", "moxie/core/utils/Mime" ], function(extensions, Basic, Dom, Events, Mime) { function FileDrop() { var _files = [], _allowedExts = [], _options; Basic.extend(this, { init: function(options) { var comp = this, dropZone; _options = options; _allowedExts = _extractExts(_options.accept); dropZone = _options.container; Events.addEvent(dropZone, 'dragover', function(e) { e.preventDefault(); e.stopPropagation(); e.dataTransfer.dropEffect = 'copy'; }, comp.uid); Events.addEvent(dropZone, 'drop', function(e) { e.preventDefault(); e.stopPropagation(); _files = []; // Chrome 21+ accepts folders via Drag'n'Drop if (e.dataTransfer.items && e.dataTransfer.items[0].webkitGetAsEntry) { var entries = []; Basic.each(e.dataTransfer.items, function(item) { entries.push(item.webkitGetAsEntry()); }); _readEntries(entries, function() { comp.trigger("drop"); }); } else { Basic.each(e.dataTransfer.files, function(file) { if (_isAcceptable(file)) { _files.push(file); } }); comp.trigger("drop"); } }, comp.uid); Events.addEvent(dropZone, 'dragenter', function(e) { e.preventDefault(); e.stopPropagation(); comp.trigger("dragenter"); }, comp.uid); Events.addEvent(dropZone, 'dragleave', function(e) { e.preventDefault(); e.stopPropagation(); comp.trigger("dragleave"); }, comp.uid); }, getFiles: function() { return _files; }, destroy: function() { Events.removeAllEvents(_options && Dom.get(_options.container), this.uid); _files = _allowedExts = _options = null; } }); function _extractExts(accept) { var exts = []; for (var i = 0; i < accept.length; i++) { [].push.apply(exts, accept[i].extensions.split(/\s*,\s*/)); } return Basic.inArray('*', exts) === -1 ? exts : []; } function _isAcceptable(file) { var ext = Mime.getFileExtension(file.name); return !ext || !_allowedExts.length || Basic.inArray(ext, _allowedExts) !== -1; } function _readEntries(entries, cb) { var queue = []; Basic.each(entries, function(entry) { queue.push(function(cbcb) { _readEntry(entry, cbcb); }); }); Basic.inSeries(queue, function() { cb(); }); } function _readEntry(entry, cb) { if (entry.isFile) { entry.file(function(file) { if (_isAcceptable(file)) { _files.push(file); } cb(); }, function() { // fire an error event maybe cb(); }); } else if (entry.isDirectory) { _readDirEntry(entry, cb); } else { cb(); // not file, not directory? what then?.. } } function _readDirEntry(dirEntry, cb) { var entries = [], dirReader = dirEntry.createReader(); // keep quering recursively till no more entries function getEntries(cbcb) { dirReader.readEntries(function(moreEntries) { if (moreEntries.length) { [].push.apply(entries, moreEntries); getEntries(cbcb); } else { cbcb(); } }, cbcb); } // ...and you thought FileReader was crazy... getEntries(function() { _readEntries(entries, cb); }); } } return (extensions.FileDrop = FileDrop); }); // Included from: src/javascript/runtime/html5/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/file/FileReader @private */ define("moxie/runtime/html5/file/FileReader", [ "moxie/runtime/html5/Runtime", "moxie/core/utils/Encode", "moxie/core/utils/Basic" ], function(extensions, Encode, Basic) { function FileReader() { var _fr, _convertToBinary = false; Basic.extend(this, { read: function(op, blob) { var target = this; _fr = new window.FileReader(); _fr.addEventListener('progress', function(e) { target.trigger(e); }); _fr.addEventListener('load', function(e) { target.trigger(e); }); _fr.addEventListener('error', function(e) { target.trigger(e, _fr.error); }); _fr.addEventListener('loadend', function() { _fr = null; }); if (Basic.typeOf(_fr[op]) === 'function') { _convertToBinary = false; _fr[op](blob.getSource()); } else if (op === 'readAsBinaryString') { // readAsBinaryString is depricated in general and never existed in IE10+ _convertToBinary = true; _fr.readAsDataURL(blob.getSource()); } }, getResult: function() { return _fr && _fr.result ? (_convertToBinary ? _toBinary(_fr.result) : _fr.result) : null; }, abort: function() { if (_fr) { _fr.abort(); } }, destroy: function() { _fr = null; } }); function _toBinary(str) { return Encode.atob(str.substring(str.indexOf('base64,') + 7)); } } return (extensions.FileReader = FileReader); }); // Included from: src/javascript/runtime/html5/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global ActiveXObject:true */ /** @class moxie/runtime/html5/xhr/XMLHttpRequest @private */ define("moxie/runtime/html5/xhr/XMLHttpRequest", [ "moxie/runtime/html5/Runtime", "moxie/core/utils/Basic", "moxie/core/utils/Mime", "moxie/core/utils/Url", "moxie/file/File", "moxie/file/Blob", "moxie/xhr/FormData", "moxie/core/Exceptions", "moxie/core/utils/Env", "moxie/core/JSON" ], function(extensions, Basic, Mime, Url, File, Blob, FormData, x, Env, parseJSON) { function XMLHttpRequest() { var _xhr , _filename ; Basic.extend(this, { send: function(meta, data) { var target = this , isGecko2_5_6 = (Env.browser === 'Mozilla' && Env.version >= 4 && Env.version < 7) , isAndroidBrowser = Env.browser === 'Android Browser' , mustSendAsBinary = false ; // extract file name _filename = meta.url.replace(/^.+?\/([\w\-\.]+)$/, '$1').toLowerCase(); _xhr = _getNativeXHR(); _xhr.open(meta.method, meta.url, meta.async, meta.user, meta.password); // prepare data to be sent if (data instanceof Blob) { if (data.isDetached()) { mustSendAsBinary = true; } data = data.getSource(); } else if (data instanceof FormData) { if (data.hasBlob()) { if (data.getBlob().isDetached()) { data = _prepareMultipart.call(target, data); // _xhr must be instantiated and be in OPENED state mustSendAsBinary = true; } else if ((isGecko2_5_6 || isAndroidBrowser) && Basic.typeOf(data.getBlob().getSource()) === 'blob' && window.FileReader) { // Gecko 2/5/6 can't send blob in FormData: https://bugzilla.mozilla.org/show_bug.cgi?id=649150 // Android browsers (default one and Dolphin) seem to have the same issue, see: #613 _preloadAndSend.call(target, meta, data); return; // _preloadAndSend will reinvoke send() with transmutated FormData =%D } } // transfer fields to real FormData if (data instanceof FormData) { // if still a FormData, e.g. not mangled by _prepareMultipart() var fd = new window.FormData(); data.each(function(value, name) { if (value instanceof Blob) { fd.append(name, value.getSource()); } else { fd.append(name, value); } }); data = fd; } } // if XHR L2 if (_xhr.upload) { if (meta.withCredentials) { _xhr.withCredentials = true; } _xhr.addEventListener('load', function(e) { target.trigger(e); }); _xhr.addEventListener('error', function(e) { target.trigger(e); }); // additionally listen to progress events _xhr.addEventListener('progress', function(e) { target.trigger(e); }); _xhr.upload.addEventListener('progress', function(e) { target.trigger({ type: 'UploadProgress', loaded: e.loaded, total: e.total }); }); // ... otherwise simulate XHR L2 } else { _xhr.onreadystatechange = function onReadyStateChange() { // fake Level 2 events switch (_xhr.readyState) { case 1: // XMLHttpRequest.OPENED // readystatechanged is fired twice for OPENED state (in IE and Mozilla) - neu break; // looks like HEADERS_RECEIVED (state 2) is not reported in Opera (or it's old versions) - neu case 2: // XMLHttpRequest.HEADERS_RECEIVED break; case 3: // XMLHttpRequest.LOADING // try to fire progress event for not XHR L2 var total, loaded; try { if (Url.hasSameOrigin(meta.url)) { // Content-Length not accessible for cross-domain on some browsers total = _xhr.getResponseHeader('Content-Length') || 0; // old Safari throws an exception here } if (_xhr.responseText) { // responseText was introduced in IE7 loaded = _xhr.responseText.length; } } catch(ex) { total = loaded = 0; } target.trigger({ type: 'progress', lengthComputable: !!total, total: parseInt(total, 10), loaded: loaded }); break; case 4: // XMLHttpRequest.DONE // release readystatechange handler (mostly for IE) _xhr.onreadystatechange = function() {}; // usually status 0 is returned when server is unreachable, but FF also fails to status 0 for 408 timeout if (_xhr.status === 0) { target.trigger('error'); } else { target.trigger('load'); } break; } }; } // set request headers if (!Basic.isEmptyObj(meta.headers)) { Basic.each(meta.headers, function(value, header) { _xhr.setRequestHeader(header, value); }); } // request response type if ("" !== meta.responseType && 'responseType' in _xhr) { if ('json' === meta.responseType && !Env.can('return_response_type', 'json')) { // we can fake this one _xhr.responseType = 'text'; } else { _xhr.responseType = meta.responseType; } } // send ... if (!mustSendAsBinary) { _xhr.send(data); } else { if (_xhr.sendAsBinary) { // Gecko _xhr.sendAsBinary(data); } else { // other browsers having support for typed arrays (function() { // mimic Gecko's sendAsBinary var ui8a = new Uint8Array(data.length); for (var i = 0; i < data.length; i++) { ui8a[i] = (data.charCodeAt(i) & 0xff); } _xhr.send(ui8a.buffer); }()); } } target.trigger('loadstart'); }, getStatus: function() { // according to W3C spec it should return 0 for readyState < 3, but instead it throws an exception try { if (_xhr) { return _xhr.status; } } catch(ex) {} return 0; }, getResponse: function(responseType) { var I = this.getRuntime(); try { switch (responseType) { case 'blob': var file = new File(I.uid, _xhr.response); // try to extract file name from content-disposition if possible (might be - not, if CORS for example) var disposition = _xhr.getResponseHeader('Content-Disposition'); if (disposition) { // extract filename from response header if available var match = disposition.match(/filename=([\'\"'])([^\1]+)\1/); if (match) { _filename = match[2]; } } file.name = _filename; // pre-webkit Opera doesn't set type property on the blob response if (!file.type) { file.type = Mime.getFileMime(_filename); } return file; case 'json': if (!Env.can('return_response_type', 'json')) { return _xhr.status === 200 ? parseJSON(_xhr.responseText) : null; } return _xhr.response; case 'document': return _getDocument(_xhr); default: return _xhr.responseText !== '' ? _xhr.responseText : null; // against the specs, but for consistency across the runtimes } } catch(ex) { return null; } }, getAllResponseHeaders: function() { try { return _xhr.getAllResponseHeaders(); } catch(ex) {} return ''; }, abort: function() { if (_xhr) { _xhr.abort(); } }, destroy: function() { self = _filename = null; } }); // here we go... ugly fix for ugly bug function _preloadAndSend(meta, data) { var target = this, blob, fr; // get original blob blob = data.getBlob().getSource(); // preload blob in memory to be sent as binary string fr = new window.FileReader(); fr.onload = function() { // overwrite original blob data.append(data.getBlobName(), new Blob(null, { type: blob.type, data: fr.result })); // invoke send operation again self.send.call(target, meta, data); }; fr.readAsBinaryString(blob); } function _getNativeXHR() { if (window.XMLHttpRequest && !(Env.browser === 'IE' && Env.version < 8)) { // IE7 has native XHR but it's buggy return new window.XMLHttpRequest(); } else { return (function() { var progIDs = ['Msxml2.XMLHTTP.6.0', 'Microsoft.XMLHTTP']; // if 6.0 available, use it, otherwise failback to default 3.0 for (var i = 0; i < progIDs.length; i++) { try { return new ActiveXObject(progIDs[i]); } catch (ex) {} } })(); } } // @credits Sergey Ilinsky (http://www.ilinsky.com/) function _getDocument(xhr) { var rXML = xhr.responseXML; var rText = xhr.responseText; // Try parsing responseText (@see: http://www.ilinsky.com/articles/XMLHttpRequest/#bugs-ie-responseXML-content-type) if (Env.browser === 'IE' && rText && rXML && !rXML.documentElement && /[^\/]+\/[^\+]+\+xml/.test(xhr.getResponseHeader("Content-Type"))) { rXML = new window.ActiveXObject("Microsoft.XMLDOM"); rXML.async = false; rXML.validateOnParse = false; rXML.loadXML(rText); } // Check if there is no error in document if (rXML) { if ((Env.browser === 'IE' && rXML.parseError !== 0) || !rXML.documentElement || rXML.documentElement.tagName === "parsererror") { return null; } } return rXML; } function _prepareMultipart(fd) { var boundary = '----moxieboundary' + new Date().getTime() , dashdash = '--' , crlf = '\r\n' , multipart = '' , I = this.getRuntime() ; if (!I.can('send_binary_string')) { throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR); } _xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary); // append multipart parameters fd.each(function(value, name) { // Firefox 3.6 failed to convert multibyte characters to UTF-8 in sendAsBinary(), // so we try it here ourselves with: unescape(encodeURIComponent(value)) if (value instanceof Blob) { // Build RFC2388 blob multipart += dashdash + boundary + crlf + 'Content-Disposition: form-data; name="' + name + '"; filename="' + unescape(encodeURIComponent(value.name || 'blob')) + '"' + crlf + 'Content-Type: ' + value.type + crlf + crlf + value.getSource() + crlf; } else { multipart += dashdash + boundary + crlf + 'Content-Disposition: form-data; name="' + name + '"' + crlf + crlf + unescape(encodeURIComponent(value)) + crlf; } }); multipart += dashdash + boundary + dashdash + crlf; return multipart; } } return (extensions.XMLHttpRequest = XMLHttpRequest); }); // Included from: src/javascript/runtime/html5/utils/BinaryReader.js /** * BinaryReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/utils/BinaryReader @private */ define("moxie/runtime/html5/utils/BinaryReader", [], function() { return function() { var II = false, bin; // Private functions function read(idx, size) { var mv = II ? 0 : -8 * (size - 1), sum = 0, i; for (i = 0; i < size; i++) { sum |= (bin.charCodeAt(idx + i) << Math.abs(mv + i*8)); } return sum; } function putstr(segment, idx, length) { length = arguments.length === 3 ? length : bin.length - idx - 1; bin = bin.substr(0, idx) + segment + bin.substr(length + idx); } function write(idx, num, size) { var str = '', mv = II ? 0 : -8 * (size - 1), i; for (i = 0; i < size; i++) { str += String.fromCharCode((num >> Math.abs(mv + i*8)) & 255); } putstr(str, idx, size); } // Public functions return { II: function(order) { if (order === undefined) { return II; } else { II = order; } }, init: function(binData) { II = false; bin = binData; }, SEGMENT: function(idx, length, segment) { switch (arguments.length) { case 1: return bin.substr(idx, bin.length - idx - 1); case 2: return bin.substr(idx, length); case 3: putstr(segment, idx, length); break; default: return bin; } }, BYTE: function(idx) { return read(idx, 1); }, SHORT: function(idx) { return read(idx, 2); }, LONG: function(idx, num) { if (num === undefined) { return read(idx, 4); } else { write(idx, num, 4); } }, SLONG: function(idx) { // 2's complement notation var num = read(idx, 4); return (num > 2147483647 ? num - 4294967296 : num); }, STRING: function(idx, size) { var str = ''; for (size += idx; idx < size; idx++) { str += String.fromCharCode(read(idx, 1)); } return str; } }; }; }); // Included from: src/javascript/runtime/html5/image/JPEGHeaders.js /** * JPEGHeaders.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/JPEGHeaders @private */ define("moxie/runtime/html5/image/JPEGHeaders", [ "moxie/runtime/html5/utils/BinaryReader" ], function(BinaryReader) { return function JPEGHeaders(data) { var headers = [], read, idx, marker, length = 0; read = new BinaryReader(); read.init(data); // Check if data is jpeg if (read.SHORT(0) !== 0xFFD8) { return; } idx = 2; while (idx <= data.length) { marker = read.SHORT(idx); // omit RST (restart) markers if (marker >= 0xFFD0 && marker <= 0xFFD7) { idx += 2; continue; } // no headers allowed after SOS marker if (marker === 0xFFDA || marker === 0xFFD9) { break; } length = read.SHORT(idx + 2) + 2; // APPn marker detected if (marker >= 0xFFE1 && marker <= 0xFFEF) { headers.push({ hex: marker, name: 'APP' + (marker & 0x000F), start: idx, length: length, segment: read.SEGMENT(idx, length) }); } idx += length; } read.init(null); // free memory return { headers: headers, restore: function(data) { var max, i; read.init(data); idx = read.SHORT(2) == 0xFFE0 ? 4 + read.SHORT(4) : 2; for (i = 0, max = headers.length; i < max; i++) { read.SEGMENT(idx, 0, headers[i].segment); idx += headers[i].length; } data = read.SEGMENT(); read.init(null); return data; }, strip: function(data) { var headers, jpegHeaders, i; jpegHeaders = new JPEGHeaders(data); headers = jpegHeaders.headers; jpegHeaders.purge(); read.init(data); i = headers.length; while (i--) { read.SEGMENT(headers[i].start, headers[i].length, ''); } data = read.SEGMENT(); read.init(null); return data; }, get: function(name) { var array = []; for (var i = 0, max = headers.length; i < max; i++) { if (headers[i].name === name.toUpperCase()) { array.push(headers[i].segment); } } return array; }, set: function(name, segment) { var array = [], i, ii, max; if (typeof(segment) === 'string') { array.push(segment); } else { array = segment; } for (i = ii = 0, max = headers.length; i < max; i++) { if (headers[i].name === name.toUpperCase()) { headers[i].segment = array[ii]; headers[i].length = array[ii].length; ii++; } if (ii >= array.length) { break; } } }, purge: function() { headers = []; read.init(null); read = null; } }; }; }); // Included from: src/javascript/runtime/html5/image/ExifParser.js /** * ExifParser.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/ExifParser @private */ define("moxie/runtime/html5/image/ExifParser", [ "moxie/core/utils/Basic", "moxie/runtime/html5/utils/BinaryReader" ], function(Basic, BinaryReader) { return function ExifParser() { // Private ExifParser fields var data, tags, Tiff, offsets = {}, tagDescs; data = new BinaryReader(); tags = { tiff : { /* The image orientation viewed in terms of rows and columns. 1 = The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side. 2 = The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side. 3 = The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side. 4 = The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side. 5 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual top. 6 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual top. 7 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom. 8 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom. */ 0x0112: 'Orientation', 0x010E: 'ImageDescription', 0x010F: 'Make', 0x0110: 'Model', 0x0131: 'Software', 0x8769: 'ExifIFDPointer', 0x8825: 'GPSInfoIFDPointer' }, exif : { 0x9000: 'ExifVersion', 0xA001: 'ColorSpace', 0xA002: 'PixelXDimension', 0xA003: 'PixelYDimension', 0x9003: 'DateTimeOriginal', 0x829A: 'ExposureTime', 0x829D: 'FNumber', 0x8827: 'ISOSpeedRatings', 0x9201: 'ShutterSpeedValue', 0x9202: 'ApertureValue' , 0x9207: 'MeteringMode', 0x9208: 'LightSource', 0x9209: 'Flash', 0x920A: 'FocalLength', 0xA402: 'ExposureMode', 0xA403: 'WhiteBalance', 0xA406: 'SceneCaptureType', 0xA404: 'DigitalZoomRatio', 0xA408: 'Contrast', 0xA409: 'Saturation', 0xA40A: 'Sharpness' }, gps : { 0x0000: 'GPSVersionID', 0x0001: 'GPSLatitudeRef', 0x0002: 'GPSLatitude', 0x0003: 'GPSLongitudeRef', 0x0004: 'GPSLongitude' } }; tagDescs = { 'ColorSpace': { 1: 'sRGB', 0: 'Uncalibrated' }, 'MeteringMode': { 0: 'Unknown', 1: 'Average', 2: 'CenterWeightedAverage', 3: 'Spot', 4: 'MultiSpot', 5: 'Pattern', 6: 'Partial', 255: 'Other' }, 'LightSource': { 1: 'Daylight', 2: 'Fliorescent', 3: 'Tungsten', 4: 'Flash', 9: 'Fine weather', 10: 'Cloudy weather', 11: 'Shade', 12: 'Daylight fluorescent (D 5700 - 7100K)', 13: 'Day white fluorescent (N 4600 -5400K)', 14: 'Cool white fluorescent (W 3900 - 4500K)', 15: 'White fluorescent (WW 3200 - 3700K)', 17: 'Standard light A', 18: 'Standard light B', 19: 'Standard light C', 20: 'D55', 21: 'D65', 22: 'D75', 23: 'D50', 24: 'ISO studio tungsten', 255: 'Other' }, 'Flash': { 0x0000: 'Flash did not fire.', 0x0001: 'Flash fired.', 0x0005: 'Strobe return light not detected.', 0x0007: 'Strobe return light detected.', 0x0009: 'Flash fired, compulsory flash mode', 0x000D: 'Flash fired, compulsory flash mode, return light not detected', 0x000F: 'Flash fired, compulsory flash mode, return light detected', 0x0010: 'Flash did not fire, compulsory flash mode', 0x0018: 'Flash did not fire, auto mode', 0x0019: 'Flash fired, auto mode', 0x001D: 'Flash fired, auto mode, return light not detected', 0x001F: 'Flash fired, auto mode, return light detected', 0x0020: 'No flash function', 0x0041: 'Flash fired, red-eye reduction mode', 0x0045: 'Flash fired, red-eye reduction mode, return light not detected', 0x0047: 'Flash fired, red-eye reduction mode, return light detected', 0x0049: 'Flash fired, compulsory flash mode, red-eye reduction mode', 0x004D: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected', 0x004F: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light detected', 0x0059: 'Flash fired, auto mode, red-eye reduction mode', 0x005D: 'Flash fired, auto mode, return light not detected, red-eye reduction mode', 0x005F: 'Flash fired, auto mode, return light detected, red-eye reduction mode' }, 'ExposureMode': { 0: 'Auto exposure', 1: 'Manual exposure', 2: 'Auto bracket' }, 'WhiteBalance': { 0: 'Auto white balance', 1: 'Manual white balance' }, 'SceneCaptureType': { 0: 'Standard', 1: 'Landscape', 2: 'Portrait', 3: 'Night scene' }, 'Contrast': { 0: 'Normal', 1: 'Soft', 2: 'Hard' }, 'Saturation': { 0: 'Normal', 1: 'Low saturation', 2: 'High saturation' }, 'Sharpness': { 0: 'Normal', 1: 'Soft', 2: 'Hard' }, // GPS related 'GPSLatitudeRef': { N: 'North latitude', S: 'South latitude' }, 'GPSLongitudeRef': { E: 'East longitude', W: 'West longitude' } }; function extractTags(IFD_offset, tags2extract) { var length = data.SHORT(IFD_offset), i, ii, tag, type, count, tagOffset, offset, value, values = [], hash = {}; for (i = 0; i < length; i++) { // Set binary reader pointer to beginning of the next tag offset = tagOffset = IFD_offset + 12 * i + 2; tag = tags2extract[data.SHORT(offset)]; if (tag === undefined) { continue; // Not the tag we requested } type = data.SHORT(offset+=2); count = data.LONG(offset+=2); offset += 4; values = []; switch (type) { case 1: // BYTE case 7: // UNDEFINED if (count > 4) { offset = data.LONG(offset) + offsets.tiffHeader; } for (ii = 0; ii < count; ii++) { values[ii] = data.BYTE(offset + ii); } break; case 2: // STRING if (count > 4) { offset = data.LONG(offset) + offsets.tiffHeader; } hash[tag] = data.STRING(offset, count - 1); continue; case 3: // SHORT if (count > 2) { offset = data.LONG(offset) + offsets.tiffHeader; } for (ii = 0; ii < count; ii++) { values[ii] = data.SHORT(offset + ii*2); } break; case 4: // LONG if (count > 1) { offset = data.LONG(offset) + offsets.tiffHeader; } for (ii = 0; ii < count; ii++) { values[ii] = data.LONG(offset + ii*4); } break; case 5: // RATIONAL offset = data.LONG(offset) + offsets.tiffHeader; for (ii = 0; ii < count; ii++) { values[ii] = data.LONG(offset + ii*4) / data.LONG(offset + ii*4 + 4); } break; case 9: // SLONG offset = data.LONG(offset) + offsets.tiffHeader; for (ii = 0; ii < count; ii++) { values[ii] = data.SLONG(offset + ii*4); } break; case 10: // SRATIONAL offset = data.LONG(offset) + offsets.tiffHeader; for (ii = 0; ii < count; ii++) { values[ii] = data.SLONG(offset + ii*4) / data.SLONG(offset + ii*4 + 4); } break; default: continue; } value = (count == 1 ? values[0] : values); if (tagDescs.hasOwnProperty(tag) && typeof value != 'object') { hash[tag] = tagDescs[tag][value]; } else { hash[tag] = value; } } return hash; } function getIFDOffsets() { var idx = offsets.tiffHeader; // Set read order of multi-byte data data.II(data.SHORT(idx) == 0x4949); // Check if always present bytes are indeed present if (data.SHORT(idx+=2) !== 0x002A) { return false; } offsets.IFD0 = offsets.tiffHeader + data.LONG(idx += 2); Tiff = extractTags(offsets.IFD0, tags.tiff); if ('ExifIFDPointer' in Tiff) { offsets.exifIFD = offsets.tiffHeader + Tiff.ExifIFDPointer; delete Tiff.ExifIFDPointer; } if ('GPSInfoIFDPointer' in Tiff) { offsets.gpsIFD = offsets.tiffHeader + Tiff.GPSInfoIFDPointer; delete Tiff.GPSInfoIFDPointer; } return true; } // At the moment only setting of simple (LONG) values, that do not require offset recalculation, is supported function setTag(ifd, tag, value) { var offset, length, tagOffset, valueOffset = 0; // If tag name passed translate into hex key if (typeof(tag) === 'string') { var tmpTags = tags[ifd.toLowerCase()]; for (var hex in tmpTags) { if (tmpTags[hex] === tag) { tag = hex; break; } } } offset = offsets[ifd.toLowerCase() + 'IFD']; length = data.SHORT(offset); for (var i = 0; i < length; i++) { tagOffset = offset + 12 * i + 2; if (data.SHORT(tagOffset) == tag) { valueOffset = tagOffset + 8; break; } } if (!valueOffset) { return false; } data.LONG(valueOffset, value); return true; } // Public functions return { init: function(segment) { // Reset internal data offsets = { tiffHeader: 10 }; if (segment === undefined || !segment.length) { return false; } data.init(segment); // Check if that's APP1 and that it has EXIF if (data.SHORT(0) === 0xFFE1 && data.STRING(4, 5).toUpperCase() === "EXIF\0") { return getIFDOffsets(); } return false; }, TIFF: function() { return Tiff; }, EXIF: function() { var Exif; // Populate EXIF hash Exif = extractTags(offsets.exifIFD, tags.exif); // Fix formatting of some tags if (Exif.ExifVersion && Basic.typeOf(Exif.ExifVersion) === 'array') { for (var i = 0, exifVersion = ''; i < Exif.ExifVersion.length; i++) { exifVersion += String.fromCharCode(Exif.ExifVersion[i]); } Exif.ExifVersion = exifVersion; } return Exif; }, GPS: function() { var GPS; GPS = extractTags(offsets.gpsIFD, tags.gps); // iOS devices (and probably some others) do not put in GPSVersionID tag (why?..) if (GPS.GPSVersionID && Basic.typeOf(GPS.GPSVersionID) === 'array') { GPS.GPSVersionID = GPS.GPSVersionID.join('.'); } return GPS; }, setExif: function(tag, value) { // Right now only setting of width/height is possible if (tag !== 'PixelXDimension' && tag !== 'PixelYDimension') {return false;} return setTag('exif', tag, value); }, getBinary: function() { return data.SEGMENT(); }, purge: function() { data.init(null); data = Tiff = null; offsets = {}; } }; }; }); // Included from: src/javascript/runtime/html5/image/JPEG.js /** * JPEG.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/JPEG @private */ define("moxie/runtime/html5/image/JPEG", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/runtime/html5/image/JPEGHeaders", "moxie/runtime/html5/utils/BinaryReader", "moxie/runtime/html5/image/ExifParser" ], function(Basic, x, JPEGHeaders, BinaryReader, ExifParser) { function JPEG(binstr) { var _binstr, _br, _hm, _ep, _info, hasExif; function _getDimensions() { var idx = 0, marker, length; // examine all through the end, since some images might have very large APP segments while (idx <= _binstr.length) { marker = _br.SHORT(idx += 2); if (marker >= 0xFFC0 && marker <= 0xFFC3) { // SOFn idx += 5; // marker (2 bytes) + length (2 bytes) + Sample precision (1 byte) return { height: _br.SHORT(idx), width: _br.SHORT(idx += 2) }; } length = _br.SHORT(idx += 2); idx += length - 2; } return null; } _binstr = binstr; _br = new BinaryReader(); _br.init(_binstr); // check if it is jpeg if (_br.SHORT(0) !== 0xFFD8) { throw new x.ImageError(x.ImageError.WRONG_FORMAT); } // backup headers _hm = new JPEGHeaders(binstr); // extract exif info _ep = new ExifParser(); hasExif = !!_ep.init(_hm.get('app1')[0]); // get dimensions _info = _getDimensions.call(this); Basic.extend(this, { type: 'image/jpeg', size: _binstr.length, width: _info && _info.width || 0, height: _info && _info.height || 0, setExif: function(tag, value) { if (!hasExif) { return false; // or throw an exception } if (Basic.typeOf(tag) === 'object') { Basic.each(tag, function(value, tag) { _ep.setExif(tag, value); }); } else { _ep.setExif(tag, value); } // update internal headers _hm.set('app1', _ep.getBinary()); }, writeHeaders: function() { if (!arguments.length) { // if no arguments passed, update headers internally return (_binstr = _hm.restore(_binstr)); } return _hm.restore(arguments[0]); }, stripHeaders: function(binstr) { return _hm.strip(binstr); }, purge: function() { _purge.call(this); } }); if (hasExif) { this.meta = { tiff: _ep.TIFF(), exif: _ep.EXIF(), gps: _ep.GPS() }; } function _purge() { if (!_ep || !_hm || !_br) { return; // ignore any repeating purge requests } _ep.purge(); _hm.purge(); _br.init(null); _binstr = _info = _hm = _ep = _br = null; } } return JPEG; }); // Included from: src/javascript/runtime/html5/image/PNG.js /** * PNG.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/PNG @private */ define("moxie/runtime/html5/image/PNG", [ "moxie/core/Exceptions", "moxie/core/utils/Basic", "moxie/runtime/html5/utils/BinaryReader" ], function(x, Basic, BinaryReader) { function PNG(binstr) { var _binstr, _br, _hm, _ep, _info; _binstr = binstr; _br = new BinaryReader(); _br.init(_binstr); // check if it's png (function() { var idx = 0, i = 0 , signature = [0x8950, 0x4E47, 0x0D0A, 0x1A0A] ; for (i = 0; i < signature.length; i++, idx += 2) { if (signature[i] != _br.SHORT(idx)) { throw new x.ImageError(x.ImageError.WRONG_FORMAT); } } }()); function _getDimensions() { var chunk, idx; chunk = _getChunkAt.call(this, 8); if (chunk.type == 'IHDR') { idx = chunk.start; return { width: _br.LONG(idx), height: _br.LONG(idx += 4) }; } return null; } function _purge() { if (!_br) { return; // ignore any repeating purge requests } _br.init(null); _binstr = _info = _hm = _ep = _br = null; } _info = _getDimensions.call(this); Basic.extend(this, { type: 'image/png', size: _binstr.length, width: _info.width, height: _info.height, purge: function() { _purge.call(this); } }); // for PNG we can safely trigger purge automatically, as we do not keep any data for later _purge.call(this); function _getChunkAt(idx) { var length, type, start, CRC; length = _br.LONG(idx); type = _br.STRING(idx += 4, 4); start = idx += 4; CRC = _br.LONG(idx + length); return { length: length, type: type, start: start, CRC: CRC }; } } return PNG; }); // Included from: src/javascript/runtime/html5/image/ImageInfo.js /** * ImageInfo.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/ImageInfo @private */ define("moxie/runtime/html5/image/ImageInfo", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/runtime/html5/image/JPEG", "moxie/runtime/html5/image/PNG" ], function(Basic, x, JPEG, PNG) { /** Optional image investigation tool for HTML5 runtime. Provides the following features: - ability to distinguish image type (JPEG or PNG) by signature - ability to extract image width/height directly from it's internals, without preloading in memory (fast) - ability to extract APP headers from JPEGs (Exif, GPS, etc) - ability to replace width/height tags in extracted JPEG headers - ability to restore APP headers, that were for example stripped during image manipulation @class ImageInfo @constructor @param {String} binstr Image source as binary string */ return function(binstr) { var _cs = [JPEG, PNG], _img; // figure out the format, throw: ImageError.WRONG_FORMAT if not supported _img = (function() { for (var i = 0; i < _cs.length; i++) { try { return new _cs[i](binstr); } catch (ex) { // //console.info(ex); } } throw new x.ImageError(x.ImageError.WRONG_FORMAT); }()); Basic.extend(this, { /** Image Mime Type extracted from it's depths @property type @type {String} @default '' */ type: '', /** Image size in bytes @property size @type {Number} @default 0 */ size: 0, /** Image width extracted from image source @property width @type {Number} @default 0 */ width: 0, /** Image height extracted from image source @property height @type {Number} @default 0 */ height: 0, /** Sets Exif tag. Currently applicable only for width and height tags. Obviously works only with JPEGs. @method setExif @param {String} tag Tag to set @param {Mixed} value Value to assign to the tag */ setExif: function() {}, /** Restores headers to the source. @method writeHeaders @param {String} data Image source as binary string @return {String} Updated binary string */ writeHeaders: function(data) { return data; }, /** Strip all headers from the source. @method stripHeaders @param {String} data Image source as binary string @return {String} Updated binary string */ stripHeaders: function(data) { return data; }, /** Dispose resources. @method purge */ purge: function() {} }); Basic.extend(this, _img); this.purge = function() { _img.purge(); _img = null; }; }; }); // Included from: src/javascript/runtime/html5/image/MegaPixel.js /** (The MIT License) Copyright (c) 2012 Shinichi Tomita <[email protected]>; Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * Mega pixel image rendering library for iOS6 Safari * * Fixes iOS6 Safari's image file rendering issue for large size image (over mega-pixel), * which causes unexpected subsampling when drawing it in canvas. * By using this library, you can safely render the image with proper stretching. * * Copyright (c) 2012 Shinichi Tomita <[email protected]> * Released under the MIT license */ /** @class moxie/runtime/html5/image/MegaPixel @private */ define("moxie/runtime/html5/image/MegaPixel", [], function() { /** * Rendering image element (with resizing) into the canvas element */ function renderImageToCanvas(img, canvas, options) { var iw = img.naturalWidth, ih = img.naturalHeight; var width = options.width, height = options.height; var x = options.x || 0, y = options.y || 0; var ctx = canvas.getContext('2d'); if (detectSubsampling(img)) { iw /= 2; ih /= 2; } var d = 1024; // size of tiling canvas var tmpCanvas = document.createElement('canvas'); tmpCanvas.width = tmpCanvas.height = d; var tmpCtx = tmpCanvas.getContext('2d'); var vertSquashRatio = detectVerticalSquash(img, iw, ih); var sy = 0; while (sy < ih) { var sh = sy + d > ih ? ih - sy : d; var sx = 0; while (sx < iw) { var sw = sx + d > iw ? iw - sx : d; tmpCtx.clearRect(0, 0, d, d); tmpCtx.drawImage(img, -sx, -sy); var dx = (sx * width / iw + x) << 0; var dw = Math.ceil(sw * width / iw); var dy = (sy * height / ih / vertSquashRatio + y) << 0; var dh = Math.ceil(sh * height / ih / vertSquashRatio); ctx.drawImage(tmpCanvas, 0, 0, sw, sh, dx, dy, dw, dh); sx += d; } sy += d; } tmpCanvas = tmpCtx = null; } /** * Detect subsampling in loaded image. * In iOS, larger images than 2M pixels may be subsampled in rendering. */ function detectSubsampling(img) { var iw = img.naturalWidth, ih = img.naturalHeight; if (iw * ih > 1024 * 1024) { // subsampling may happen over megapixel image var canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; var ctx = canvas.getContext('2d'); ctx.drawImage(img, -iw + 1, 0); // subsampled image becomes half smaller in rendering size. // check alpha channel value to confirm image is covering edge pixel or not. // if alpha value is 0 image is not covering, hence subsampled. return ctx.getImageData(0, 0, 1, 1).data[3] === 0; } else { return false; } } /** * Detecting vertical squash in loaded image. * Fixes a bug which squash image vertically while drawing into canvas for some images. */ function detectVerticalSquash(img, iw, ih) { var canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = ih; var ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); var data = ctx.getImageData(0, 0, 1, ih).data; // search image edge pixel position in case it is squashed vertically. var sy = 0; var ey = ih; var py = ih; while (py > sy) { var alpha = data[(py - 1) * 4 + 3]; if (alpha === 0) { ey = py; } else { sy = py; } py = (ey + sy) >> 1; } canvas = null; var ratio = (py / ih); return (ratio === 0) ? 1 : ratio; } return { isSubsampled: detectSubsampling, renderTo: renderImageToCanvas }; }); // Included from: src/javascript/runtime/html5/image/Image.js /** * Image.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/image/Image @private */ define("moxie/runtime/html5/image/Image", [ "moxie/runtime/html5/Runtime", "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/core/utils/Encode", "moxie/file/Blob", "moxie/runtime/html5/image/ImageInfo", "moxie/runtime/html5/image/MegaPixel", "moxie/core/utils/Mime", "moxie/core/utils/Env" ], function(extensions, Basic, x, Encode, Blob, ImageInfo, MegaPixel, Mime, Env) { function HTML5Image() { var me = this , _img, _imgInfo, _canvas, _binStr, _blob , _modified = false // is set true whenever image is modified , _preserveHeaders = true ; Basic.extend(this, { loadFromBlob: function(blob) { var comp = this, I = comp.getRuntime() , asBinary = arguments.length > 1 ? arguments[1] : true ; if (!I.can('access_binary')) { throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR); } _blob = blob; if (blob.isDetached()) { _binStr = blob.getSource(); _preload.call(this, _binStr); return; } else { _readAsDataUrl.call(this, blob.getSource(), function(dataUrl) { if (asBinary) { _binStr = _toBinary(dataUrl); } _preload.call(comp, dataUrl); }); } }, loadFromImage: function(img, exact) { this.meta = img.meta; _blob = new Blob(null, { name: img.name, size: img.size, type: img.type }); _preload.call(this, exact ? (_binStr = img.getAsBinaryString()) : img.getAsDataURL()); }, getInfo: function() { var I = this.getRuntime(), info; if (!_imgInfo && _binStr && I.can('access_image_binary')) { _imgInfo = new ImageInfo(_binStr); } info = { width: _getImg().width || 0, height: _getImg().height || 0, type: _blob.type || Mime.getFileMime(_blob.name), size: _binStr && _binStr.length || _blob.size || 0, name: _blob.name || '', meta: _imgInfo && _imgInfo.meta || this.meta || {} }; return info; }, downsize: function() { _downsize.apply(this, arguments); }, getAsCanvas: function() { if (_canvas) { _canvas.id = this.uid + '_canvas'; } return _canvas; }, getAsBlob: function(type, quality) { if (type !== this.type) { // if different mime type requested prepare image for conversion _downsize.call(this, this.width, this.height, false); } return new Blob(null, { type: type, data: me.getAsBinaryString.call(this, type, quality) }); }, getAsDataURL: function(type) { var quality = arguments[1] || 90; // if image has not been modified, return the source right away if (!_modified) { return _img.src; } if ('image/jpeg' !== type) { return _canvas.toDataURL('image/png'); } else { try { // older Geckos used to result in an exception on quality argument return _canvas.toDataURL('image/jpeg', quality/100); } catch (ex) { return _canvas.toDataURL('image/jpeg'); } } }, getAsBinaryString: function(type, quality) { // if image has not been modified, return the source right away if (!_modified) { // if image was not loaded from binary string if (!_binStr) { _binStr = _toBinary(me.getAsDataURL(type, quality)); } return _binStr; } if ('image/jpeg' !== type) { _binStr = _toBinary(me.getAsDataURL(type, quality)); } else { var dataUrl; // if jpeg if (!quality) { quality = 90; } try { // older Geckos used to result in an exception on quality argument dataUrl = _canvas.toDataURL('image/jpeg', quality/100); } catch (ex) { dataUrl = _canvas.toDataURL('image/jpeg'); } _binStr = _toBinary(dataUrl); if (_imgInfo) { _binStr = _imgInfo.stripHeaders(_binStr); if (_preserveHeaders) { // update dimensions info in exif if (_imgInfo.meta && _imgInfo.meta.exif) { _imgInfo.setExif({ PixelXDimension: this.width, PixelYDimension: this.height }); } // re-inject the headers _binStr = _imgInfo.writeHeaders(_binStr); } // will be re-created from fresh on next getInfo call _imgInfo.purge(); _imgInfo = null; } } _modified = false; return _binStr; }, destroy: function() { me = null; _purge.call(this); this.getRuntime().getShim().removeInstance(this.uid); } }); function _getImg() { if (!_canvas && !_img) { throw new x.ImageError(x.DOMException.INVALID_STATE_ERR); } return _canvas || _img; } function _toBinary(str) { return Encode.atob(str.substring(str.indexOf('base64,') + 7)); } function _toDataUrl(str, type) { return 'data:' + (type || '') + ';base64,' + Encode.btoa(str); } function _preload(str) { var comp = this; _img = new Image(); _img.onerror = function() { _purge.call(this); comp.trigger('error', new x.ImageError(x.ImageError.WRONG_FORMAT)); }; _img.onload = function() { comp.trigger('load'); }; _img.src = /^data:[^;]*;base64,/.test(str) ? str : _toDataUrl(str, _blob.type); } function _readAsDataUrl(file, callback) { var comp = this, fr; // use FileReader if it's available if (window.FileReader) { fr = new FileReader(); fr.onload = function() { callback(this.result); }; fr.onerror = function() { comp.trigger('error', new x.FileException(x.FileException.NOT_READABLE_ERR)); }; fr.readAsDataURL(file); } else { return callback(file.getAsDataURL()); } } function _downsize(width, height, crop, preserveHeaders) { var self = this, ctx, scale, mathFn, x, y, img, imgWidth, imgHeight, orientation; _preserveHeaders = preserveHeaders; // we will need to check this on export // take into account orientation tag orientation = (this.meta && this.meta.tiff && this.meta.tiff.Orientation) || 1; if (Basic.inArray(orientation, [5,6,7,8]) !== -1) { // values that require 90 degree rotation // swap dimensions var mem = width; width = height; height = mem; } img = _getImg(); // unify dimensions mathFn = !crop ? Math.min : Math.max; scale = mathFn(width/img.width, height/img.height); // we only downsize here if (scale > 1 && (!crop || preserveHeaders)) { // when cropping one of dimensions may still exceed max, so process it anyway this.trigger('Resize'); return; } imgWidth = Math.round(img.width * scale); imgHeight = Math.round(img.height * scale); // prepare canvas if necessary if (!_canvas) { _canvas = document.createElement("canvas"); } ctx = _canvas.getContext('2d'); // scale image and canvas if (crop) { _canvas.width = width; _canvas.height = height; } else { _canvas.width = imgWidth; _canvas.height = imgHeight; } // if dimensions of the resulting image still larger than canvas, center it x = imgWidth > _canvas.width ? Math.round((imgWidth - _canvas.width) / 2) : 0; y = imgHeight > _canvas.height ? Math.round((imgHeight - _canvas.height) / 2) : 0; if (!_preserveHeaders) { _rotateToOrientaion(_canvas.width, _canvas.height, orientation); } _drawToCanvas.call(this, img, _canvas, -x, -y, imgWidth, imgHeight); this.width = _canvas.width; this.height = _canvas.height; _modified = true; self.trigger('Resize'); } function _drawToCanvas(img, canvas, x, y, w, h) { if (Env.OS === 'iOS') { // avoid squish bug in iOS6 MegaPixel.renderTo(img, canvas, { width: w, height: h, x: x, y: y }); } else { var ctx = canvas.getContext('2d'); ctx.drawImage(img, x, y, w, h); } } /** * Transform canvas coordination according to specified frame size and orientation * Orientation value is from EXIF tag * @author Shinichi Tomita <[email protected]> */ function _rotateToOrientaion(width, height, orientation) { switch (orientation) { case 5: case 6: case 7: case 8: _canvas.width = height; _canvas.height = width; break; default: _canvas.width = width; _canvas.height = height; } /** 1 = The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side. 2 = The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side. 3 = The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side. 4 = The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side. 5 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual top. 6 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual top. 7 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom. 8 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom. */ var ctx = _canvas.getContext('2d'); switch (orientation) { case 2: // horizontal flip ctx.translate(width, 0); ctx.scale(-1, 1); break; case 3: // 180 rotate left ctx.translate(width, height); ctx.rotate(Math.PI); break; case 4: // vertical flip ctx.translate(0, height); ctx.scale(1, -1); break; case 5: // vertical flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.scale(1, -1); break; case 6: // 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(0, -height); break; case 7: // horizontal flip + 90 rotate right ctx.rotate(0.5 * Math.PI); ctx.translate(width, -height); ctx.scale(-1, 1); break; case 8: // 90 rotate left ctx.rotate(-0.5 * Math.PI); ctx.translate(-width, 0); break; } } function _purge() { if (_imgInfo) { _imgInfo.purge(); _imgInfo = null; } _binStr = _img = _canvas = _blob = null; _modified = false; } } return (extensions.Image = HTML5Image); }); // Included from: src/javascript/runtime/flash/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global ActiveXObject:true */ /** Defines constructor for Flash runtime. @class moxie/runtime/flash/Runtime @private */ define("moxie/runtime/flash/Runtime", [ "moxie/core/utils/Basic", "moxie/core/utils/Env", "moxie/core/utils/Dom", "moxie/core/Exceptions", "moxie/runtime/Runtime" ], function(Basic, Env, Dom, x, Runtime) { var type = 'flash', extensions = {}; /** Get the version of the Flash Player @method getShimVersion @private @return {Number} Flash Player version */ function getShimVersion() { var version; try { version = navigator.plugins['Shockwave Flash']; version = version.description; } catch (e1) { try { version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version'); } catch (e2) { version = '0.0'; } } version = version.match(/\d+/g); return parseFloat(version[0] + '.' + version[1]); } /** Constructor for the Flash Runtime @class FlashRuntime @extends Runtime */ function FlashRuntime(options) { var I = this, initTimer; options = Basic.extend({ swf_url: Env.swf_url }, options); Runtime.call(this, options, type, { access_binary: function(value) { return value && I.mode === 'browser'; }, access_image_binary: function(value) { return value && I.mode === 'browser'; }, display_media: Runtime.capTrue, do_cors: Runtime.capTrue, drag_and_drop: false, report_upload_progress: function() { return I.mode === 'client'; }, resize_image: Runtime.capTrue, return_response_headers: false, return_response_type: function(responseType) { return !Basic.arrayDiff(responseType, ['', 'text', 'json', 'document']) || I.mode === 'browser'; }, return_status_code: function(code) { return I.mode === 'browser' || !Basic.arrayDiff(code, [200, 404]); }, select_file: Runtime.capTrue, select_multiple: Runtime.capTrue, send_binary_string: function(value) { return value && I.mode === 'browser'; }, send_browser_cookies: function(value) { return value && I.mode === 'browser'; }, send_custom_headers: function(value) { return value && I.mode === 'browser'; }, send_multipart: Runtime.capTrue, slice_blob: Runtime.capTrue, stream_upload: function(value) { return value && I.mode === 'browser'; }, summon_file_dialog: false, upload_filesize: function(size) { return Basic.parseSizeStr(size) <= 2097152 || I.mode === 'client'; }, use_http_method: function(methods) { return !Basic.arrayDiff(methods, ['GET', 'POST']); } }, { // capabilities that require specific mode access_binary: function(value) { return value ? 'browser' : 'client'; }, access_image_binary: function(value) { return value ? 'browser' : 'client'; }, report_upload_progress: function(value) { return value ? 'browser' : 'client'; }, return_response_type: function(responseType) { return Basic.arrayDiff(responseType, ['', 'text', 'json', 'document']) ? 'browser' : ['client', 'browser']; }, return_status_code: function(code) { return Basic.arrayDiff(code, [200, 404]) ? 'browser' : ['client', 'browser']; }, send_binary_string: function(value) { return value ? 'browser' : 'client'; }, send_browser_cookies: function(value) { return value ? 'browser' : 'client'; }, send_custom_headers: function(value) { return value ? 'browser' : 'client'; }, stream_upload: function(value) { return value ? 'client' : 'browser'; }, upload_filesize: function(size) { return Basic.parseSizeStr(size) >= 2097152 ? 'client' : 'browser'; } }, 'client'); // minimal requirement Flash Player 10 if (getShimVersion() < 10) { this.mode = false; // with falsy mode, runtime won't operable, no matter what the mode was before } Basic.extend(this, { getShim: function() { return Dom.get(this.uid); }, shimExec: function(component, action) { var args = [].slice.call(arguments, 2); return I.getShim().exec(this.uid, component, action, args); }, init: function() { var html, el, container; container = this.getShimContainer(); // if not the minimal height, shims are not initialized in older browsers (e.g FF3.6, IE6,7,8, Safari 4.0,5.0, etc) Basic.extend(container.style, { position: 'absolute', top: '-8px', left: '-8px', width: '9px', height: '9px', overflow: 'hidden' }); // insert flash object html = '<object id="' + this.uid + '" type="application/x-shockwave-flash" data="' + options.swf_url + '" '; if (Env.browser === 'IE') { html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '; } html += 'width="100%" height="100%" style="outline:0">' + '<param name="movie" value="' + options.swf_url + '" />' + '<param name="flashvars" value="uid=' + escape(this.uid) + '&target=' + Env.global_event_dispatcher + '" />' + '<param name="wmode" value="transparent" />' + '<param name="allowscriptaccess" value="always" />' + '</object>'; if (Env.browser === 'IE') { el = document.createElement('div'); container.appendChild(el); el.outerHTML = html; el = container = null; // just in case } else { container.innerHTML = html; } // Init is dispatched by the shim initTimer = setTimeout(function() { if (I && !I.initialized) { // runtime might be already destroyed by this moment I.trigger("Error", new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR)); } }, 5000); }, destroy: (function(destroy) { // extend default destroy method return function() { destroy.call(I); clearTimeout(initTimer); // initialization check might be still onwait options = initTimer = destroy = I = null; }; }(this.destroy)) }, extensions); } Runtime.addConstructor(type, FlashRuntime); return extensions; }); // Included from: src/javascript/runtime/flash/file/Blob.js /** * Blob.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/file/Blob @private */ define("moxie/runtime/flash/file/Blob", [ "moxie/runtime/flash/Runtime", "moxie/file/Blob" ], function(extensions, Blob) { var FlashBlob = { slice: function(blob, start, end, type) { var self = this.getRuntime(); if (start < 0) { start = Math.max(blob.size + start, 0); } else if (start > 0) { start = Math.min(start, blob.size); } if (end < 0) { end = Math.max(blob.size + end, 0); } else if (end > 0) { end = Math.min(end, blob.size); } blob = self.shimExec.call(this, 'Blob', 'slice', start, end, type || ''); if (blob) { blob = new Blob(self.uid, blob); } return blob; } }; return (extensions.Blob = FlashBlob); }); // Included from: src/javascript/runtime/flash/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/file/FileInput @private */ define("moxie/runtime/flash/file/FileInput", [ "moxie/runtime/flash/Runtime" ], function(extensions) { var FileInput = { init: function(options) { this.getRuntime().shimExec.call(this, 'FileInput', 'init', { name: options.name, accept: options.accept, multiple: options.multiple }); this.trigger('ready'); } }; return (extensions.FileInput = FileInput); }); // Included from: src/javascript/runtime/flash/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/file/FileReader @private */ define("moxie/runtime/flash/file/FileReader", [ "moxie/runtime/flash/Runtime", "moxie/core/utils/Encode" ], function(extensions, Encode) { var _result = ''; function _formatData(data, op) { switch (op) { case 'readAsText': return Encode.atob(data, 'utf8'); case 'readAsBinaryString': return Encode.atob(data); case 'readAsDataURL': return data; } return null; } var FileReader = { read: function(op, blob) { var target = this, self = target.getRuntime(); // special prefix for DataURL read mode if (op === 'readAsDataURL') { _result = 'data:' + (blob.type || '') + ';base64,'; } target.bind('Progress', function(e, data) { if (data) { _result += _formatData(data, op); } }); return self.shimExec.call(this, 'FileReader', 'readAsBase64', blob.uid); }, getResult: function() { return _result; }, destroy: function() { _result = null; } }; return (extensions.FileReader = FileReader); }); // Included from: src/javascript/runtime/flash/file/FileReaderSync.js /** * FileReaderSync.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/file/FileReaderSync @private */ define("moxie/runtime/flash/file/FileReaderSync", [ "moxie/runtime/flash/Runtime", "moxie/core/utils/Encode" ], function(extensions, Encode) { function _formatData(data, op) { switch (op) { case 'readAsText': return Encode.atob(data, 'utf8'); case 'readAsBinaryString': return Encode.atob(data); case 'readAsDataURL': return data; } return null; } var FileReaderSync = { read: function(op, blob) { var result, self = this.getRuntime(); result = self.shimExec.call(this, 'FileReaderSync', 'readAsBase64', blob.uid); if (!result) { return null; // or throw ex } // special prefix for DataURL read mode if (op === 'readAsDataURL') { result = 'data:' + (blob.type || '') + ';base64,' + result; } return _formatData(result, op, blob.type); } }; return (extensions.FileReaderSync = FileReaderSync); }); // Included from: src/javascript/runtime/flash/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/xhr/XMLHttpRequest @private */ define("moxie/runtime/flash/xhr/XMLHttpRequest", [ "moxie/runtime/flash/Runtime", "moxie/core/utils/Basic", "moxie/file/Blob", "moxie/file/File", "moxie/file/FileReaderSync", "moxie/xhr/FormData", "moxie/runtime/Transporter", "moxie/core/JSON" ], function(extensions, Basic, Blob, File, FileReaderSync, FormData, Transporter, parseJSON) { var XMLHttpRequest = { send: function(meta, data) { var target = this, self = target.getRuntime(); function send() { meta.transport = self.mode; self.shimExec.call(target, 'XMLHttpRequest', 'send', meta, data); } function appendBlob(name, blob) { self.shimExec.call(target, 'XMLHttpRequest', 'appendBlob', name, blob.uid); data = null; send(); } function attachBlob(blob, cb) { var tr = new Transporter(); tr.bind("TransportingComplete", function() { cb(this.result); }); tr.transport(blob.getSource(), blob.type, { ruid: self.uid }); } // copy over the headers if any if (!Basic.isEmptyObj(meta.headers)) { Basic.each(meta.headers, function(value, header) { self.shimExec.call(target, 'XMLHttpRequest', 'setRequestHeader', header, value.toString()); // Silverlight doesn't accept integers into the arguments of type object }); } // transfer over multipart params and blob itself if (data instanceof FormData) { var blobField; data.each(function(value, name) { if (value instanceof Blob) { blobField = name; } else { self.shimExec.call(target, 'XMLHttpRequest', 'append', name, value); } }); if (!data.hasBlob()) { data = null; send(); } else { var blob = data.getBlob(); if (blob.isDetached()) { attachBlob(blob, function(attachedBlob) { blob.destroy(); appendBlob(blobField, attachedBlob); }); } else { appendBlob(blobField, blob); } } } else if (data instanceof Blob) { if (data.isDetached()) { attachBlob(data, function(attachedBlob) { data.destroy(); data = attachedBlob.uid; send(); }); } else { data = data.uid; send(); } } else { send(); } }, getResponse: function(responseType) { var frs, blob, self = this.getRuntime(); blob = self.shimExec.call(this, 'XMLHttpRequest', 'getResponseAsBlob'); if (blob) { blob = new File(self.uid, blob); if ('blob' === responseType) { return blob; } else if (!!~Basic.inArray(responseType, ["", "text"])) { frs = new FileReaderSync(); return frs.readAsText(blob); } else if ('arraybuffer' === responseType) { // do something } else if ('json' === responseType) { frs = new FileReaderSync(); try { return parseJSON(frs.readAsText(blob)); } catch (ex) { return null; } } } return null; }, abort: function(upload_complete_flag) { var self = this.getRuntime(); self.shimExec.call(this, 'XMLHttpRequest', 'abort'); this.dispatchEvent('readystatechange'); // this.dispatchEvent('progress'); this.dispatchEvent('abort'); if (!upload_complete_flag) { // this.dispatchEvent('uploadprogress'); } } }; return (extensions.XMLHttpRequest = XMLHttpRequest); }); // Included from: src/javascript/runtime/flash/runtime/Transporter.js /** * Transporter.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/runtime/Transporter @private */ define("moxie/runtime/flash/runtime/Transporter", [ "moxie/runtime/flash/Runtime", "moxie/file/Blob" ], function(extensions, Blob) { var Transporter = { getAsBlob: function(type) { var self = this.getRuntime() , blob = self.shimExec.call(this, 'Transporter', 'getAsBlob', type) ; if (blob) { return new Blob(self.uid, blob); } return null; } }; return (extensions.Transporter = Transporter); }); // Included from: src/javascript/runtime/flash/image/Image.js /** * Image.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/image/Image @private */ define("moxie/runtime/flash/image/Image", [ "moxie/runtime/flash/Runtime", "moxie/core/utils/Basic", "moxie/runtime/Transporter", "moxie/file/Blob", "moxie/file/FileReaderSync" ], function(extensions, Basic, Transporter, Blob, FileReaderSync) { var Image = { loadFromBlob: function(blob) { var comp = this, self = comp.getRuntime(); function exec(srcBlob) { self.shimExec.call(comp, 'Image', 'loadFromBlob', srcBlob.uid); comp = self = null; } if (blob.isDetached()) { // binary string var tr = new Transporter(); tr.bind("TransportingComplete", function() { exec(tr.result.getSource()); }); tr.transport(blob.getSource(), blob.type, { ruid: self.uid }); } else { exec(blob.getSource()); } }, loadFromImage: function(img) { var self = this.getRuntime(); return self.shimExec.call(this, 'Image', 'loadFromImage', img.uid); }, getAsBlob: function(type, quality) { var self = this.getRuntime() , blob = self.shimExec.call(this, 'Image', 'getAsBlob', type, quality) ; if (blob) { return new Blob(self.uid, blob); } return null; }, getAsDataURL: function() { var self = this.getRuntime() , blob = self.Image.getAsBlob.apply(this, arguments) , frs ; if (!blob) { return null; } frs = new FileReaderSync(); return frs.readAsDataURL(blob); } }; return (extensions.Image = Image); }); // Included from: src/javascript/runtime/silverlight/Runtime.js /** * RunTime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global ActiveXObject:true */ /** Defines constructor for Silverlight runtime. @class moxie/runtime/silverlight/Runtime @private */ define("moxie/runtime/silverlight/Runtime", [ "moxie/core/utils/Basic", "moxie/core/utils/Env", "moxie/core/utils/Dom", "moxie/core/Exceptions", "moxie/runtime/Runtime" ], function(Basic, Env, Dom, x, Runtime) { var type = "silverlight", extensions = {}; function isInstalled(version) { var isVersionSupported = false, control = null, actualVer, actualVerArray, reqVerArray, requiredVersionPart, actualVersionPart, index = 0; try { try { control = new ActiveXObject('AgControl.AgControl'); if (control.IsVersionSupported(version)) { isVersionSupported = true; } control = null; } catch (e) { var plugin = navigator.plugins["Silverlight Plug-In"]; if (plugin) { actualVer = plugin.description; if (actualVer === "1.0.30226.2") { actualVer = "2.0.30226.2"; } actualVerArray = actualVer.split("."); while (actualVerArray.length > 3) { actualVerArray.pop(); } while ( actualVerArray.length < 4) { actualVerArray.push(0); } reqVerArray = version.split("."); while (reqVerArray.length > 4) { reqVerArray.pop(); } do { requiredVersionPart = parseInt(reqVerArray[index], 10); actualVersionPart = parseInt(actualVerArray[index], 10); index++; } while (index < reqVerArray.length && requiredVersionPart === actualVersionPart); if (requiredVersionPart <= actualVersionPart && !isNaN(requiredVersionPart)) { isVersionSupported = true; } } } } catch (e2) { isVersionSupported = false; } return isVersionSupported; } /** Constructor for the Silverlight Runtime @class SilverlightRuntime @extends Runtime */ function SilverlightRuntime(options) { var I = this, initTimer; options = Basic.extend({ xap_url: Env.xap_url }, options); Runtime.call(this, options, type, { access_binary: Runtime.capTrue, access_image_binary: Runtime.capTrue, display_media: Runtime.capTrue, do_cors: Runtime.capTrue, drag_and_drop: false, report_upload_progress: Runtime.capTrue, resize_image: Runtime.capTrue, return_response_headers: function(value) { return value && I.mode === 'client'; }, return_response_type: Runtime.capTrue, return_status_code: function(code) { return I.mode === 'client' || !Basic.arrayDiff(code, [200, 404]); }, select_file: Runtime.capTrue, select_multiple: Runtime.capTrue, send_binary_string: Runtime.capTrue, send_browser_cookies: function(value) { return value && I.mode === 'browser'; }, send_custom_headers: function(value) { return value && I.mode === 'client'; }, send_multipart: Runtime.capTrue, slice_blob: Runtime.capTrue, stream_upload: true, summon_file_dialog: false, upload_filesize: Runtime.capTrue, use_http_method: function(methods) { return I.mode === 'client' || !Basic.arrayDiff(methods, ['GET', 'POST']); } }, { // capabilities that require specific mode return_response_headers: function(value) { return value ? 'client' : 'browser'; }, return_status_code: function(code) { return Basic.arrayDiff(code, [200, 404]) ? 'client' : ['client', 'browser']; }, send_browser_cookies: function(value) { return value ? 'browser' : 'client'; }, send_custom_headers: function(value) { return value ? 'client' : 'browser'; }, use_http_method: function(methods) { return Basic.arrayDiff(methods, ['GET', 'POST']) ? 'client' : ['client', 'browser']; } }); // minimal requirement if (!isInstalled('2.0.31005.0') || Env.browser === 'Opera') { this.mode = false; } Basic.extend(this, { getShim: function() { return Dom.get(this.uid).content.Moxie; }, shimExec: function(component, action) { var args = [].slice.call(arguments, 2); return I.getShim().exec(this.uid, component, action, args); }, init : function() { var container; container = this.getShimContainer(); container.innerHTML = '<object id="' + this.uid + '" data="data:application/x-silverlight," type="application/x-silverlight-2" width="100%" height="100%" style="outline:none;">' + '<param name="source" value="' + options.xap_url + '"/>' + '<param name="background" value="Transparent"/>' + '<param name="windowless" value="true"/>' + '<param name="enablehtmlaccess" value="true"/>' + '<param name="initParams" value="uid=' + this.uid + ',target=' + Env.global_event_dispatcher + '"/>' + '</object>'; // Init is dispatched by the shim initTimer = setTimeout(function() { if (I && !I.initialized) { // runtime might be already destroyed by this moment I.trigger("Error", new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR)); } }, Env.OS !== 'Windows'? 10000 : 5000); // give it more time to initialize in non Windows OS (like Mac) }, destroy: (function(destroy) { // extend default destroy method return function() { destroy.call(I); clearTimeout(initTimer); // initialization check might be still onwait options = initTimer = destroy = I = null; }; }(this.destroy)) }, extensions); } Runtime.addConstructor(type, SilverlightRuntime); return extensions; }); // Included from: src/javascript/runtime/silverlight/file/Blob.js /** * Blob.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/Blob @private */ define("moxie/runtime/silverlight/file/Blob", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/file/Blob" ], function(extensions, Basic, Blob) { return (extensions.Blob = Basic.extend({}, Blob)); }); // Included from: src/javascript/runtime/silverlight/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/FileInput @private */ define("moxie/runtime/silverlight/file/FileInput", [ "moxie/runtime/silverlight/Runtime" ], function(extensions) { var FileInput = { init: function(options) { function toFilters(accept) { var filter = ''; for (var i = 0; i < accept.length; i++) { filter += (filter !== '' ? '|' : '') + accept[i].title + " | *." + accept[i].extensions.replace(/,/g, ';*.'); } return filter; } this.getRuntime().shimExec.call(this, 'FileInput', 'init', toFilters(options.accept), options.name, options.multiple); this.trigger('ready'); } }; return (extensions.FileInput = FileInput); }); // Included from: src/javascript/runtime/silverlight/file/FileDrop.js /** * FileDrop.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/FileDrop @private */ define("moxie/runtime/silverlight/file/FileDrop", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Dom", "moxie/core/utils/Events" ], function(extensions, Dom, Events) { // not exactly useful, since works only in safari (...crickets...) var FileDrop = { init: function() { var comp = this, self = comp.getRuntime(), dropZone; dropZone = self.getShimContainer(); Events.addEvent(dropZone, 'dragover', function(e) { e.preventDefault(); e.stopPropagation(); e.dataTransfer.dropEffect = 'copy'; }, comp.uid); Events.addEvent(dropZone, 'dragenter', function(e) { e.preventDefault(); var flag = Dom.get(self.uid).dragEnter(e); // If handled, then stop propagation of event in DOM if (flag) { e.stopPropagation(); } }, comp.uid); Events.addEvent(dropZone, 'drop', function(e) { e.preventDefault(); var flag = Dom.get(self.uid).dragDrop(e); // If handled, then stop propagation of event in DOM if (flag) { e.stopPropagation(); } }, comp.uid); return self.shimExec.call(this, 'FileDrop', 'init'); } }; return (extensions.FileDrop = FileDrop); }); // Included from: src/javascript/runtime/silverlight/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/FileReader @private */ define("moxie/runtime/silverlight/file/FileReader", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/file/FileReader" ], function(extensions, Basic, FileReader) { return (extensions.FileReader = Basic.extend({}, FileReader)); }); // Included from: src/javascript/runtime/silverlight/file/FileReaderSync.js /** * FileReaderSync.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/FileReaderSync @private */ define("moxie/runtime/silverlight/file/FileReaderSync", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/file/FileReaderSync" ], function(extensions, Basic, FileReaderSync) { return (extensions.FileReaderSync = Basic.extend({}, FileReaderSync)); }); // Included from: src/javascript/runtime/silverlight/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/xhr/XMLHttpRequest @private */ define("moxie/runtime/silverlight/xhr/XMLHttpRequest", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/xhr/XMLHttpRequest" ], function(extensions, Basic, XMLHttpRequest) { return (extensions.XMLHttpRequest = Basic.extend({}, XMLHttpRequest)); }); // Included from: src/javascript/runtime/silverlight/runtime/Transporter.js /** * Transporter.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/runtime/Transporter @private */ define("moxie/runtime/silverlight/runtime/Transporter", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/runtime/Transporter" ], function(extensions, Basic, Transporter) { return (extensions.Transporter = Basic.extend({}, Transporter)); }); // Included from: src/javascript/runtime/silverlight/image/Image.js /** * Image.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/image/Image @private */ define("moxie/runtime/silverlight/image/Image", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/image/Image" ], function(extensions, Basic, Image) { return (extensions.Image = Basic.extend({}, Image)); }); // Included from: src/javascript/runtime/html4/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global File:true */ /** Defines constructor for HTML4 runtime. @class moxie/runtime/html4/Runtime @private */ define("moxie/runtime/html4/Runtime", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/runtime/Runtime", "moxie/core/utils/Env" ], function(Basic, x, Runtime, Env) { var type = 'html4', extensions = {}; function Html4Runtime(options) { var I = this , Test = Runtime.capTest , True = Runtime.capTrue ; Runtime.call(this, options, type, { access_binary: Test(window.FileReader || window.File && File.getAsDataURL), access_image_binary: false, display_media: Test(extensions.Image && (Env.can('create_canvas') || Env.can('use_data_uri_over32kb'))), do_cors: false, drag_and_drop: false, filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest return (Env.browser === 'Chrome' && Env.version >= 28) || (Env.browser === 'IE' && Env.version >= 10); }()), resize_image: function() { return extensions.Image && I.can('access_binary') && Env.can('create_canvas'); }, report_upload_progress: false, return_response_headers: false, return_response_type: function(responseType) { return !!~Basic.inArray(responseType, ['json', 'text', 'document', '']); }, return_status_code: function(code) { return !Basic.arrayDiff(code, [200, 404]); }, select_file: function() { return Env.can('use_fileinput'); }, select_multiple: false, send_binary_string: false, send_custom_headers: false, send_multipart: true, slice_blob: false, stream_upload: function() { return I.can('select_file'); }, summon_file_dialog: Test(function() { // yeah... some dirty sniffing here... return (Env.browser === 'Firefox' && Env.version >= 4) || (Env.browser === 'Opera' && Env.version >= 12) || (Env.browser === 'IE' && Env.version >= 10) || !!~Basic.inArray(Env.browser, ['Chrome', 'Safari']); }()), upload_filesize: True, use_http_method: function(methods) { return !Basic.arrayDiff(methods, ['GET', 'POST']); } }); Basic.extend(this, { init : function() { this.trigger("Init"); }, destroy: (function(destroy) { // extend default destroy method return function() { destroy.call(I); destroy = I = null; }; }(this.destroy)) }); Basic.extend(this.getShim(), extensions); } Runtime.addConstructor(type, Html4Runtime); return extensions; }); // Included from: src/javascript/runtime/html4/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html4/file/FileInput @private */ define("moxie/runtime/html4/file/FileInput", [ "moxie/runtime/html4/Runtime", "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/utils/Events", "moxie/core/utils/Mime", "moxie/core/utils/Env" ], function(extensions, Basic, Dom, Events, Mime, Env) { function FileInput() { var _uid, _files = [], _mimes = [], _options; function addInput() { var comp = this, I = comp.getRuntime(), shimContainer, browseButton, currForm, form, input, uid; uid = Basic.guid('uid_'); shimContainer = I.getShimContainer(); // we get new ref everytime to avoid memory leaks in IE if (_uid) { // move previous form out of the view currForm = Dom.get(_uid + '_form'); if (currForm) { Basic.extend(currForm.style, { top: '100%' }); } } // build form in DOM, since innerHTML version not able to submit file for some reason form = document.createElement('form'); form.setAttribute('id', uid + '_form'); form.setAttribute('method', 'post'); form.setAttribute('enctype', 'multipart/form-data'); form.setAttribute('encoding', 'multipart/form-data'); Basic.extend(form.style, { overflow: 'hidden', position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }); input = document.createElement('input'); input.setAttribute('id', uid); input.setAttribute('type', 'file'); input.setAttribute('name', 'Filedata'); input.setAttribute('accept', _mimes.join(',')); Basic.extend(input.style, { fontSize: '999px', opacity: 0 }); form.appendChild(input); shimContainer.appendChild(form); // prepare file input to be placed underneath the browse_button element Basic.extend(input.style, { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }); if (Env.browser === 'IE' && Env.version < 10) { Basic.extend(input.style, { filter : "progid:DXImageTransform.Microsoft.Alpha(opacity=0)" }); } input.onchange = function() { // there should be only one handler for this var file; if (!this.value) { return; } if (this.files) { file = this.files[0]; } else { file = { name: this.value }; } _files = [file]; this.onchange = function() {}; // clear event handler addInput.call(comp); // after file is initialized as o.File, we need to update form and input ids comp.bind('change', function() { var input = Dom.get(uid), form = Dom.get(uid + '_form'), file; if (comp.files.length && input && form) { file = comp.files[0]; input.setAttribute('id', file.uid); form.setAttribute('id', file.uid + '_form'); // set upload target form.setAttribute('target', file.uid + '_iframe'); } input = form = null; }, 998); input = form = null; comp.trigger('change'); }; // route click event to the input if (I.can('summon_file_dialog')) { browseButton = Dom.get(_options.browse_button); Events.removeEvent(browseButton, 'click', comp.uid); Events.addEvent(browseButton, 'click', function(e) { if (input && !input.disabled) { // for some reason FF (up to 8.0.1 so far) lets to click disabled input[type=file] input.click(); } e.preventDefault(); }, comp.uid); } _uid = uid; shimContainer = currForm = browseButton = null; // trigger ready event asynchronously comp.trigger({ type: 'ready', async: true }); } Basic.extend(this, { init: function(options) { var comp = this, I = comp.getRuntime(), shimContainer; // figure out accept string _options = options; _mimes = options.accept.mimes || Mime.extList2mimes(options.accept, I.can('filter_by_extension')); shimContainer = I.getShimContainer(); (function() { var browseButton, zIndex, top; browseButton = Dom.get(options.browse_button); // Route click event to the input[type=file] element for browsers that support such behavior if (I.can('summon_file_dialog')) { if (Dom.getStyle(browseButton, 'position') === 'static') { browseButton.style.position = 'relative'; } zIndex = parseInt(Dom.getStyle(browseButton, 'z-index'), 10) || 1; browseButton.style.zIndex = zIndex; shimContainer.style.zIndex = zIndex - 1; } /* Since we have to place input[type=file] on top of the browse_button for some browsers, browse_button loses interactivity, so we restore it here */ top = I.can('summon_file_dialog') ? browseButton : shimContainer; Events.addEvent(top, 'mouseover', function() { comp.trigger('mouseenter'); }, comp.uid); Events.addEvent(top, 'mouseout', function() { comp.trigger('mouseleave'); }, comp.uid); Events.addEvent(top, 'mousedown', function() { comp.trigger('mousedown'); }, comp.uid); Events.addEvent(Dom.get(options.container), 'mouseup', function() { comp.trigger('mouseup'); }, comp.uid); browseButton = null; }()); addInput.call(this); shimContainer = null; }, getFiles: function() { return _files; }, disable: function(state) { var input; if ((input = Dom.get(_uid))) { input.disabled = !!state; } }, destroy: function() { var I = this.getRuntime(), shimContainer = I.getShimContainer(); Events.removeAllEvents(shimContainer, this.uid); Events.removeAllEvents(_options && Dom.get(_options.container), this.uid); Events.removeAllEvents(_options && Dom.get(_options.browse_button), this.uid); if (shimContainer) { shimContainer.innerHTML = ''; } _uid = _files = _mimes = _options = null; } }); } return (extensions.FileInput = FileInput); }); // Included from: src/javascript/runtime/html4/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html4/file/FileReader @private */ define("moxie/runtime/html4/file/FileReader", [ "moxie/runtime/html4/Runtime", "moxie/runtime/html5/file/FileReader" ], function(extensions, FileReader) { return (extensions.FileReader = FileReader); }); // Included from: src/javascript/runtime/html4/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html4/xhr/XMLHttpRequest @private */ define("moxie/runtime/html4/xhr/XMLHttpRequest", [ "moxie/runtime/html4/Runtime", "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/utils/Url", "moxie/core/Exceptions", "moxie/core/utils/Events", "moxie/file/Blob", "moxie/xhr/FormData", "moxie/core/JSON" ], function(extensions, Basic, Dom, Url, x, Events, Blob, FormData, parseJSON) { function XMLHttpRequest() { var _status, _response, _iframe; function cleanup(cb) { var target = this, uid, form, inputs, i, hasFile = false; if (!_iframe) { return; } uid = _iframe.id.replace(/_iframe$/, ''); form = Dom.get(uid + '_form'); if (form) { inputs = form.getElementsByTagName('input'); i = inputs.length; while (i--) { switch (inputs[i].getAttribute('type')) { case 'hidden': inputs[i].parentNode.removeChild(inputs[i]); break; case 'file': hasFile = true; // flag the case for later break; } } inputs = []; if (!hasFile) { // we need to keep the form for sake of possible retries form.parentNode.removeChild(form); } form = null; } // without timeout, request is marked as canceled (in console) setTimeout(function() { Events.removeEvent(_iframe, 'load', target.uid); if (_iframe.parentNode) { // #382 _iframe.parentNode.removeChild(_iframe); } // check if shim container has any other children, if - not, remove it as well var shimContainer = target.getRuntime().getShimContainer(); if (!shimContainer.children.length) { shimContainer.parentNode.removeChild(shimContainer); } shimContainer = _iframe = null; cb(); }, 1); } Basic.extend(this, { send: function(meta, data) { var target = this, I = target.getRuntime(), uid, form, input, blob; _status = _response = null; function createIframe() { var container = I.getShimContainer() || document.body , temp = document.createElement('div') ; // IE 6 won't be able to set the name using setAttribute or iframe.name temp.innerHTML = '<iframe id="' + uid + '_iframe" name="' + uid + '_iframe" src="javascript:&quot;&quot;" style="display:none"></iframe>'; _iframe = temp.firstChild; container.appendChild(_iframe); /* _iframe.onreadystatechange = function() { //console.info(_iframe.readyState); };*/ Events.addEvent(_iframe, 'load', function() { // _iframe.onload doesn't work in IE lte 8 var el; try { el = _iframe.contentWindow.document || _iframe.contentDocument || window.frames[_iframe.id].document; // try to detect some standard error pages if (/^4\d{2}\s/.test(el.title) && el.getElementsByTagName('address').length) { // standard Apache style _status = el.title.replace(/^(\d+).*$/, '$1'); } else { _status = 200; // get result _response = Basic.trim(el.body.innerHTML); // we need to fire these at least once target.trigger({ type: 'progress', loaded: _response.length, total: _response.length }); if (blob) { // if we were uploading a file target.trigger({ type: 'uploadprogress', loaded: blob.size || 1025, total: blob.size || 1025 }); } } } catch (ex) { if (Url.hasSameOrigin(meta.url)) { // if response is sent with error code, iframe in IE gets redirected to res://ieframe.dll/http_x.htm // which obviously results to cross domain error (wtf?) _status = 404; } else { cleanup.call(target, function() { target.trigger('error'); }); return; } } cleanup.call(target, function() { target.trigger('load'); }); }, target.uid); } // end createIframe // prepare data to be sent and convert if required if (data instanceof FormData && data.hasBlob()) { blob = data.getBlob(); uid = blob.uid; input = Dom.get(uid); form = Dom.get(uid + '_form'); if (!form) { throw new x.DOMException(x.DOMException.NOT_FOUND_ERR); } } else { uid = Basic.guid('uid_'); form = document.createElement('form'); form.setAttribute('id', uid + '_form'); form.setAttribute('method', meta.method); form.setAttribute('enctype', 'multipart/form-data'); form.setAttribute('encoding', 'multipart/form-data'); form.setAttribute('target', uid + '_iframe'); I.getShimContainer().appendChild(form); } if (data instanceof FormData) { data.each(function(value, name) { if (value instanceof Blob) { if (input) { input.setAttribute('name', name); } } else { var hidden = document.createElement('input'); Basic.extend(hidden, { type : 'hidden', name : name, value : value }); form.appendChild(hidden); } }); } // set destination url form.setAttribute("action", meta.url); createIframe(); form.submit(); target.trigger('loadstart'); }, getStatus: function() { return _status; }, getResponse: function(responseType) { if ('json' === responseType) { // strip off <pre>..</pre> tags that might be enclosing the response if (Basic.typeOf(_response) === 'string') { try { return parseJSON(_response.replace(/^\s*<pre[^>]*>/, '').replace(/<\/pre>\s*$/, '')); } catch (ex) { return null; } } } else if ('document' === responseType) { } return _response; }, abort: function() { var target = this; if (_iframe && _iframe.contentWindow) { if (_iframe.contentWindow.stop) { // FireFox/Safari/Chrome _iframe.contentWindow.stop(); } else if (_iframe.contentWindow.document.execCommand) { // IE _iframe.contentWindow.document.execCommand('Stop'); } else { _iframe.src = "about:blank"; } } cleanup.call(this, function() { // target.dispatchEvent('readystatechange'); target.dispatchEvent('abort'); }); } }); } return (extensions.XMLHttpRequest = XMLHttpRequest); }); // Included from: src/javascript/runtime/html4/image/Image.js /** * Image.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html4/image/Image @private */ define("moxie/runtime/html4/image/Image", [ "moxie/runtime/html4/Runtime", "moxie/runtime/html5/image/Image" ], function(extensions, Image) { return (extensions.Image = Image); }); expose(["moxie/core/utils/Basic","moxie/core/I18n","moxie/core/utils/Mime","moxie/core/utils/Env","moxie/core/utils/Dom","moxie/core/Exceptions","moxie/core/EventTarget","moxie/core/utils/Encode","moxie/runtime/Runtime","moxie/runtime/RuntimeClient","moxie/file/Blob","moxie/file/File","moxie/file/FileInput","moxie/file/FileDrop","moxie/runtime/RuntimeTarget","moxie/file/FileReader","moxie/core/utils/Url","moxie/file/FileReaderSync","moxie/xhr/FormData","moxie/xhr/XMLHttpRequest","moxie/runtime/Transporter","moxie/core/JSON","moxie/image/Image","moxie/core/utils/Events"]); })(this);/** * o.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global moxie:true */ /** Globally exposed namespace with the most frequently used public classes and handy methods. @class o @static @private */ (function() { "use strict"; var o = {}, inArray = moxie.core.utils.Basic.inArray; // directly add some public classes // (we do it dynamically here, since for custom builds we cannot know beforehand what modules were included) (function addAlias(ns) { var name, itemType; for (name in ns) { itemType = typeof(ns[name]); if (itemType === 'object' && !~inArray(name, ['Exceptions', 'Env', 'Mime'])) { addAlias(ns[name]); } else if (itemType === 'function') { o[name] = ns[name]; } } })(window.moxie); // add some manually o.Env = window.moxie.core.utils.Env; o.Mime = window.moxie.core.utils.Mime; o.Exceptions = window.moxie.core.Exceptions; // expose globally window.mOxie = o; if (!window.o) { window.o = o; } return o; })();
bug fix
web/js/lib/jquery/moxie.js
bug fix
<ide><path>eb/js/lib/jquery/moxie.js <ide> runtime.bind('Init', function() { <ide> // mark runtime as initialized <ide> runtime.initialized = true; <del> <ide> // jailbreak ... <ide> setTimeout(function() { <add> //console.log(runtime,typeof runtime); <ide> runtime.clients++; <ide> // this will be triggered on component <ide> comp.trigger('RuntimeInit', runtime); <del> }, 200); <add> }, 2000); <ide> }); <ide> <ide> runtime.bind('Error', function() {
JavaScript
mit
268a32ee0a7259c343e6aa572ad24cbf6393e5e2
0
reiclone/doushio,KoinoAoi/meguca,KoinoAoi/meguca,reiclone/doushio,theGaggle/sleepingpizza,reiclone/doushio,KoinoAoi/meguca,theGaggle/sleepingpizza,KoinoAoi/meguca,theGaggle/sleepingpizza,theGaggle/sleepingpizza,reiclone/doushio,theGaggle/sleepingpizza,reiclone/doushio,theGaggle/sleepingpizza,KoinoAoi/meguca
/* Client-side administration logic */ let main = require('main'), {$, $threads, _, Backbone, common, config, etc, lang} = main; const ident = window.IDENT; // Pass login status to ./www/js/login.js window.loggedInUser = ident.email; window.x_csrf = ident.csrf; $('<link/>', { rel: 'stylesheet', href: `${config.MEDIA_URL}css/mod.css?v=${cssHash}` }).appendTo('head'); let ToolboxView = Backbone.View.extend({ tagName: 'div', id: 'toolbox', className: 'mod modal', initialize() { this.render(); }, render() { let specs = this.specs = [ 'clearSelection', 'spoilerImages', 'deleteImages', 'deletePosts', 'lockThread', 'toggleMnemonics' ]; if (ident.auth === 'Admin') specs.push('sendNotification', 'dispatchFun', 'renderPanel'); let controls = '<span>'; for (let i = 0; i < specs.length; i++) { const ln = lang.mod[specs[i]]; controls += common.parseHTML `<a class="modButton" data-kind="${i}" title="${ln[1]}"> ${ln[0]} </a>`; } controls += '</span>'; this.$controls = $(controls); this.$checkboxToggle = $(common.parseHTML `<style> .postCheckbox { display: inline-block; } </style>` ) .appendTo('head') // Disabled only works if the emelemnt is in the DOM .prop('disabled', true); this.$toggle = $(`<a id="toolboxToggle">${lang.show}</a>`); this.$el.prepend(this.$controls, this.$toggle) .appendTo('body'); // Sets mnemonic visability this.$mnemonicStyle = $(common.parseHTML `<style> header > .mod.addr { display: none; } </style>` ) .appendTo('head') .prop('disabled', localStorage.noMnemonics !== 'true'); return this; }, events: { 'click #toolboxToggle': 'toggleButtons', 'click .modButton': 'buttonHandler' }, toggleButtons() { const hidden = !this.model.get('shown'); this.$toggle.text(lang[hidden ? 'hide' : 'show']); this.$controls.toggle(0); this.$checkboxToggle.prop('disabled', !hidden); this.model.set('shown', hidden); }, buttonHandler(event) { this[this.specs[event.target.getAttribute('data-kind')]](); }, getSelected() { let checked = []; this.loopCheckboxes(function (el) { if (el.checked) checked.push(etc.getID(el)); }); // Postform will not have an ID, so we remove falsy values return _.compact(checked); }, clearSelection() { this.loopCheckboxes(el => el.checked = false); }, loopCheckboxes(func) { const els = $threads[0].getElementsByClassName('postCheckbox'); for (let i = 0; i < els.length; i++) { func(els[i]); } }, toggleMnemonics() { const hide = localStorage.noMnemonics === 'true'; this.$mnemonicStyle.prop('disabled', hide); localStorage.noMnemonics = !hide; }, spoilerImages() { main.command('send', [common.SPOILER_IMAGES, ...this.getSelected()]); } }); let toolbox = new ToolboxView({ model: new Backbone.Model() });
admin/client.js
/* Client-side administration logic */ let main = require('main'), {$, $threads, _, Backbone, common, config, etc, lang} = main; const ident = window.IDENT; // Pass login status to ./www/js/login.js window.loggedInUser = ident.email; window.x_csrf = ident.csrf; $('<link/>', { rel: 'stylesheet', href: `${config.MEDIA_URL}css/mod.css?v=${cssHash}` }).appendTo('head'); let ToolboxView = Backbone.View.extend({ tagName: 'div', id: 'toolbox', className: 'mod modal', initialize() { this.render(); }, render() { let specs = this.specs = [ 'clearSelection', 'spoilerImages', 'deleteImages', 'deletePosts', 'lockThread', 'toggleMnemonics' ]; if (ident.auth === 'Admin') specs.push('sendNotification', 'dispatchFun', 'renderPanel'); let controls = '<span>'; for (let i = 0; i < specs.length; i++) { const ln = lang.mod[specs[i]]; controls += common.parseHTML `<a class="modButton" data-kind="${i}" title="${ln[1]}"> ${ln[0]} </a>`; } controls += '</span>'; this.$controls = $(controls); this.$checkboxToggle = $('<style/>', { html: '.postCheckbox {display: inline-block;}' }) .appendTo('head') // Disabled only works if the emelemnt is in the DOM .prop('disabled', true); this.$toggle = $(`<a id="toolboxToggle">${lang.show}</a>`); this.$el.prepend(this.$controls, this.$toggle) .appendTo('body'); // Sets mnemonic visability this.$mnemonicStyle = $(common.parseHTML `<style> header > .mod.addr { display: none; } </style>` ) .appendTo('head') .prop('disabled', localStorage.noMnemonics !== 'true'); return this; }, events: { 'click #toolboxToggle': 'toggleButtons', 'click .modButton': 'buttonHandler' }, toggleButtons() { const hidden = !this.model.get('shown'); this.$toggle.text(lang[hidden ? 'hide' : 'show']); this.$controls.toggle(0); this.$checkboxToggle.prop('disabled', !hidden); this.model.set('shown', hidden); }, buttonHandler(event) { this[this.specs[event.target.getAttribute('data-kind')]](); }, getSelected() { let checked = []; this.loopCheckboxes(function (el) { if (el.checked) checked.push(etc.getID(el)); }); // Postform will not have an ID, so we remove falsy values return _.compact(checked); }, clearSelection() { this.loopCheckboxes(el => el.checked = false); }, loopCheckboxes(func) { const els = $threads[0].getElementsByClassName('postCheckbox'); for (let i = 0; i < els.length; i++) { func(els[i]); } }, toggleMnemonics() { const hide = localStorage.noMnemonics === 'true'; this.$mnemonicStyle.prop('disabled', hide); localStorage.noMnemonics = !hide; }, spoilerImages() { main.command('send', [common.SPOILER_IMAGES, ...this.getSelected()]); } }); let toolbox = new ToolboxView({ model: new Backbone.Model() });
Slightly more readable string
admin/client.js
Slightly more readable string
<ide><path>dmin/client.js <ide> controls += '</span>'; <ide> this.$controls = $(controls); <ide> <del> this.$checkboxToggle = $('<style/>', { <del> html: '.postCheckbox {display: inline-block;}' <del> }) <add> this.$checkboxToggle = $(common.parseHTML <add> `<style> <add> .postCheckbox { <add> display: inline-block; <add> } <add> </style>` <add> ) <ide> .appendTo('head') <ide> // Disabled only works if the emelemnt is in the DOM <ide> .prop('disabled', true);
Java
mit
c2b998b572734e86a3be7c983d3be580e77e5fa6
0
miciek/problem-hunting,miciek/problem-hunting
package com.michalplachta.hunting.uva.s164; import java.util.Scanner; /** * UVA 164 - String Computer * * http://uva.onlinejudge.org/external/1/164.html * * @category string, dynamic-programming, edit-distance, alignment * @author micio */ class Main { public static class StringAlignment { private char[] A; private char[] B; private int[][] dp; private final int match; private final int mismatch; private final int deletion; // represented as '\u0000' in B private final int insertion; // represented as '\u0000' in A public StringAlignment(int matchScore, int mismatchScore, int deletionScore, int insertionScore) { match = matchScore; mismatch = mismatchScore; deletion = deletionScore; insertion = insertionScore; } public void solve(String a, String b) { // TODO } public int getScore() { return dp[A.length - 1][B.length - 1]; } } public static void main(String[] args) { } }
src/com/michalplachta/hunting/uva/s164/Main.java
package com.michalplachta.hunting.uva.s164; import java.util.Scanner; /** * UVA 164 - String Computer * * http://uva.onlinejudge.org/external/1/164.html * * @category string, dynamic-programming, edit-distance, alignment * @author micio */ class Main { public static void main(String[] args) { } }
added StringAlignment template
src/com/michalplachta/hunting/uva/s164/Main.java
added StringAlignment template
<ide><path>rc/com/michalplachta/hunting/uva/s164/Main.java <ide> * @category string, dynamic-programming, edit-distance, alignment <ide> * @author micio <ide> */ <del>class Main { <add>class Main { <add> <add> public static class StringAlignment { <add> private char[] A; <add> private char[] B; <add> private int[][] dp; <add> private final int match; <add> private final int mismatch; <add> private final int deletion; // represented as '\u0000' in B <add> private final int insertion; // represented as '\u0000' in A <add> <add> public StringAlignment(int matchScore, int mismatchScore, int deletionScore, int insertionScore) { <add> match = matchScore; <add> mismatch = mismatchScore; <add> deletion = deletionScore; <add> insertion = insertionScore; <add> } <add> <add> public void solve(String a, String b) { <add> // TODO <add> } <add> <add> public int getScore() { <add> return dp[A.length - 1][B.length - 1]; <add> } <add> } <ide> <ide> public static void main(String[] args) { <ide>
Java
apache-2.0
a96d197e2450ac543964b2ce43811e01515e67ae
0
BusTechnology/geocoder-api-adapter
package geocoder; import static org.junit.Assert.assertTrue; import java.io.IOException; import org.junit.Before; import org.junit.Test; import okhttp3.HttpUrl; import okhttp3.Response; public class GeocoderTest { private static NYCGeoclient nycGeoclient; @Before public void init() { nycGeoclient = new NYCGeoclient(); } // Not mocked for Travis use //@Test public void shouldReceiveResponse() throws IOException { Response response = buildSearchRequest("input"); assertTrue("response is successful", response.isSuccessful()); } //@Test(expected=IOException.class) public void shouldThrowException() throws IOException { Response response = buildSearchRequest("aa"); assertTrue("response is successful", response.isSuccessful()); } public Response buildSearchRequest(String query) throws IOException { HttpUrl urlWithKey = null; try { urlWithKey = nycGeoclient.keyVerify(); } catch (Exception e) { e.printStackTrace(); } Response response = Geocoder.search(urlWithKey, query, "123"); return response; } }
src/test/java/geocoder/GeocoderTest.java
package geocoder; import static org.junit.Assert.assertTrue; import java.io.IOException; import org.junit.Before; import org.junit.Test; import okhttp3.HttpUrl; import okhttp3.Response; public class GeocoderTest { private static NYCGeoclient nycGeoclient; @Before public void init() { nycGeoclient = new NYCGeoclient(); } @Test public void shouldReceiveResponse() throws IOException { Response response = buildSearchRequest("input"); assertTrue("response is successful", response.isSuccessful()); } @Test(expected=IOException.class) public void shouldThrowException() throws IOException { Response response = buildSearchRequest("aa"); assertTrue("response is successful", response.isSuccessful()); } public Response buildSearchRequest(String query) throws IOException { HttpUrl urlWithKey = null; try { urlWithKey = nycGeoclient.keyVerify(); } catch (Exception e) { e.printStackTrace(); } Response response = Geocoder.search(urlWithKey, query, "123"); return response; } }
Update GeocoderTest.java
src/test/java/geocoder/GeocoderTest.java
Update GeocoderTest.java
<ide><path>rc/test/java/geocoder/GeocoderTest.java <ide> public void init() { <ide> nycGeoclient = new NYCGeoclient(); <ide> } <del> <del> @Test <add> // Not mocked for Travis use <add> //@Test <ide> public void shouldReceiveResponse() throws IOException { <ide> <ide> Response response = buildSearchRequest("input"); <ide> assertTrue("response is successful", response.isSuccessful()); <ide> } <ide> <del> @Test(expected=IOException.class) <add> //@Test(expected=IOException.class) <ide> public void shouldThrowException() throws IOException { <ide> Response response = buildSearchRequest("aa"); <ide> assertTrue("response is successful", response.isSuccessful());
Java
apache-2.0
089404becb13d12df04230f5370a8788a4e554bf
0
nelsongraca/wildfly-swarm,jamesnetherton/wildfly-swarm,kenfinnigan/wildfly-swarm,gastaldi/wildfly-swarm,emag/wildfly-swarm,wildfly-swarm/wildfly-swarm-core,Ladicek/wildfly-swarm,jamezp/wildfly-swarm,juangon/wildfly-swarm,wildfly-swarm/wildfly-swarm,christian-posta/wildfly-swarm,gastaldi/wildfly-swarm,juangon/wildfly-swarm,christian-posta/wildfly-swarm,nelsongraca/wildfly-swarm,bobmcwhirter/wildfly-swarm,nelsongraca/wildfly-swarm,jamesnetherton/wildfly-swarm,heiko-braun/wildfly-swarm-1,christian-posta/wildfly-swarm,gastaldi/wildfly-swarm,Ladicek/wildfly-swarm,wildfly-swarm/wildfly-swarm-core,kenfinnigan/wildfly-swarm,bobmcwhirter/wildfly-swarm,juangon/wildfly-swarm,jamezp/wildfly-swarm,jamesnetherton/wildfly-swarm,jamezp/wildfly-swarm,heiko-braun/wildfly-swarm-1,heiko-braun/wildfly-swarm-1,wildfly-swarm/wildfly-swarm,bobmcwhirter/wildfly-swarm,kenfinnigan/wildfly-swarm,emag/wildfly-swarm,gastaldi/wildfly-swarm,Ladicek/wildfly-swarm,emag/wildfly-swarm,wildfly-swarm/wildfly-swarm-core,nelsongraca/wildfly-swarm,jamesnetherton/wildfly-swarm,wildfly-swarm/wildfly-swarm-core,wildfly-swarm/wildfly-swarm-core,bobmcwhirter/wildfly-swarm,wildfly-swarm/wildfly-swarm,juangon/wildfly-swarm,jamezp/wildfly-swarm,wildfly-swarm/wildfly-swarm,kenfinnigan/wildfly-swarm,jamesnetherton/wildfly-swarm,juangon/wildfly-swarm,nelsongraca/wildfly-swarm,bobmcwhirter/wildfly-swarm,Ladicek/wildfly-swarm,christian-posta/wildfly-swarm,Ladicek/wildfly-swarm,emag/wildfly-swarm,kenfinnigan/wildfly-swarm,gastaldi/wildfly-swarm,heiko-braun/wildfly-swarm-1,christian-posta/wildfly-swarm,heiko-braun/wildfly-swarm-1,jamezp/wildfly-swarm,wildfly-swarm/wildfly-swarm,emag/wildfly-swarm
/** * Copyright 2015-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.swarm.plugin.maven; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.eclipse.aether.DefaultRepositorySystemSession; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Properties; /** * @author Bob McWhirter */ public abstract class AbstractSwarmMojo extends AbstractMojo { protected static String VERSION; @Parameter(defaultValue = "${project}", readonly = true) protected MavenProject project; @Parameter(defaultValue = "${repositorySystemSession}", readonly = true) protected DefaultRepositorySystemSession repositorySystemSession; @Parameter(defaultValue = "${project.remoteArtifactRepositories}", readonly = true) protected List<ArtifactRepository> remoteRepositories; @Parameter(defaultValue = "${project.build.directory}") protected String projectBuildDir; @Parameter(alias = "mainClass") protected String mainClass; @Parameter(alias = "properties") protected Properties properties; @Parameter(alias = "propertiesFile") protected String propertiesFile; @Parameter(alias = "environment") protected Properties environment; @Parameter(alias = "environmentFile") protected String environmentFile; @Parameter(alias = "modules") protected String[] additionalModules; AbstractSwarmMojo() { if (this.additionalModules == null) { this.additionalModules = new String[] {"modules"}; } } protected void initProperties() throws MojoFailureException { if (this.properties == null) { this.properties = new Properties(); } if (this.propertiesFile != null) { this.properties.putAll(loadProperties(this.propertiesFile)); } // copy any jboss.*, swarm.*, maven.*, or wildfly.* sysprops from System, // along with anything that shadows a specified property System.getProperties().stringPropertyNames().forEach(key -> { if (key.startsWith("jboss.") || key.startsWith("swarm.") || key.startsWith("wildfly.") || key.startsWith("maven.") || this.properties.containsKey(key)) { this.properties.put(key, System.getProperty(key)); } }); } protected void initEnvironment() throws MojoFailureException { if (this.environment == null) { this.environment = new Properties(); } if (this.environmentFile != null) { this.environment.putAll(loadProperties(this.environmentFile)); } } protected static Properties loadProperties(final InputStream in) throws IOException { final Properties props = new Properties(); try { props.load(in); } finally { in.close(); } return props; } protected static Properties loadProperties(final String file) throws MojoFailureException { return loadProperties(new File(file)); } protected static Properties loadProperties(final File file) throws MojoFailureException { try { return loadProperties(new FileInputStream(file)); } catch (FileNotFoundException e) { throw new MojoFailureException("No such file: " + file, e); } catch (IOException e) { throw new MojoFailureException("Error reading file: " + file, e); } } static { try { VERSION = loadProperties(PackageMojo.class .getClassLoader() .getResourceAsStream("META-INF/maven/org.wildfly.swarm/wildfly-swarm-plugin/pom.properties")) .getProperty("version"); } catch (IOException e) { e.printStackTrace(); } } }
plugin/src/main/java/org/wildfly/swarm/plugin/maven/AbstractSwarmMojo.java
/** * Copyright 2015-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.swarm.plugin.maven; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.eclipse.aether.DefaultRepositorySystemSession; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Properties; /** * @author Bob McWhirter */ public abstract class AbstractSwarmMojo extends AbstractMojo { protected static String VERSION; @Parameter(defaultValue = "${project}", readonly = true) protected MavenProject project; @Parameter(defaultValue = "${repositorySystemSession}", readonly = true) protected DefaultRepositorySystemSession repositorySystemSession; @Parameter(defaultValue = "${project.remoteArtifactRepositories}", readonly = true) protected List<ArtifactRepository> remoteRepositories; @Parameter(defaultValue = "${project.build.directory}") protected String projectBuildDir; @Parameter(alias = "mainClass") protected String mainClass; @Parameter(alias = "properties") protected Properties properties; @Parameter(alias = "propertiesFile") protected String propertiesFile; @Parameter(alias = "environment") protected Properties environment; @Parameter(alias = "environmentFile") protected String environmentFile; @Parameter(alias = "modules") protected String[] additionalModules; AbstractSwarmMojo() { if (this.additionalModules == null) { this.additionalModules = new String[] {"modules"}; } } protected void initProperties() throws MojoFailureException { if (this.properties == null) { this.properties = new Properties(); } if (this.propertiesFile != null) { this.properties.putAll(loadProperties(this.propertiesFile)); } // copy any jboss.*, swarm.*, or wildfly.* sysprops from System, along with anything that shadows // a specified property System.getProperties().stringPropertyNames().forEach(key -> { if (key.startsWith("jboss.") || key.startsWith("swarm.") || key.startsWith("wildfly.") || this.properties.containsKey(key)) { this.properties.put(key, System.getProperty(key)); } }); } protected void initEnvironment() throws MojoFailureException { if (this.environment == null) { this.environment = new Properties(); } if (this.environmentFile != null) { this.environment.putAll(loadProperties(this.environmentFile)); } } protected static Properties loadProperties(final InputStream in) throws IOException { final Properties props = new Properties(); try { props.load(in); } finally { in.close(); } return props; } protected static Properties loadProperties(final String file) throws MojoFailureException { return loadProperties(new File(file)); } protected static Properties loadProperties(final File file) throws MojoFailureException { try { return loadProperties(new FileInputStream(file)); } catch (FileNotFoundException e) { throw new MojoFailureException("No such file: " + file, e); } catch (IOException e) { throw new MojoFailureException("Error reading file: " + file, e); } } static { try { VERSION = loadProperties(PackageMojo.class .getClassLoader() .getResourceAsStream("META-INF/maven/org.wildfly.swarm/wildfly-swarm-plugin/pom.properties")) .getProperty("version"); } catch (IOException e) { e.printStackTrace(); } } }
Include maven.* in the copied sysprops The start task no longer uses SwarmExecutor#withDefaultSystemProperties(), so we need to ensure that maven props get copied in initProperties instead.
plugin/src/main/java/org/wildfly/swarm/plugin/maven/AbstractSwarmMojo.java
Include maven.* in the copied sysprops
<ide><path>lugin/src/main/java/org/wildfly/swarm/plugin/maven/AbstractSwarmMojo.java <ide> if (this.propertiesFile != null) { <ide> this.properties.putAll(loadProperties(this.propertiesFile)); <ide> } <del> // copy any jboss.*, swarm.*, or wildfly.* sysprops from System, along with anything that shadows <del> // a specified property <add> // copy any jboss.*, swarm.*, maven.*, or wildfly.* sysprops from System, <add> // along with anything that shadows a specified property <ide> System.getProperties().stringPropertyNames().forEach(key -> { <ide> if (key.startsWith("jboss.") || <ide> key.startsWith("swarm.") || <ide> key.startsWith("wildfly.") || <add> key.startsWith("maven.") || <ide> this.properties.containsKey(key)) { <ide> this.properties.put(key, System.getProperty(key)); <ide> }
Java
lgpl-2.1
0e8dcf1c04047881714e4653282873ca7ed47aee
0
spotbugs/spotbugs,KengoTODA/spotbugs,spotbugs/spotbugs,spotbugs/spotbugs,sewe/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,sewe/spotbugs,KengoTODA/spotbugs,johnscancella/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,KengoTODA/spotbugs,sewe/spotbugs,spotbugs/spotbugs,johnscancella/spotbugs,johnscancella/spotbugs
/* * FindBugs - Find Bugs in Java programs * Copyright (C) 2003-2008, University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs.ba.jsr305; import java.lang.annotation.ElementType; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.annotation.meta.When; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.ba.AbstractClassMember; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.XMethod; import edu.umd.cs.findbugs.classfile.ClassDescriptor; import edu.umd.cs.findbugs.classfile.DescriptorFactory; import edu.umd.cs.findbugs.classfile.analysis.AnnotatedObject; import edu.umd.cs.findbugs.classfile.analysis.AnnotationValue; import edu.umd.cs.findbugs.classfile.analysis.EnumValue; import edu.umd.cs.findbugs.util.DualKeyHashMap; /** * Figure out where and how type qualifier annotations are applied. * * @author William Pugh * @author David Hovemeyer */ public class TypeQualifierApplications { static final boolean DEBUG = SystemProperties.getBoolean("ctq.applications.debug"); static final String DEBUG_METHOD = SystemProperties.getProperty("ctq.applications.method"); static final boolean DEBUG_DEFAULT_ANNOTATION = SystemProperties.getBoolean("ctq.applications.default.debug"); /** * Should exclusive type qualifiers be handled? */ static final boolean CHECK_EXCLUSIVE = true;//SystemProperties.getBoolean("ctq.applications.checkexclusive"); static final boolean CHECK_EXHAUSTIVE = true; //SystemProperties.getBoolean("ctq.applications.checkexhaustive"); static class Data { /** Type qualifier annotations applied directly to methods/fields/classes/etc. */ private Map<AnnotatedObject, Collection<AnnotationValue>> directObjectAnnotations = new HashMap<AnnotatedObject, Collection<AnnotationValue>>(); /** Type qualifier annotations applied directly to method parameters. */ private DualKeyHashMap<XMethod, Integer, Collection<AnnotationValue>> directParameterAnnotations = new DualKeyHashMap<XMethod, Integer, Collection<AnnotationValue>>(); /** * Map of TypeQualifierValues to maps containing, for each AnnotatedObject, * the effective TypeQualifierAnnotation (if any) for that AnnotatedObject. */ private Map<TypeQualifierValue, Map<AnnotatedObject, TypeQualifierAnnotation>> effectiveObjectAnnotations = new HashMap<TypeQualifierValue, Map<AnnotatedObject,TypeQualifierAnnotation>>(); /** * Map of TypeQualifierValues to maps containing, for each XMethod/parameter, * the effective TypeQualifierAnnotation (if any) for that XMethod/parameter. */ private Map<TypeQualifierValue, DualKeyHashMap<XMethod, Integer, TypeQualifierAnnotation>> effectiveParameterAnnotations = new HashMap<TypeQualifierValue, DualKeyHashMap<XMethod,Integer,TypeQualifierAnnotation>>(); } private static ThreadLocal<Data> instance = new ThreadLocal<Data>() { @Override protected Data initialValue() { return new Data(); } }; public static void clearInstance() { if (DEBUG) { System.out.println("Clearing TypeQualifier application cache"); } instance.remove(); } private static Map<TypeQualifierValue, DualKeyHashMap<XMethod, Integer, TypeQualifierAnnotation>> getEffectiveParameterAnnotations() { return instance.get().effectiveParameterAnnotations; } private static Map<TypeQualifierValue, Map<AnnotatedObject, TypeQualifierAnnotation>> getEffectiveObjectAnnotations() { return instance.get().effectiveObjectAnnotations; } private static DualKeyHashMap<XMethod, Integer, Collection<AnnotationValue>> getDirectParameterAnnotations() { return instance.get().directParameterAnnotations; } private static Map<AnnotatedObject, Collection<AnnotationValue>> getDirectObjectAnnotations() { return instance.get().directObjectAnnotations; } /** * Callback interface to compute effective TypeQualifierAnnotation on an * AnnotatedObject or method parameter. */ private interface ComputeEffectiveTypeQualifierAnnotation { public TypeQualifierAnnotation compute(TypeQualifierValue tqv); } /** * Get the direct annotations (if any) on given AnnotatedObject. * * @param m an AnnotatedObject * @return Collection of AnnotationValues representing annotations directly * applied to this AnnotatedObject */ private static Collection<AnnotationValue> getDirectAnnotation(AnnotatedObject m) { Collection<AnnotationValue> result = getDirectObjectAnnotations().get(m); if (result != null) return result; if (m.getAnnotationDescriptors().isEmpty()) return Collections.emptyList(); result = TypeQualifierResolver.resolveTypeQualifiers(m.getAnnotations()); if (result.size() == 0) result = Collections.emptyList(); getDirectObjectAnnotations().put(m, result); return result; } /** * Get the direct annotations (if any) on given method parameter. * * @param m a method * @param parameter a parameter (0 == first parameter) * @return Collection of AnnotationValues representing annotations directly * applied to this parameter */ private static Collection<AnnotationValue> getDirectAnnotation(XMethod m, int parameter) { Collection<AnnotationValue> result = getDirectParameterAnnotations().get(m, parameter); if (result != null) return result; if (m.getParameterAnnotationDescriptors(parameter).isEmpty()) return Collections.emptyList(); result = TypeQualifierResolver.resolveTypeQualifiers(m.getParameterAnnotations(parameter)); if (result.size() == 0) result = Collections.emptyList(); getDirectParameterAnnotations().put(m, parameter, result); return result; } /** * Populate a Set of TypeQualifierAnnotations representing * directly-applied type qualifier annotations on given * method parameter. * * @param result Set of TypeQualifierAnnotations * @param o a method * @param parameter a parameter (0 == first parameter) */ public static void getDirectApplications(Set<TypeQualifierAnnotation> result, XMethod o, int parameter) { Collection<AnnotationValue> values = getDirectAnnotation(o, parameter); for(AnnotationValue v : values) constructTypeQualifierAnnotation(result, v); } /** * Populate a Set of TypeQualifierAnnotations representing * directly-applied type qualifier annotations on given * AnnotatedObject. * * @param result Set of TypeQualifierAnnotations * @param o an AnnotatedObject * @param e ElementType representing kind of annotated object */ public static void getDirectApplications(Set<TypeQualifierAnnotation> result, AnnotatedObject o, ElementType e) { if (!o.getElementType().equals(e)) return; Collection<AnnotationValue> values = getDirectAnnotation(o); for(AnnotationValue v : values) constructTypeQualifierAnnotation(result, v); } /** * Resolve a raw AnnotationValue into a TypeQualifierAnnotation. * * @param v a raw AnnotationValue * @return a constructed TypeQualifierAnnotation */ public static TypeQualifierAnnotation constructTypeQualifierAnnotation(AnnotationValue v) { assert v != null; EnumValue whenValue = (EnumValue) v.getValue("when"); When when = whenValue == null ? When.ALWAYS : When.valueOf(whenValue.value); ClassDescriptor annotationClass = v.getAnnotationClass(); TypeQualifierValue tqv = TypeQualifierValue.getValue(annotationClass, v.getValue("value")); TypeQualifierAnnotation tqa = TypeQualifierAnnotation.getValue(tqv, when); return tqa; } /** * Resolve a raw AnnotationValue into a TypeQualifierAnnotation, * storing result in given Set. * * @param set Set of resolved TypeQualifierAnnotations * @param v a raw AnnotationValue */ public static void constructTypeQualifierAnnotation(Set<TypeQualifierAnnotation> set, AnnotationValue v) { assert set != null; TypeQualifierAnnotation tqa = constructTypeQualifierAnnotation(v); set.add(tqa); } /** * Populate Set of TypeQualifierAnnotations * for given AnnotatedObject, * taking into account annotations * applied to outer scopes (e.g., enclosing classes and packages.) * * @param result Set of TypeQualifierAnnotations * @param o an AnnotatedObject * @param e ElementType representing kind of AnnotatedObject */ private static void getApplicableScopedApplications(Set<TypeQualifierAnnotation> result, AnnotatedObject o, ElementType e) { AnnotatedObject outer = o.getContainingScope(); if (outer != null) getApplicableScopedApplications(result, outer, e); getDirectApplications(result, o, e); } /** * Get the collection of resolved TypeQualifierAnnotations for * a given AnnotatedObject, * taking into account annotations * applied to outer scopes (e.g., enclosing classes and packages.) * * @param o an AnnotatedObject * @param e ElementType representing kind of AnnotatedObject * @return Collection of resolved TypeQualifierAnnotations */ private static Collection<TypeQualifierAnnotation> getApplicableScopedApplications(AnnotatedObject o, ElementType e) { Set<TypeQualifierAnnotation> result = new HashSet<TypeQualifierAnnotation>(); getApplicableScopedApplications(result, o, e); return result; } /** * Get the collection of resolved TypeQualifierAnnotations for * a given parameter, * taking into account annotations * applied to outer scopes (e.g., enclosing classes and packages.) * * @param o a method * @param parameter a parameter (0 == first parameter) * @return Collection of resolved TypeQualifierAnnotations */ private static Collection<TypeQualifierAnnotation> getApplicableScopedApplications(XMethod o, int parameter) { Set<TypeQualifierAnnotation> result = new HashSet<TypeQualifierAnnotation>(); ElementType e = ElementType.PARAMETER; getApplicableScopedApplications(result, o, e); getDirectApplications(result, o, parameter); return result; } /** * Get the Collection of resolved TypeQualifierAnnotations representing * directly applied and default (outer scope) type qualifier annotations * for given AnnotatedObject. * * <p>NOTE: does not properly account for inherited annotations * on instance methods. * It is ok to call this method to find out generally-relevant TypeQualifierAnnotations, * but not to find the effective TypeQualifierAnnotation.</p> * * @param o an AnnotatedObject * @return Collection of TypeQualifierAnnotations applicable to the AnnotatedObject */ public static Collection<TypeQualifierAnnotation> getApplicableApplications(AnnotatedObject o) { return getApplicableScopedApplications(o, o.getElementType()); } /** * Get the Collection of resolved TypeQualifierAnnotations representing * directly applied and default (outer scope) type qualifier annotations * for given method parameter. * * <p>NOTE: does not properly account for inherited annotations * on instance method parameters. * It is ok to call this method to find out generally-relevant TypeQualifierAnnotations, * but not to find the effective TypeQualifierAnnotation.</p> * * @param o a method * @param parameter a parameter (0 == first parameter) * @return Collection of TypeQualifierAnnotations applicable to the method parameter */ public static Collection<TypeQualifierAnnotation> getApplicableApplications(XMethod o, int parameter) { return getApplicableScopedApplications(o, parameter); } /** * Look up a TypeQualifierAnnotation matching given TypeQualifierValue. * * @param typeQualifierAnnotations a Collection of TypeQualifierAnnotations * @param typeQualifierValue a TypeQualifierValue * @return matching TypeQualifierAnnotation, or null if none */ private static @CheckForNull TypeQualifierAnnotation findMatchingTypeQualifierAnnotation( Collection<TypeQualifierAnnotation> typeQualifierAnnotations, TypeQualifierValue typeQualifierValue) { for (TypeQualifierAnnotation typeQualifierAnnotation : typeQualifierAnnotations) { if (typeQualifierAnnotation.typeQualifier.equals(typeQualifierValue)) { return typeQualifierAnnotation; } } return null; } /** * Look for a default type qualifier annotation. * * @param o an AnnotatedObject * @param typeQualifierValue a TypeQualifierValue * @param elementType type of element for which we're looking for a default annotation * @return default TypeQualifierAnnotation, or null if none */ private static @CheckForNull TypeQualifierAnnotation getDefaultAnnotation(AnnotatedObject o, TypeQualifierValue typeQualifierValue, ElementType elementType) { // // Try to find a default annotation using the standard JSR-305 // default annotation mechanism. // TypeQualifierAnnotation result; Collection<AnnotationValue> values = TypeQualifierResolver.resolveTypeQualifierDefaults(o.getAnnotations(), elementType); TypeQualifierAnnotation tqa = extractAnnotation(values, typeQualifierValue); if (tqa != null) return tqa; // // Try one of the FindBugs-specific default annotation mechanisms. // if ((result = checkFindBugsDefaultAnnotation(FindBugsDefaultAnnotations.DEFAULT_ANNOTATION, o, typeQualifierValue)) != null) { return result; } switch (elementType) { case FIELD: result = checkFindBugsDefaultAnnotation(FindBugsDefaultAnnotations.DEFAULT_ANNOTATION_FOR_FIELDS, o, typeQualifierValue); break; case METHOD: result = checkFindBugsDefaultAnnotation(FindBugsDefaultAnnotations.DEFAULT_ANNOTATION_FOR_METHODS, o, typeQualifierValue); break; case PARAMETER: result = checkFindBugsDefaultAnnotation(FindBugsDefaultAnnotations.DEFAULT_ANNOTATION_FOR_PARAMETERS, o, typeQualifierValue); break; default: // ignore } return result; } private static @CheckForNull TypeQualifierAnnotation checkFindBugsDefaultAnnotation(ClassDescriptor defaultAnnotation, AnnotatedObject o, TypeQualifierValue typeQualifierValue) { if (DEBUG_DEFAULT_ANNOTATION) { System.out.println("Checking for " + defaultAnnotation + " containing " + typeQualifierValue + " on " + o); } // - check to see if default annotation is present; if not, return null AnnotationValue annotationValue = o.getAnnotation(defaultAnnotation); if (annotationValue == null) { if (DEBUG_DEFAULT_ANNOTATION) { System.out.println(" ===> no " + defaultAnnotation); } return null; } // - get value - should be Type or array of Type Object value = annotationValue.getValue("value"); if (value == null) { if (DEBUG_DEFAULT_ANNOTATION) { System.out.println(" ===> value is null"); } return null; } Object[] types; if (value instanceof Object[]) { types = (Object[]) value; } else { types = new Object[]{ value }; } // - scan through array elements; see if any match the TypeQualifierValue (including type qualifier nicknames) for (Object obj : types) { if (!(obj instanceof Type)) { if (DEBUG_DEFAULT_ANNOTATION) { System.out.println("Found a non-Type value in value array of " + defaultAnnotation.toString() + " annotation"); } continue; } Type type = (Type) obj; if (DEBUG_DEFAULT_ANNOTATION) { System.out.println(" ===> checking " + type.getDescriptor()); } if (type.getDescriptor().startsWith("[")) { continue; } ClassDescriptor typeDesc = DescriptorFactory.instance().getClassDescriptor(type.getInternalName()); // There is no general way to figure out whether a particular // type is a type qualifier we're interested in without // resolving it. AnnotationValue annotation = new AnnotationValue(typeDesc); Collection<AnnotationValue> resolvedTypeQualifiers = TypeQualifierResolver.resolveTypeQualifiers(annotation); TypeQualifierAnnotation tqa = extractAnnotation(resolvedTypeQualifiers, typeQualifierValue); if (tqa != null) return tqa; } return null; } private static TypeQualifierAnnotation extractAnnotation(Collection<AnnotationValue> resolvedTypeQualifiers, TypeQualifierValue typeQualifierValue) { for (AnnotationValue typeQualifier : resolvedTypeQualifiers) { TypeQualifierAnnotation tqa = constructTypeQualifierAnnotation(typeQualifier); if (tqa.typeQualifier.equals(typeQualifierValue)) { if (DEBUG) { System.out.println(" ===> Found match " + tqa); } return tqa; } } return null; } /** * Get the effective TypeQualifierAnnotation on given * AnnotatedObject. Takes into account inherited and * default (outer scope) annotations. * Also takes exclusive qualifiers into account. * * @param o an AnnotatedObject * @param typeQualifierValue a TypeQualifierValue specifying kind of annotation * we want to look up * @return the effective TypeQualifierAnnotation, or null if * there is no effective TypeQualifierAnnotation on this * AnnotatedObject */ public static TypeQualifierAnnotation getEffectiveTypeQualifierAnnotation( final AnnotatedObject o, TypeQualifierValue typeQualifierValue) { TypeQualifierAnnotation tqa = computeEffectiveTypeQualifierAnnotation(typeQualifierValue, o); if (CHECK_EXCLUSIVE && tqa == null && typeQualifierValue.isExclusiveQualifier()) { tqa = computeExclusiveQualifier(typeQualifierValue, new ComputeEffectiveTypeQualifierAnnotation() { public TypeQualifierAnnotation compute(TypeQualifierValue tqv) { return computeEffectiveTypeQualifierAnnotation(tqv, o); } @Override public String toString() { return o.toString(); } }); } return tqa; } private static TypeQualifierAnnotation computeEffectiveTypeQualifierAnnotation(TypeQualifierValue typeQualifierValue, AnnotatedObject o) { if (DEBUG) { System.out.println("Looking up application of " + typeQualifierValue + " on " + o); } Map<AnnotatedObject, TypeQualifierAnnotation> map = getEffectiveObjectAnnotations().get(typeQualifierValue); if (map == null) { map = new HashMap<AnnotatedObject, TypeQualifierAnnotation>(); getEffectiveObjectAnnotations().put(typeQualifierValue, map); } // Check cached answer TypeQualifierAnnotation result; if (map.containsKey(o)) { result = map.get(o); } else { // Compute answer TypeQualifierAnnotation tqa; // See if there is a direct application tqa = getDirectTypeQualifierAnnotation(o, typeQualifierValue); // If it's an instance method, check for an inherited annotation if (tqa == null && (o instanceof XMethod) && !((XMethod) o).isStatic()) { tqa = getInheritedTypeQualifierAnnotation((XMethod) o, typeQualifierValue); } // Check for a default (outer scope) annotation if (tqa == null) { tqa = getDefaultTypeQualifierAnnotation(o, typeQualifierValue); } // Cache computed answer result = tqa; map.put(o, result); } if (DEBUG) { System.out.println(" => Answer: " + result); } // Return cached answer return result; } /** * Get a directly-applied TypeQualifierAnnotation on given AnnotatedObject. * * @param o an AnnotatedObject * @param typeQualifierValue the kind of TypeQualifierValue we are looking for * @return directly-applied TypeQualifierAnnotation, or null if there is no * such annotation on the AnnotatedObject */ private static TypeQualifierAnnotation getDirectTypeQualifierAnnotation(AnnotatedObject o, TypeQualifierValue typeQualifierValue) { TypeQualifierAnnotation result; Set<TypeQualifierAnnotation> applications = new HashSet<TypeQualifierAnnotation>(); getDirectApplications(applications, o, o.getElementType()); result = findMatchingTypeQualifierAnnotation(applications, typeQualifierValue); return result; } /** * Get the effective inherited TypeQualifierAnnotation on given * instance method. * * @param o an XMethod * @param typeQualifierValue the kind of TypeQualifierValue we are looking for * @return effective TypeQualifierAnnotation inherited from overridden supertype methods, * or null if there is no inherited TypeQualifierAnnotation */ private static TypeQualifierAnnotation getInheritedTypeQualifierAnnotation(XMethod o, TypeQualifierValue typeQualifierValue) { assert !o.isStatic(); ReturnTypeAnnotationAccumulator accumulator = new ReturnTypeAnnotationAccumulator(typeQualifierValue, o); try { AnalysisContext.currentAnalysisContext().getSubtypes2().traverseSupertypes(o.getClassDescriptor(), accumulator); return accumulator.getResult().getEffectiveTypeQualifierAnnotation(); } catch (ClassNotFoundException e) { AnalysisContext.currentAnalysisContext().getLookupFailureCallback().reportMissingClass(e); return null; } } /** * Get the default (outer scope) annotation applicable to given * AnnotatedObject. * * @param o an AnnotatedObject * @param typeQualifierValue the kind of TypeQualifierValue we are looking for * @return the applicable default TypeQualifierAnnotation, or null * if there is no default TypeQualifierAnnotation */ private static TypeQualifierAnnotation getDefaultTypeQualifierAnnotation(AnnotatedObject o, TypeQualifierValue typeQualifierValue) { if (o instanceof AbstractClassMember && (((AbstractClassMember)o).getAccessFlags() & Opcodes.ACC_SYNTHETIC) != 0) return null; // synthetic methods don't get default annotations ElementType elementType = o.getElementType(); while (true) { o = o.getContainingScope(); if (o == null) return null; TypeQualifierAnnotation result; // Check direct applications of the type qualifier Set<TypeQualifierAnnotation> applications = new HashSet<TypeQualifierAnnotation>(); getDirectApplications(applications, o, elementType); result = findMatchingTypeQualifierAnnotation(applications, typeQualifierValue); if (result != null) { // Great - found an outer scope with a relevant annotation return result; } // Check default annotations result = getDefaultAnnotation(o, typeQualifierValue, elementType); if (result != null) { return result; } } } /** * Get the effective TypeQualifierAnnotation on given method parameter. * Takes into account inherited and default (outer scope) annotations. * Also takes exclusive qualifiers into account. * * @param xmethod a method * @param parameter a parameter (0 == first parameter) * @param typeQualifierValue the kind of TypeQualifierValue we are looking for * @return effective TypeQualifierAnnotation on the parameter, * or null if there is no effective TypeQualifierAnnotation */ public static @CheckForNull TypeQualifierAnnotation getEffectiveTypeQualifierAnnotation( final XMethod xmethod, final int parameter, TypeQualifierValue typeQualifierValue) { TypeQualifierAnnotation tqa = computeEffectiveTypeQualifierAnnotation(typeQualifierValue, xmethod, parameter); if (CHECK_EXCLUSIVE && tqa == null && typeQualifierValue.isExclusiveQualifier()) { tqa = computeExclusiveQualifier(typeQualifierValue, new ComputeEffectiveTypeQualifierAnnotation() { public TypeQualifierAnnotation compute(TypeQualifierValue tqv) { return computeEffectiveTypeQualifierAnnotation(tqv, xmethod, parameter); } @Override public String toString() { return "parameter " + parameter + " of " + xmethod; } }); } return tqa; } // static Map<String, Throwable> checked = new HashMap<String, Throwable>(); private static TypeQualifierAnnotation computeEffectiveTypeQualifierAnnotation(TypeQualifierValue typeQualifierValue, XMethod xmethod, int parameter) { if (DEBUG) { // System.out.println("XX: " +System.identityHashCode(typeQualifierValue)); if (typeQualifierValue.value != null) { System.out.println(" Value is " + typeQualifierValue.value +"("+typeQualifierValue.value.getClass().toString()+")"); } } DualKeyHashMap<XMethod, Integer, TypeQualifierAnnotation> map = getEffectiveParameterAnnotations().get(typeQualifierValue); if (map == null) { if (DEBUG) { System.out.println("computeEffectiveTypeQualifierAnnotation: Creating map for " + typeQualifierValue); } map = new DualKeyHashMap<XMethod, Integer, TypeQualifierAnnotation>(); getEffectiveParameterAnnotations().put(typeQualifierValue, map); } // Check cached answer TypeQualifierAnnotation result; if (map.containsKey(xmethod, parameter)) { result = map.get(xmethod, parameter); } else { if (DEBUG) { System.out.println("Looking up application of " + typeQualifierValue + " on " + xmethod + " parameter " + parameter); } // String desc = xmethod.toString()+":"+parameter+":"+typeQualifierValue; // if (checked.containsKey(desc)) { // //throw new IllegalStateException("Repeating computation of " + desc, checked.get(desc)); // System.out.println("Repeating computation of " + desc); // System.out.println("Previously computed:"); // checked.get(desc).printStackTrace(System.out); // throw new IllegalStateException(); // } // checked.put(desc, new Throwable().fillInStackTrace()); // Compute answer TypeQualifierAnnotation tqa; // Check direct application if (DEBUG) { System.out.print(" (1) Checking direct application..."); } tqa = getDirectTypeQualifierAnnotation(xmethod, parameter, typeQualifierValue); if (DEBUG) { System.out.println(tqa != null ? "FOUND" : "none"); } // If it's an instance method, check for inherited annotation if (tqa == null && !xmethod.isStatic()) { if (DEBUG) { System.out.print(" (2) Checking inherited..."); } tqa = getInheritedTypeQualifierAnnotation(xmethod, parameter, typeQualifierValue); if (DEBUG) { System.out.println(tqa != null ? "FOUND" : "none"); } } // Check for default (outer scope) annotation if (tqa == null) { if (DEBUG) { System.out.print(" (3) Checking default..."); } tqa = getDefaultTypeQualifierAnnotation(xmethod, parameter, typeQualifierValue); if (DEBUG) { System.out.println(tqa != null ? "FOUND" : "none"); } } // Cache answer result = tqa; map.put(xmethod, parameter, result); if (DEBUG) { System.out.println(" => Answer: " + result); } } if (!map.containsKey(xmethod, parameter)) { throw new IllegalStateException("Did not populate cache?"); } // Return cached answer return result; } /** * Get the TypeQualifierAnnotation directly applied to given * method parameter. * * @param xmethod a method * @param parameter a parameter (0 == first parameter) * @param typeQualifierValue the kind of TypeQualifierValue we are looking for * @return TypeQualifierAnnotation directly applied to the parameter, * or null if there is no directly applied TypeQualifierAnnotation */ public static @CheckForNull TypeQualifierAnnotation getDirectTypeQualifierAnnotation(XMethod xmethod, int parameter, TypeQualifierValue typeQualifierValue) { Set<TypeQualifierAnnotation> applications = new HashSet<TypeQualifierAnnotation>(); getDirectApplications(applications, xmethod, parameter); if (DEBUG_METHOD != null && DEBUG_METHOD.equals(xmethod.getName())) { System.out.println(" Direct applications are: " + applications); } return findMatchingTypeQualifierAnnotation(applications, typeQualifierValue); } /** * Get the effective inherited TypeQualifierAnnotation on the given * instance method parameter. * * @param xmethod an instance method * @param parameter a parameter (0 == first parameter) * @param typeQualifierValue the kind of TypeQualifierValue we are looking for * @return effective inherited TypeQualifierAnnotation on the parameter, * or null if there is not effective TypeQualifierAnnotation */ private static @CheckForNull TypeQualifierAnnotation getInheritedTypeQualifierAnnotation(XMethod xmethod, int parameter, TypeQualifierValue typeQualifierValue) { assert !xmethod.isStatic(); ParameterAnnotationAccumulator accumulator = new ParameterAnnotationAccumulator(typeQualifierValue, xmethod, parameter); try { AnalysisContext.currentAnalysisContext().getSubtypes2().traverseSupertypes(xmethod.getClassDescriptor(), accumulator); return accumulator.getResult().getEffectiveTypeQualifierAnnotation(); } catch (ClassNotFoundException e) { AnalysisContext.currentAnalysisContext().getLookupFailureCallback().reportMissingClass(e); return null; } } /** * Get the default (outer-scope) TypeQualifierAnnotation on given method parameter. * * @param xmethod a method * @param parameter a parameter (0 == first parameter) * @param typeQualifierValue the kind of TypeQualifierValue we are looking for * @return the default (outer scope) TypeQualifierAnnotation on the parameter, * or null if there is no default TypeQualifierAnnotation */ private static @CheckForNull TypeQualifierAnnotation getDefaultTypeQualifierAnnotation( XMethod xmethod, int parameter, TypeQualifierValue typeQualifierValue) { if ((xmethod.getAccessFlags() & Opcodes.ACC_SYNTHETIC) != 0) return null; // synthetic methods don't get default annotations AnnotatedObject o = xmethod; while (true) { o = o.getContainingScope(); if (o == null) return null; // Check for direct type qualifier annotation Set<TypeQualifierAnnotation> applications = new HashSet<TypeQualifierAnnotation>(); getDirectApplications(applications, o, ElementType.PARAMETER); TypeQualifierAnnotation tqa = findMatchingTypeQualifierAnnotation(applications, typeQualifierValue); if (tqa != null) { // Found matching annotation in outer scope return tqa; } // Check for default annotation tqa = getDefaultAnnotation(o, typeQualifierValue, ElementType.PARAMETER); if (tqa != null) { return tqa; } } } private static TypeQualifierAnnotation computeExclusiveQualifier(TypeQualifierValue typeQualifierValue, ComputeEffectiveTypeQualifierAnnotation c) { assert typeQualifierValue.isExclusiveQualifier(); boolean isExhaustive = CHECK_EXHAUSTIVE && typeQualifierValue.isExhaustiveQualifier(); // Exclusive qualifiers: // - if there is an effective application of // a "complementary" TypeQualifierValue in which // when=ALWAYS. If so, then it's effectively // the same as the asked-for TypeQualifierValue, // but with when=NEVER. // // Exhaustive qualifiers: // - if all effective applications of "complementary" TypeQualifierValues // are when=NEVER, then the asked-for TypeQualifierValue // is effectively when=ALWAYS. boolean allComplementaryValuesAreWhenEqualsNever = true; Collection<TypeQualifierValue> complementaryTypeQualifierValues = TypeQualifierValue.getComplementaryExclusiveTypeQualifierValue(typeQualifierValue); for (TypeQualifierValue complementaryTypeQualifierValue : complementaryTypeQualifierValues) { TypeQualifierAnnotation complementaryTqa = c.compute(complementaryTypeQualifierValue); if (complementaryTqa != null) { if (complementaryTqa.when == When.ALWAYS) { // Exclusive qualifier where a complementary qualifier // was observed effectively when=ALWAYS. return TypeQualifierAnnotation.getValue(typeQualifierValue, When.NEVER); } else if (complementaryTqa.when != When.NEVER) { allComplementaryValuesAreWhenEqualsNever = false; } } else { allComplementaryValuesAreWhenEqualsNever = false; } } if (isExhaustive && allComplementaryValuesAreWhenEqualsNever) { // It's an exhaustive qualifier, and all complementary // qualifiers were effectively when=NEVER. if (TypeQualifierValue.DEBUG) { System.out.println("*** application of " + typeQualifierValue + " on " + c + " is when=ALWAYS due to exhaustion"); } return TypeQualifierAnnotation.getValue(typeQualifierValue, When.ALWAYS); } return null; } }
findbugs/src/java/edu/umd/cs/findbugs/ba/jsr305/TypeQualifierApplications.java
/* * FindBugs - Find Bugs in Java programs * Copyright (C) 2003-2008, University of Maryland * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.umd.cs.findbugs.ba.jsr305; import java.lang.annotation.ElementType; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.annotation.meta.When; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.annotations.CheckForNull; import edu.umd.cs.findbugs.ba.AbstractClassMember; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.XMethod; import edu.umd.cs.findbugs.classfile.ClassDescriptor; import edu.umd.cs.findbugs.classfile.DescriptorFactory; import edu.umd.cs.findbugs.classfile.analysis.AnnotatedObject; import edu.umd.cs.findbugs.classfile.analysis.AnnotationValue; import edu.umd.cs.findbugs.classfile.analysis.EnumValue; import edu.umd.cs.findbugs.util.DualKeyHashMap; /** * Figure out where and how type qualifier annotations are applied. * * @author William Pugh * @author David Hovemeyer */ public class TypeQualifierApplications { static final boolean DEBUG = SystemProperties.getBoolean("ctq.applications.debug"); static final String DEBUG_METHOD = SystemProperties.getProperty("ctq.applications.method"); static final boolean DEBUG_DEFAULT_ANNOTATION = SystemProperties.getBoolean("ctq.applications.default.debug"); /** * Should exclusive type qualifiers be handled? */ static final boolean CHECK_EXCLUSIVE = true;//SystemProperties.getBoolean("ctq.applications.checkexclusive"); static final boolean CHECK_EXHAUSTIVE = SystemProperties.getBoolean("ctq.applications.checkexhaustive"); static class Data { /** Type qualifier annotations applied directly to methods/fields/classes/etc. */ private Map<AnnotatedObject, Collection<AnnotationValue>> directObjectAnnotations = new HashMap<AnnotatedObject, Collection<AnnotationValue>>(); /** Type qualifier annotations applied directly to method parameters. */ private DualKeyHashMap<XMethod, Integer, Collection<AnnotationValue>> directParameterAnnotations = new DualKeyHashMap<XMethod, Integer, Collection<AnnotationValue>>(); /** * Map of TypeQualifierValues to maps containing, for each AnnotatedObject, * the effective TypeQualifierAnnotation (if any) for that AnnotatedObject. */ private Map<TypeQualifierValue, Map<AnnotatedObject, TypeQualifierAnnotation>> effectiveObjectAnnotations = new HashMap<TypeQualifierValue, Map<AnnotatedObject,TypeQualifierAnnotation>>(); /** * Map of TypeQualifierValues to maps containing, for each XMethod/parameter, * the effective TypeQualifierAnnotation (if any) for that XMethod/parameter. */ private Map<TypeQualifierValue, DualKeyHashMap<XMethod, Integer, TypeQualifierAnnotation>> effectiveParameterAnnotations = new HashMap<TypeQualifierValue, DualKeyHashMap<XMethod,Integer,TypeQualifierAnnotation>>(); } private static ThreadLocal<Data> instance = new ThreadLocal<Data>() { @Override protected Data initialValue() { return new Data(); } }; public static void clearInstance() { if (DEBUG) { System.out.println("Clearing TypeQualifier application cache"); } instance.remove(); } private static Map<TypeQualifierValue, DualKeyHashMap<XMethod, Integer, TypeQualifierAnnotation>> getEffectiveParameterAnnotations() { return instance.get().effectiveParameterAnnotations; } private static Map<TypeQualifierValue, Map<AnnotatedObject, TypeQualifierAnnotation>> getEffectiveObjectAnnotations() { return instance.get().effectiveObjectAnnotations; } private static DualKeyHashMap<XMethod, Integer, Collection<AnnotationValue>> getDirectParameterAnnotations() { return instance.get().directParameterAnnotations; } private static Map<AnnotatedObject, Collection<AnnotationValue>> getDirectObjectAnnotations() { return instance.get().directObjectAnnotations; } /** * Callback interface to compute effective TypeQualifierAnnotation on an * AnnotatedObject or method parameter. */ private interface ComputeEffectiveTypeQualifierAnnotation { public TypeQualifierAnnotation compute(TypeQualifierValue tqv); } /** * Get the direct annotations (if any) on given AnnotatedObject. * * @param m an AnnotatedObject * @return Collection of AnnotationValues representing annotations directly * applied to this AnnotatedObject */ private static Collection<AnnotationValue> getDirectAnnotation(AnnotatedObject m) { Collection<AnnotationValue> result = getDirectObjectAnnotations().get(m); if (result != null) return result; if (m.getAnnotationDescriptors().isEmpty()) return Collections.emptyList(); result = TypeQualifierResolver.resolveTypeQualifiers(m.getAnnotations()); if (result.size() == 0) result = Collections.emptyList(); getDirectObjectAnnotations().put(m, result); return result; } /** * Get the direct annotations (if any) on given method parameter. * * @param m a method * @param parameter a parameter (0 == first parameter) * @return Collection of AnnotationValues representing annotations directly * applied to this parameter */ private static Collection<AnnotationValue> getDirectAnnotation(XMethod m, int parameter) { Collection<AnnotationValue> result = getDirectParameterAnnotations().get(m, parameter); if (result != null) return result; if (m.getParameterAnnotationDescriptors(parameter).isEmpty()) return Collections.emptyList(); result = TypeQualifierResolver.resolveTypeQualifiers(m.getParameterAnnotations(parameter)); if (result.size() == 0) result = Collections.emptyList(); getDirectParameterAnnotations().put(m, parameter, result); return result; } /** * Populate a Set of TypeQualifierAnnotations representing * directly-applied type qualifier annotations on given * method parameter. * * @param result Set of TypeQualifierAnnotations * @param o a method * @param parameter a parameter (0 == first parameter) */ public static void getDirectApplications(Set<TypeQualifierAnnotation> result, XMethod o, int parameter) { Collection<AnnotationValue> values = getDirectAnnotation(o, parameter); for(AnnotationValue v : values) constructTypeQualifierAnnotation(result, v); } /** * Populate a Set of TypeQualifierAnnotations representing * directly-applied type qualifier annotations on given * AnnotatedObject. * * @param result Set of TypeQualifierAnnotations * @param o an AnnotatedObject * @param e ElementType representing kind of annotated object */ public static void getDirectApplications(Set<TypeQualifierAnnotation> result, AnnotatedObject o, ElementType e) { if (!o.getElementType().equals(e)) return; Collection<AnnotationValue> values = getDirectAnnotation(o); for(AnnotationValue v : values) constructTypeQualifierAnnotation(result, v); } /** * Resolve a raw AnnotationValue into a TypeQualifierAnnotation. * * @param v a raw AnnotationValue * @return a constructed TypeQualifierAnnotation */ public static TypeQualifierAnnotation constructTypeQualifierAnnotation(AnnotationValue v) { assert v != null; EnumValue whenValue = (EnumValue) v.getValue("when"); When when = whenValue == null ? When.ALWAYS : When.valueOf(whenValue.value); ClassDescriptor annotationClass = v.getAnnotationClass(); TypeQualifierValue tqv = TypeQualifierValue.getValue(annotationClass, v.getValue("value")); TypeQualifierAnnotation tqa = TypeQualifierAnnotation.getValue(tqv, when); return tqa; } /** * Resolve a raw AnnotationValue into a TypeQualifierAnnotation, * storing result in given Set. * * @param set Set of resolved TypeQualifierAnnotations * @param v a raw AnnotationValue */ public static void constructTypeQualifierAnnotation(Set<TypeQualifierAnnotation> set, AnnotationValue v) { assert set != null; TypeQualifierAnnotation tqa = constructTypeQualifierAnnotation(v); set.add(tqa); } /** * Populate Set of TypeQualifierAnnotations * for given AnnotatedObject, * taking into account annotations * applied to outer scopes (e.g., enclosing classes and packages.) * * @param result Set of TypeQualifierAnnotations * @param o an AnnotatedObject * @param e ElementType representing kind of AnnotatedObject */ private static void getApplicableScopedApplications(Set<TypeQualifierAnnotation> result, AnnotatedObject o, ElementType e) { AnnotatedObject outer = o.getContainingScope(); if (outer != null) getApplicableScopedApplications(result, outer, e); getDirectApplications(result, o, e); } /** * Get the collection of resolved TypeQualifierAnnotations for * a given AnnotatedObject, * taking into account annotations * applied to outer scopes (e.g., enclosing classes and packages.) * * @param o an AnnotatedObject * @param e ElementType representing kind of AnnotatedObject * @return Collection of resolved TypeQualifierAnnotations */ private static Collection<TypeQualifierAnnotation> getApplicableScopedApplications(AnnotatedObject o, ElementType e) { Set<TypeQualifierAnnotation> result = new HashSet<TypeQualifierAnnotation>(); getApplicableScopedApplications(result, o, e); return result; } /** * Get the collection of resolved TypeQualifierAnnotations for * a given parameter, * taking into account annotations * applied to outer scopes (e.g., enclosing classes and packages.) * * @param o a method * @param parameter a parameter (0 == first parameter) * @return Collection of resolved TypeQualifierAnnotations */ private static Collection<TypeQualifierAnnotation> getApplicableScopedApplications(XMethod o, int parameter) { Set<TypeQualifierAnnotation> result = new HashSet<TypeQualifierAnnotation>(); ElementType e = ElementType.PARAMETER; getApplicableScopedApplications(result, o, e); getDirectApplications(result, o, parameter); return result; } /** * Get the Collection of resolved TypeQualifierAnnotations representing * directly applied and default (outer scope) type qualifier annotations * for given AnnotatedObject. * * <p>NOTE: does not properly account for inherited annotations * on instance methods. * It is ok to call this method to find out generally-relevant TypeQualifierAnnotations, * but not to find the effective TypeQualifierAnnotation.</p> * * @param o an AnnotatedObject * @return Collection of TypeQualifierAnnotations applicable to the AnnotatedObject */ public static Collection<TypeQualifierAnnotation> getApplicableApplications(AnnotatedObject o) { return getApplicableScopedApplications(o, o.getElementType()); } /** * Get the Collection of resolved TypeQualifierAnnotations representing * directly applied and default (outer scope) type qualifier annotations * for given method parameter. * * <p>NOTE: does not properly account for inherited annotations * on instance method parameters. * It is ok to call this method to find out generally-relevant TypeQualifierAnnotations, * but not to find the effective TypeQualifierAnnotation.</p> * * @param o a method * @param parameter a parameter (0 == first parameter) * @return Collection of TypeQualifierAnnotations applicable to the method parameter */ public static Collection<TypeQualifierAnnotation> getApplicableApplications(XMethod o, int parameter) { return getApplicableScopedApplications(o, parameter); } /** * Look up a TypeQualifierAnnotation matching given TypeQualifierValue. * * @param typeQualifierAnnotations a Collection of TypeQualifierAnnotations * @param typeQualifierValue a TypeQualifierValue * @return matching TypeQualifierAnnotation, or null if none */ private static @CheckForNull TypeQualifierAnnotation findMatchingTypeQualifierAnnotation( Collection<TypeQualifierAnnotation> typeQualifierAnnotations, TypeQualifierValue typeQualifierValue) { for (TypeQualifierAnnotation typeQualifierAnnotation : typeQualifierAnnotations) { if (typeQualifierAnnotation.typeQualifier.equals(typeQualifierValue)) { return typeQualifierAnnotation; } } return null; } /** * Look for a default type qualifier annotation. * * @param o an AnnotatedObject * @param typeQualifierValue a TypeQualifierValue * @param elementType type of element for which we're looking for a default annotation * @return default TypeQualifierAnnotation, or null if none */ private static @CheckForNull TypeQualifierAnnotation getDefaultAnnotation(AnnotatedObject o, TypeQualifierValue typeQualifierValue, ElementType elementType) { // // Try to find a default annotation using the standard JSR-305 // default annotation mechanism. // TypeQualifierAnnotation result; Collection<AnnotationValue> values = TypeQualifierResolver.resolveTypeQualifierDefaults(o.getAnnotations(), elementType); TypeQualifierAnnotation tqa = extractAnnotation(values, typeQualifierValue); if (tqa != null) return tqa; // // Try one of the FindBugs-specific default annotation mechanisms. // if ((result = checkFindBugsDefaultAnnotation(FindBugsDefaultAnnotations.DEFAULT_ANNOTATION, o, typeQualifierValue)) != null) { return result; } switch (elementType) { case FIELD: result = checkFindBugsDefaultAnnotation(FindBugsDefaultAnnotations.DEFAULT_ANNOTATION_FOR_FIELDS, o, typeQualifierValue); break; case METHOD: result = checkFindBugsDefaultAnnotation(FindBugsDefaultAnnotations.DEFAULT_ANNOTATION_FOR_METHODS, o, typeQualifierValue); break; case PARAMETER: result = checkFindBugsDefaultAnnotation(FindBugsDefaultAnnotations.DEFAULT_ANNOTATION_FOR_PARAMETERS, o, typeQualifierValue); break; default: // ignore } return result; } private static @CheckForNull TypeQualifierAnnotation checkFindBugsDefaultAnnotation(ClassDescriptor defaultAnnotation, AnnotatedObject o, TypeQualifierValue typeQualifierValue) { if (DEBUG_DEFAULT_ANNOTATION) { System.out.println("Checking for " + defaultAnnotation + " containing " + typeQualifierValue + " on " + o); } // - check to see if default annotation is present; if not, return null AnnotationValue annotationValue = o.getAnnotation(defaultAnnotation); if (annotationValue == null) { if (DEBUG_DEFAULT_ANNOTATION) { System.out.println(" ===> no " + defaultAnnotation); } return null; } // - get value - should be Type or array of Type Object value = annotationValue.getValue("value"); if (value == null) { if (DEBUG_DEFAULT_ANNOTATION) { System.out.println(" ===> value is null"); } return null; } Object[] types; if (value instanceof Object[]) { types = (Object[]) value; } else { types = new Object[]{ value }; } // - scan through array elements; see if any match the TypeQualifierValue (including type qualifier nicknames) for (Object obj : types) { if (!(obj instanceof Type)) { if (DEBUG_DEFAULT_ANNOTATION) { System.out.println("Found a non-Type value in value array of " + defaultAnnotation.toString() + " annotation"); } continue; } Type type = (Type) obj; if (DEBUG_DEFAULT_ANNOTATION) { System.out.println(" ===> checking " + type.getDescriptor()); } if (type.getDescriptor().startsWith("[")) { continue; } ClassDescriptor typeDesc = DescriptorFactory.instance().getClassDescriptor(type.getInternalName()); // There is no general way to figure out whether a particular // type is a type qualifier we're interested in without // resolving it. AnnotationValue annotation = new AnnotationValue(typeDesc); Collection<AnnotationValue> resolvedTypeQualifiers = TypeQualifierResolver.resolveTypeQualifiers(annotation); TypeQualifierAnnotation tqa = extractAnnotation(resolvedTypeQualifiers, typeQualifierValue); if (tqa != null) return tqa; } return null; } private static TypeQualifierAnnotation extractAnnotation(Collection<AnnotationValue> resolvedTypeQualifiers, TypeQualifierValue typeQualifierValue) { for (AnnotationValue typeQualifier : resolvedTypeQualifiers) { TypeQualifierAnnotation tqa = constructTypeQualifierAnnotation(typeQualifier); if (tqa.typeQualifier.equals(typeQualifierValue)) { if (DEBUG) { System.out.println(" ===> Found match " + tqa); } return tqa; } } return null; } /** * Get the effective TypeQualifierAnnotation on given * AnnotatedObject. Takes into account inherited and * default (outer scope) annotations. * Also takes exclusive qualifiers into account. * * @param o an AnnotatedObject * @param typeQualifierValue a TypeQualifierValue specifying kind of annotation * we want to look up * @return the effective TypeQualifierAnnotation, or null if * there is no effective TypeQualifierAnnotation on this * AnnotatedObject */ public static TypeQualifierAnnotation getEffectiveTypeQualifierAnnotation( final AnnotatedObject o, TypeQualifierValue typeQualifierValue) { TypeQualifierAnnotation tqa = computeEffectiveTypeQualifierAnnotation(typeQualifierValue, o); if (CHECK_EXCLUSIVE && tqa == null && typeQualifierValue.isExclusiveQualifier()) { tqa = computeExclusiveQualifier(typeQualifierValue, new ComputeEffectiveTypeQualifierAnnotation() { public TypeQualifierAnnotation compute(TypeQualifierValue tqv) { return computeEffectiveTypeQualifierAnnotation(tqv, o); } @Override public String toString() { return o.toString(); } }); } return tqa; } private static TypeQualifierAnnotation computeEffectiveTypeQualifierAnnotation(TypeQualifierValue typeQualifierValue, AnnotatedObject o) { if (DEBUG) { System.out.println("Looking up application of " + typeQualifierValue + " on " + o); } Map<AnnotatedObject, TypeQualifierAnnotation> map = getEffectiveObjectAnnotations().get(typeQualifierValue); if (map == null) { map = new HashMap<AnnotatedObject, TypeQualifierAnnotation>(); getEffectiveObjectAnnotations().put(typeQualifierValue, map); } // Check cached answer TypeQualifierAnnotation result; if (map.containsKey(o)) { result = map.get(o); } else { // Compute answer TypeQualifierAnnotation tqa; // See if there is a direct application tqa = getDirectTypeQualifierAnnotation(o, typeQualifierValue); // If it's an instance method, check for an inherited annotation if (tqa == null && (o instanceof XMethod) && !((XMethod) o).isStatic()) { tqa = getInheritedTypeQualifierAnnotation((XMethod) o, typeQualifierValue); } // Check for a default (outer scope) annotation if (tqa == null) { tqa = getDefaultTypeQualifierAnnotation(o, typeQualifierValue); } // Cache computed answer result = tqa; map.put(o, result); } if (DEBUG) { System.out.println(" => Answer: " + result); } // Return cached answer return result; } /** * Get a directly-applied TypeQualifierAnnotation on given AnnotatedObject. * * @param o an AnnotatedObject * @param typeQualifierValue the kind of TypeQualifierValue we are looking for * @return directly-applied TypeQualifierAnnotation, or null if there is no * such annotation on the AnnotatedObject */ private static TypeQualifierAnnotation getDirectTypeQualifierAnnotation(AnnotatedObject o, TypeQualifierValue typeQualifierValue) { TypeQualifierAnnotation result; Set<TypeQualifierAnnotation> applications = new HashSet<TypeQualifierAnnotation>(); getDirectApplications(applications, o, o.getElementType()); result = findMatchingTypeQualifierAnnotation(applications, typeQualifierValue); return result; } /** * Get the effective inherited TypeQualifierAnnotation on given * instance method. * * @param o an XMethod * @param typeQualifierValue the kind of TypeQualifierValue we are looking for * @return effective TypeQualifierAnnotation inherited from overridden supertype methods, * or null if there is no inherited TypeQualifierAnnotation */ private static TypeQualifierAnnotation getInheritedTypeQualifierAnnotation(XMethod o, TypeQualifierValue typeQualifierValue) { assert !o.isStatic(); ReturnTypeAnnotationAccumulator accumulator = new ReturnTypeAnnotationAccumulator(typeQualifierValue, o); try { AnalysisContext.currentAnalysisContext().getSubtypes2().traverseSupertypes(o.getClassDescriptor(), accumulator); return accumulator.getResult().getEffectiveTypeQualifierAnnotation(); } catch (ClassNotFoundException e) { AnalysisContext.currentAnalysisContext().getLookupFailureCallback().reportMissingClass(e); return null; } } /** * Get the default (outer scope) annotation applicable to given * AnnotatedObject. * * @param o an AnnotatedObject * @param typeQualifierValue the kind of TypeQualifierValue we are looking for * @return the applicable default TypeQualifierAnnotation, or null * if there is no default TypeQualifierAnnotation */ private static TypeQualifierAnnotation getDefaultTypeQualifierAnnotation(AnnotatedObject o, TypeQualifierValue typeQualifierValue) { if (o instanceof AbstractClassMember && (((AbstractClassMember)o).getAccessFlags() & Opcodes.ACC_SYNTHETIC) != 0) return null; // synthetic methods don't get default annotations ElementType elementType = o.getElementType(); while (true) { o = o.getContainingScope(); if (o == null) return null; TypeQualifierAnnotation result; // Check direct applications of the type qualifier Set<TypeQualifierAnnotation> applications = new HashSet<TypeQualifierAnnotation>(); getDirectApplications(applications, o, elementType); result = findMatchingTypeQualifierAnnotation(applications, typeQualifierValue); if (result != null) { // Great - found an outer scope with a relevant annotation return result; } // Check default annotations result = getDefaultAnnotation(o, typeQualifierValue, elementType); if (result != null) { return result; } } } /** * Get the effective TypeQualifierAnnotation on given method parameter. * Takes into account inherited and default (outer scope) annotations. * Also takes exclusive qualifiers into account. * * @param xmethod a method * @param parameter a parameter (0 == first parameter) * @param typeQualifierValue the kind of TypeQualifierValue we are looking for * @return effective TypeQualifierAnnotation on the parameter, * or null if there is no effective TypeQualifierAnnotation */ public static @CheckForNull TypeQualifierAnnotation getEffectiveTypeQualifierAnnotation( final XMethod xmethod, final int parameter, TypeQualifierValue typeQualifierValue) { TypeQualifierAnnotation tqa = computeEffectiveTypeQualifierAnnotation(typeQualifierValue, xmethod, parameter); if (CHECK_EXCLUSIVE && tqa == null && typeQualifierValue.isExclusiveQualifier()) { tqa = computeExclusiveQualifier(typeQualifierValue, new ComputeEffectiveTypeQualifierAnnotation() { public TypeQualifierAnnotation compute(TypeQualifierValue tqv) { return computeEffectiveTypeQualifierAnnotation(tqv, xmethod, parameter); } @Override public String toString() { return "parameter " + parameter + " of " + xmethod; } }); } return tqa; } // static Map<String, Throwable> checked = new HashMap<String, Throwable>(); private static TypeQualifierAnnotation computeEffectiveTypeQualifierAnnotation(TypeQualifierValue typeQualifierValue, XMethod xmethod, int parameter) { if (DEBUG) { // System.out.println("XX: " +System.identityHashCode(typeQualifierValue)); if (typeQualifierValue.value != null) { System.out.println(" Value is " + typeQualifierValue.value +"("+typeQualifierValue.value.getClass().toString()+")"); } } DualKeyHashMap<XMethod, Integer, TypeQualifierAnnotation> map = getEffectiveParameterAnnotations().get(typeQualifierValue); if (map == null) { if (DEBUG) { System.out.println("computeEffectiveTypeQualifierAnnotation: Creating map for " + typeQualifierValue); } map = new DualKeyHashMap<XMethod, Integer, TypeQualifierAnnotation>(); getEffectiveParameterAnnotations().put(typeQualifierValue, map); } // Check cached answer TypeQualifierAnnotation result; if (map.containsKey(xmethod, parameter)) { result = map.get(xmethod, parameter); } else { if (DEBUG) { System.out.println("Looking up application of " + typeQualifierValue + " on " + xmethod + " parameter " + parameter); } // String desc = xmethod.toString()+":"+parameter+":"+typeQualifierValue; // if (checked.containsKey(desc)) { // //throw new IllegalStateException("Repeating computation of " + desc, checked.get(desc)); // System.out.println("Repeating computation of " + desc); // System.out.println("Previously computed:"); // checked.get(desc).printStackTrace(System.out); // throw new IllegalStateException(); // } // checked.put(desc, new Throwable().fillInStackTrace()); // Compute answer TypeQualifierAnnotation tqa; // Check direct application if (DEBUG) { System.out.print(" (1) Checking direct application..."); } tqa = getDirectTypeQualifierAnnotation(xmethod, parameter, typeQualifierValue); if (DEBUG) { System.out.println(tqa != null ? "FOUND" : "none"); } // If it's an instance method, check for inherited annotation if (tqa == null && !xmethod.isStatic()) { if (DEBUG) { System.out.print(" (2) Checking inherited..."); } tqa = getInheritedTypeQualifierAnnotation(xmethod, parameter, typeQualifierValue); if (DEBUG) { System.out.println(tqa != null ? "FOUND" : "none"); } } // Check for default (outer scope) annotation if (tqa == null) { if (DEBUG) { System.out.print(" (3) Checking default..."); } tqa = getDefaultTypeQualifierAnnotation(xmethod, parameter, typeQualifierValue); if (DEBUG) { System.out.println(tqa != null ? "FOUND" : "none"); } } // Cache answer result = tqa; map.put(xmethod, parameter, result); if (DEBUG) { System.out.println(" => Answer: " + result); } } if (!map.containsKey(xmethod, parameter)) { throw new IllegalStateException("Did not populate cache?"); } // Return cached answer return result; } /** * Get the TypeQualifierAnnotation directly applied to given * method parameter. * * @param xmethod a method * @param parameter a parameter (0 == first parameter) * @param typeQualifierValue the kind of TypeQualifierValue we are looking for * @return TypeQualifierAnnotation directly applied to the parameter, * or null if there is no directly applied TypeQualifierAnnotation */ public static @CheckForNull TypeQualifierAnnotation getDirectTypeQualifierAnnotation(XMethod xmethod, int parameter, TypeQualifierValue typeQualifierValue) { Set<TypeQualifierAnnotation> applications = new HashSet<TypeQualifierAnnotation>(); getDirectApplications(applications, xmethod, parameter); if (DEBUG_METHOD != null && DEBUG_METHOD.equals(xmethod.getName())) { System.out.println(" Direct applications are: " + applications); } return findMatchingTypeQualifierAnnotation(applications, typeQualifierValue); } /** * Get the effective inherited TypeQualifierAnnotation on the given * instance method parameter. * * @param xmethod an instance method * @param parameter a parameter (0 == first parameter) * @param typeQualifierValue the kind of TypeQualifierValue we are looking for * @return effective inherited TypeQualifierAnnotation on the parameter, * or null if there is not effective TypeQualifierAnnotation */ private static @CheckForNull TypeQualifierAnnotation getInheritedTypeQualifierAnnotation(XMethod xmethod, int parameter, TypeQualifierValue typeQualifierValue) { assert !xmethod.isStatic(); ParameterAnnotationAccumulator accumulator = new ParameterAnnotationAccumulator(typeQualifierValue, xmethod, parameter); try { AnalysisContext.currentAnalysisContext().getSubtypes2().traverseSupertypes(xmethod.getClassDescriptor(), accumulator); return accumulator.getResult().getEffectiveTypeQualifierAnnotation(); } catch (ClassNotFoundException e) { AnalysisContext.currentAnalysisContext().getLookupFailureCallback().reportMissingClass(e); return null; } } /** * Get the default (outer-scope) TypeQualifierAnnotation on given method parameter. * * @param xmethod a method * @param parameter a parameter (0 == first parameter) * @param typeQualifierValue the kind of TypeQualifierValue we are looking for * @return the default (outer scope) TypeQualifierAnnotation on the parameter, * or null if there is no default TypeQualifierAnnotation */ private static @CheckForNull TypeQualifierAnnotation getDefaultTypeQualifierAnnotation( XMethod xmethod, int parameter, TypeQualifierValue typeQualifierValue) { if ((xmethod.getAccessFlags() & Opcodes.ACC_SYNTHETIC) != 0) return null; // synthetic methods don't get default annotations AnnotatedObject o = xmethod; while (true) { o = o.getContainingScope(); if (o == null) return null; // Check for direct type qualifier annotation Set<TypeQualifierAnnotation> applications = new HashSet<TypeQualifierAnnotation>(); getDirectApplications(applications, o, ElementType.PARAMETER); TypeQualifierAnnotation tqa = findMatchingTypeQualifierAnnotation(applications, typeQualifierValue); if (tqa != null) { // Found matching annotation in outer scope return tqa; } // Check for default annotation tqa = getDefaultAnnotation(o, typeQualifierValue, ElementType.PARAMETER); if (tqa != null) { return tqa; } } } private static TypeQualifierAnnotation computeExclusiveQualifier(TypeQualifierValue typeQualifierValue, ComputeEffectiveTypeQualifierAnnotation c) { assert typeQualifierValue.isExclusiveQualifier(); boolean isExhaustive = CHECK_EXHAUSTIVE && typeQualifierValue.isExhaustiveQualifier(); // Exclusive qualifiers: // - if there is an effective application of // a "complementary" TypeQualifierValue in which // when=ALWAYS. If so, then it's effectively // the same as the asked-for TypeQualifierValue, // but with when=NEVER. // // Exhaustive qualifiers: // - if all effective applications of "complementary" TypeQualifierValues // are when=NEVER, then the asked-for TypeQualifierValue // is effectively when=ALWAYS. boolean allComplementaryValuesAreWhenEqualsNever = true; Collection<TypeQualifierValue> complementaryTypeQualifierValues = TypeQualifierValue.getComplementaryExclusiveTypeQualifierValue(typeQualifierValue); for (TypeQualifierValue complementaryTypeQualifierValue : complementaryTypeQualifierValues) { TypeQualifierAnnotation complementaryTqa = c.compute(complementaryTypeQualifierValue); if (complementaryTqa != null) { if (complementaryTqa.when == When.ALWAYS) { // Exclusive qualifier where a complementary qualifier // was observed effectively when=ALWAYS. return TypeQualifierAnnotation.getValue(typeQualifierValue, When.NEVER); } else if (complementaryTqa.when != When.NEVER) { allComplementaryValuesAreWhenEqualsNever = false; } } else { allComplementaryValuesAreWhenEqualsNever = false; } } if (isExhaustive && allComplementaryValuesAreWhenEqualsNever) { // It's an exhaustive qualifier, and all complementary // qualifiers were effectively when=NEVER. if (TypeQualifierValue.DEBUG) { System.out.println("*** application of " + typeQualifierValue + " on " + c + " is when=ALWAYS due to exhaustion"); } return TypeQualifierAnnotation.getValue(typeQualifierValue, When.ALWAYS); } return null; } }
Make checking exhaustive qualifiers the default. git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@9732 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3
findbugs/src/java/edu/umd/cs/findbugs/ba/jsr305/TypeQualifierApplications.java
Make checking exhaustive qualifiers the default.
<ide><path>indbugs/src/java/edu/umd/cs/findbugs/ba/jsr305/TypeQualifierApplications.java <ide> * Should exclusive type qualifiers be handled? <ide> */ <ide> static final boolean CHECK_EXCLUSIVE = true;//SystemProperties.getBoolean("ctq.applications.checkexclusive"); <del> static final boolean CHECK_EXHAUSTIVE = SystemProperties.getBoolean("ctq.applications.checkexhaustive"); <add> static final boolean CHECK_EXHAUSTIVE = true; //SystemProperties.getBoolean("ctq.applications.checkexhaustive"); <ide> <ide> static class Data { <ide> /** Type qualifier annotations applied directly to methods/fields/classes/etc. */
Java
mit
error: pathspec 'generators/keycloak/templates/src/main/java/security/AjaxLogoutSuccessHandler.java' did not match any file(s) known to git
ca71f9ebdfb725c8918f25963e3bb72556a55534
1
giovannicandido/generator-spring-spa,giovannicandido/generator-spring-spa
package <%= packageName %>.security; import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.stereotype.Component; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; /** * Spring Security logout handler, specialized for Ajax requests. */ @Component public class AjaxLogoutSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler implements LogoutSuccessHandler { @Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { response.setStatus(HttpServletResponse.SC_OK); } }
generators/keycloak/templates/src/main/java/security/AjaxLogoutSuccessHandler.java
fix compile Added AjaxLogoutSuccessHandler
generators/keycloak/templates/src/main/java/security/AjaxLogoutSuccessHandler.java
fix compile Added AjaxLogoutSuccessHandler
<ide><path>enerators/keycloak/templates/src/main/java/security/AjaxLogoutSuccessHandler.java <add>package <%= packageName %>.security; <add> <add>import org.springframework.security.core.Authentication; <add>import org.springframework.security.web.authentication.AbstractAuthenticationTargetUrlRequestHandler; <add>import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; <add>import org.springframework.stereotype.Component; <add> <add>import javax.servlet.ServletException; <add>import javax.servlet.http.HttpServletRequest; <add>import javax.servlet.http.HttpServletResponse; <add>import java.io.IOException; <add> <add>/** <add> * Spring Security logout handler, specialized for Ajax requests. <add> */ <add>@Component <add>public class AjaxLogoutSuccessHandler extends AbstractAuthenticationTargetUrlRequestHandler <add> implements LogoutSuccessHandler { <add> <add> @Override <add> public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, <add> Authentication authentication) <add> throws IOException, ServletException { <add> response.setStatus(HttpServletResponse.SC_OK); <add> } <add>}
JavaScript
mit
1cf3318e738eac49435f7618b4a96ae07dc763c7
0
haensl/js-performance
'use strict'; const EventEmitter = require('events'); const join = require('path').join; const clock = require(join(__appRoot, 'src/support/clock/clock')); const events = require(join(__appRoot, 'src/support/events')); class ProfileRunner extends EventEmitter { /** * @constructor * @param {object} config Configuration object * @param {array} config.profiles An array of profiles * @param {number} config.iterations Number of iterations * @param {array} config.data An array of test data */ constructor(config) { super(); this.profiles = config.profiles.slice(); this.iterations = config.iterations; this.data = config.data; } /** * Starts this ProfileRunner */ run() { try { this.emit(events.START, this.profiles); const results = this.profiles.map((profile) => this.runProfile(profile)); this.emit(events.END, results); } catch (err) { this.emit(events.ERROR, err); } } /** * Runs a single profile * @private * @param {object} profile A profile * @returns {object} The test result */ runProfile(profile) { this.emit(events.PROFILE_START, profile); const result = { profile, testResults: profile.functions.map((func) => this.runFunction(profile, func)) }; this.emit(events.PROFILE_END, profile, result); return result; } /** * Runs a single profile function * @private * @param {object} profile A profile * @param {object} func A profile function * @returns {object} The test result */ runFunction(profile, func) { this.emit(events.TEST_START, profile, func); const testResult = { averageTime: 0, totalTime: 0, func }; for (let i = 0; i < this.iterations; i++) { testResult.totalTime += clock.time(func.f, this.data); } testResult.averageTime = testResult.totalTime / this.iterations; this.emit(events.TEST_END, profile, func, testResult); return testResult; } } module.exports = ProfileRunner;
src/profile-runner.js
'use strict'; const EventEmitter = require('events'); const join = require('path').join; const clock = require(join(__appRoot, 'src/support/clock/clock')); const events = require(join(__appRoot, 'src/support/events')); class ProfileRunner extends EventEmitter { /** * @constructor * @param {object} config Configuration object * @param {array} config.profiles An array of profiles * @param {number} config.iterations Number of iterations * @param {array} config.data An array of test data * @param {number} config.precision Number of decimals to show for results */ constructor(config) { super(); this.profiles = config.profiles.slice(); this.iterations = config.iterations; this.data = config.data; this.precision = config.precision; } /** * Starts this ProfileRunner */ run() { try { this.emit(events.START, this.profiles); const results = this.profiles.map((profile) => this.runProfile(profile)); this.emit(events.END, results); } catch (err) { this.emit(events.ERROR, err); } } /** * Runs a single profile * @private * @param {object} profile A profile * @returns {object} The test result */ runProfile(profile) { this.emit(events.PROFILE_START, profile); const result = { profile, testResults: profile.functions.map((func) => this.runFunction(profile, func)) }; this.emit(events.PROFILE_END, profile, result); return result; } /** * Runs a single profile function * @private * @param {object} profile A profile * @param {object} func A profile function * @returns {object} The test result */ runFunction(profile, func) { this.emit(events.TEST_START, profile, func); const testResult = { averageTime: 0, totalTime: 0, func }; for (let i = 0; i < this.iterations; i++) { testResult.totalTime += clock.time(func.f, this.data); } testResult.averageTime = testResult.totalTime / this.iterations; this.emit(events.TEST_END, profile, func, testResult); return testResult; } } module.exports = ProfileRunner;
Remove unused parameter.
src/profile-runner.js
Remove unused parameter.
<ide><path>rc/profile-runner.js <ide> * @param {array} config.profiles An array of profiles <ide> * @param {number} config.iterations Number of iterations <ide> * @param {array} config.data An array of test data <del> * @param {number} config.precision Number of decimals to show for results <ide> */ <ide> constructor(config) { <ide> super(); <ide> this.profiles = config.profiles.slice(); <ide> this.iterations = config.iterations; <ide> this.data = config.data; <del> this.precision = config.precision; <ide> } <ide> <ide> /**
JavaScript
mit
2a9aab18346c10ac677835f655f4b6a8fe5d6a53
0
ahatzz11/toolkit-for-ynab,blargity/toolkit-for-ynab,toolkit-for-ynab/toolkit-for-ynab,gpeden/ynab-enhanced,gpeden/ynab-enhanced,ahatzz11/toolkit-for-ynab,joshmadewell/toolkit-for-ynab,dbaldon/toolkit-for-ynab,toolkit-for-ynab/toolkit-for-ynab,mhum/ynab-enhanced,toolkit-for-ynab/toolkit-for-ynab,ahatzz11/toolkit-for-ynab,egens/toolkit-for-ynab,egens/toolkit-for-ynab,joshmadewell/toolkit-for-ynab,falkencreative/toolkit-for-ynab,blargity/toolkit-for-ynab,mhum/ynab-enhanced,gpeden/ynab-enhanced,mhum/ynab-enhanced,dbaldon/toolkit-for-ynab,mhum/ynab-enhanced,dbaldon/toolkit-for-ynab,joshmadewell/toolkit-for-ynab,falkencreative/toolkit-for-ynab,egens/toolkit-for-ynab,blargity/toolkit-for-ynab,ahatzz11/toolkit-for-ynab,joshmadewell/toolkit-for-ynab,egens/toolkit-for-ynab,gpeden/ynab-enhanced,blargity/toolkit-for-ynab,falkencreative/toolkit-for-ynab,toolkit-for-ynab/toolkit-for-ynab,falkencreative/toolkit-for-ynab,dbaldon/toolkit-for-ynab
(function poll() { if ( typeof ynabToolKit !== 'undefined' && ynabToolKit.pageReady === true) { ynabToolKit.resizeInspector = new function () { this.invoke = function() { if( $('.ember-view.content .budget-inspector').length > 0 ) { if($('.resize-inspector').length == 0) { $('.ember-view.content .scroll-wrap').addClass('resize-inspector'); $('aside').before('<div class="inspector-resize-handle">&nbsp;</div>'); $('.inspector-resize-handle').css('background-image','url('+window.resizeInspectorAsset+')'); $('section').resizable({ handleSelector: '.inspector-resize-handle', resizeHeight: false }); } } else { $('.resize-inspector').removeClass('resize-inspector'); } }, this.observe = function(changedNodes) { if (changedNodes.has('pure-g layout user-logged-in')) { // The user has switched screens ynabToolKit.resizeInspector.invoke(); } } }; ynabToolKit.resizeInspector.invoke(); // Run itself once } else { setTimeout(poll, 250); } })();
src/common/res/features/resize-inspector/resize-inspector.js
(function poll() { if ( typeof ynabToolKit !== 'undefined' && ynabToolKit.pageReady === true) { ynabToolKit.resizeInspector = new function () { this.invoke = function() { if( $('.ember-view.content .budget-inspector').length > 0 ) { if($('.resize-inspector').length == 0) { $('.ember-view.content .scroll-wrap').addClass('resize-inspector'); $('aside').before('<div class="inspector-resize-handle">&nbsp;</div>'); $('.inspector-resize-handle').css('background-image','url('+window.resizeInspectorAsset+')'); $('section').resizable({ handleSelector: '.inspector-resize-handle', resizeHeight: false }); } } else { $('.resize-inspector').removeClass('resize-inspector'); } }, this.observe = function(changedNodes) { if (changedNodes.has('layout')) { // The user has switched screens ynabToolKit.resizeInspector.invoke(); } } }; ynabToolKit.resizeInspector.invoke(); // Run itself once } else { setTimeout(poll, 250); } })();
Fixes #137.
src/common/res/features/resize-inspector/resize-inspector.js
Fixes #137.
<ide><path>rc/common/res/features/resize-inspector/resize-inspector.js <ide> <ide> this.observe = function(changedNodes) { <ide> <del> if (changedNodes.has('layout')) { <add> if (changedNodes.has('pure-g layout user-logged-in')) { <ide> // The user has switched screens <ide> ynabToolKit.resizeInspector.invoke(); <ide> }
Java
apache-2.0
a0700b862aaeb724c8684c8e7eb2382a90b358fe
0
ze-pequeno/retrofit,lichblitz/retrofit,lichblitz/retrofit,ze-pequeno/retrofit,lichblitz/retrofit,square/retrofit,square/retrofit,ze-pequeno/retrofit,ze-pequeno/retrofit,square/retrofit,square/retrofit
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package retrofit2; import android.os.Build; import android.os.Handler; import android.os.Looper; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodHandles.Lookup; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.List; import java.util.concurrent.Executor; import javax.annotation.Nullable; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; class Platform { private static final Platform PLATFORM = findPlatform(); static Platform get() { return PLATFORM; } private static Platform findPlatform() { try { Class.forName("android.os.Build"); if (Build.VERSION.SDK_INT != 0) { return new Android(); } } catch (ClassNotFoundException ignored) { } return new Platform(true); } private final boolean hasJava8Types; private final @Nullable Constructor<Lookup> lookupConstructor; Platform(boolean hasJava8Types) { this.hasJava8Types = hasJava8Types; Constructor<Lookup> lookupConstructor = null; if (hasJava8Types) { try { // Because the service interface might not be public, we need to use a MethodHandle lookup // that ignores the visibility of the declaringClass. lookupConstructor = Lookup.class.getDeclaredConstructor(Class.class, int.class); lookupConstructor.setAccessible(true); } catch (NoSuchMethodException ignored) { // Assume JDK 14+ which contains a fix that allows a regular lookup to succeed. // See https://bugs.openjdk.java.net/browse/JDK-8209005. } } this.lookupConstructor = lookupConstructor; } @Nullable Executor defaultCallbackExecutor() { return null; } List<? extends CallAdapter.Factory> defaultCallAdapterFactories( @Nullable Executor callbackExecutor) { DefaultCallAdapterFactory executorFactory = new DefaultCallAdapterFactory(callbackExecutor); return hasJava8Types ? asList(CompletableFutureCallAdapterFactory.INSTANCE, executorFactory) : singletonList(executorFactory); } int defaultCallAdapterFactoriesSize() { return hasJava8Types ? 2 : 1; } List<? extends Converter.Factory> defaultConverterFactories() { return hasJava8Types ? singletonList(OptionalConverterFactory.INSTANCE) : emptyList(); } int defaultConverterFactoriesSize() { return hasJava8Types ? 1 : 0; } boolean isDefaultMethod(Method method) { return hasJava8Types && method.isDefault(); } @Nullable Object invokeDefaultMethod(Method method, Class<?> declaringClass, Object object, @Nullable Object... args) throws Throwable { Lookup lookup = lookupConstructor != null ? lookupConstructor.newInstance(declaringClass, -1 /* trusted */) : MethodHandles.lookup(); return lookup .unreflectSpecial(method, declaringClass) .bindTo(object) .invokeWithArguments(args); } static final class Android extends Platform { Android() { super(Build.VERSION.SDK_INT >= 24); } @Override public Executor defaultCallbackExecutor() { return new MainThreadExecutor(); } static class MainThreadExecutor implements Executor { private final Handler handler = new Handler(Looper.getMainLooper()); @Override public void execute(Runnable r) { handler.post(r); } } } }
retrofit/src/main/java/retrofit2/Platform.java
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package retrofit2; import android.os.Build; import android.os.Handler; import android.os.Looper; import java.lang.invoke.MethodHandles.Lookup; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.List; import java.util.concurrent.Executor; import javax.annotation.Nullable; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; class Platform { private static final Platform PLATFORM = findPlatform(); static Platform get() { return PLATFORM; } private static Platform findPlatform() { try { Class.forName("android.os.Build"); if (Build.VERSION.SDK_INT != 0) { return new Android(); } } catch (ClassNotFoundException ignored) { } return new Platform(true); } private final boolean hasJava8Types; Platform(boolean hasJava8Types) { this.hasJava8Types = hasJava8Types; } @Nullable Executor defaultCallbackExecutor() { return null; } List<? extends CallAdapter.Factory> defaultCallAdapterFactories( @Nullable Executor callbackExecutor) { DefaultCallAdapterFactory executorFactory = new DefaultCallAdapterFactory(callbackExecutor); return hasJava8Types ? asList(CompletableFutureCallAdapterFactory.INSTANCE, executorFactory) : singletonList(executorFactory); } int defaultCallAdapterFactoriesSize() { return hasJava8Types ? 2 : 1; } List<? extends Converter.Factory> defaultConverterFactories() { return hasJava8Types ? singletonList(OptionalConverterFactory.INSTANCE) : emptyList(); } int defaultConverterFactoriesSize() { return hasJava8Types ? 1 : 0; } boolean isDefaultMethod(Method method) { return hasJava8Types && method.isDefault(); } @Nullable Object invokeDefaultMethod(Method method, Class<?> declaringClass, Object object, @Nullable Object... args) throws Throwable { // Because the service interface might not be public, we need to use a MethodHandle lookup // that ignores the visibility of the declaringClass. Constructor<Lookup> constructor = Lookup.class.getDeclaredConstructor(Class.class, int.class); constructor.setAccessible(true); return constructor.newInstance(declaringClass, -1 /* trusted */) .unreflectSpecial(method, declaringClass) .bindTo(object) .invokeWithArguments(args); } static final class Android extends Platform { Android() { super(Build.VERSION.SDK_INT >= 24); } @Override public Executor defaultCallbackExecutor() { return new MainThreadExecutor(); } static class MainThreadExecutor implements Executor { private final Handler handler = new Handler(Looper.getMainLooper()); @Override public void execute(Runnable r) { handler.post(r); } } } }
Add Java 14+ support for default methods The bug which required the reflective use of a hidden constructor is fixed in Java 14 and the normal lookup can just be used. Moreover, that private constructor is no longer even available.
retrofit/src/main/java/retrofit2/Platform.java
Add Java 14+ support for default methods
<ide><path>etrofit/src/main/java/retrofit2/Platform.java <ide> import android.os.Build; <ide> import android.os.Handler; <ide> import android.os.Looper; <add>import java.lang.invoke.MethodHandles; <ide> import java.lang.invoke.MethodHandles.Lookup; <ide> import java.lang.reflect.Constructor; <ide> import java.lang.reflect.Method; <ide> } <ide> <ide> private final boolean hasJava8Types; <add> private final @Nullable Constructor<Lookup> lookupConstructor; <ide> <ide> Platform(boolean hasJava8Types) { <ide> this.hasJava8Types = hasJava8Types; <add> <add> Constructor<Lookup> lookupConstructor = null; <add> if (hasJava8Types) { <add> try { <add> // Because the service interface might not be public, we need to use a MethodHandle lookup <add> // that ignores the visibility of the declaringClass. <add> lookupConstructor = Lookup.class.getDeclaredConstructor(Class.class, int.class); <add> lookupConstructor.setAccessible(true); <add> } catch (NoSuchMethodException ignored) { <add> // Assume JDK 14+ which contains a fix that allows a regular lookup to succeed. <add> // See https://bugs.openjdk.java.net/browse/JDK-8209005. <add> } <add> } <add> this.lookupConstructor = lookupConstructor; <ide> } <ide> <ide> @Nullable Executor defaultCallbackExecutor() { <ide> <ide> @Nullable Object invokeDefaultMethod(Method method, Class<?> declaringClass, Object object, <ide> @Nullable Object... args) throws Throwable { <del> // Because the service interface might not be public, we need to use a MethodHandle lookup <del> // that ignores the visibility of the declaringClass. <del> Constructor<Lookup> constructor = Lookup.class.getDeclaredConstructor(Class.class, int.class); <del> constructor.setAccessible(true); <del> return constructor.newInstance(declaringClass, -1 /* trusted */) <add> Lookup lookup = lookupConstructor != null <add> ? lookupConstructor.newInstance(declaringClass, -1 /* trusted */) <add> : MethodHandles.lookup(); <add> return lookup <ide> .unreflectSpecial(method, declaringClass) <ide> .bindTo(object) <ide> .invokeWithArguments(args);
Java
mit
eac3971390c1b2cb7636ce289af470dd7668dfe8
0
domix/lombok,Shedings/hrisey,yangpeiyong/hrisey,martenbohlin/lombok,Tradunsky/lombok,MaTriXy/lombok,jdiasamaro/lombok,jdiasamaro/lombok,timtreibmann/lombokDataReceived,Shedings/hrisey,yangpeiyong/hrisey,wuwen5/lombok,dcendents/lombok,wuwen5/lombok,luanpotter/lombok,MaTriXy/lombok,redundent/lombok,redundent/lombok,Tradunsky/lombok,rzwitserloot/lombok,luanpotter/lombok,rzwitserloot/lombok,jdiasamaro/lombok,MaTriXy/lombok,fpeter8/lombok,dcendents/lombok,openlegacy/lombok,openlegacy/lombok,Lekanich/lombok,Tradunsky/lombok,dcendents/lombok,rzwitserloot/lombok,mg6maciej/hrisey,derektom14/lombok,Lekanich/lombok,Lekanich/lombok,vampiregod1996/lombok,fpeter8/lombok,riccardobl/lombok,redundent/lombok,riccardobl/lombok,mg6maciej/hrisey,jdiasamaro/lombok,timtreibmann/lombokDataReceived,yangpeiyong/hrisey,fpeter8/lombok,Lekanich/lombok,fpeter8/lombok,Shedings/hrisey,Beabel2/lombok,Tradunsky/lombok,luanpotter/lombok,timtreibmann/lombokDataReceived,wuwen5/lombok,dmissoh/lombok,nickbarban/lombok,Beabel2/lombok,nickbarban/lombok,arielnetworks/lombok,Arvoreen/lombok,nickbarban/lombok,dcendents/lombok,openlegacy/lombok,dmissoh/lombok,consulo/lombokOld,fpeter8/lombok,wuwen5/lombok,yangpeiyong/hrisey,Shedings/hrisey,timtreibmann/lombokDataReceived,Arvoreen/lombok,riccardobl/lombok,Arvoreen/lombok,mg6maciej/hrisey,MaTriXy/lombok,mg6maciej/hrisey,arielnetworks/lombok,develhack/develhacked-lombok,dmissoh/lombok,luanpotter/lombok,vampiregod1996/lombok,arielnetworks/lombok,derektom14/lombok,Arvoreen/lombok,develhack/develhacked-lombok,Beabel2/lombok,derektom14/lombok,nickbarban/lombok,develhack/develhacked-lombok,rzwitserloot/lombok,martenbohlin/lombok,rzwitserloot/lombok,domix/lombok,openlegacy/lombok,martenbohlin/lombok,Beabel2/lombok,domix/lombok,riccardobl/lombok,fpeter8/lombok,dmissoh/lombok,martenbohlin/lombok,derektom14/lombok,develhack/develhacked-lombok,vampiregod1996/lombok,vampiregod1996/lombok
/* * Copyright © 2009-2011 Reinier Zwitserloot and Roel Spilker. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.agent; import java.lang.instrument.Instrumentation; import java.util.Collection; import java.util.Collections; import java.util.List; import lombok.core.Agent; import lombok.patcher.Hook; import lombok.patcher.MethodTarget; import lombok.patcher.ScriptManager; import lombok.patcher.StackRequest; import lombok.patcher.TargetMatcher; import lombok.patcher.equinox.EquinoxClassLoader; import lombok.patcher.scripts.ScriptBuilder; /** * This is a java-agent that patches some of eclipse's classes so AST Nodes are handed off to Lombok * for modification before Eclipse actually uses them to compile, render errors, show code outlines, * create auto-completion dialogs, and anything else eclipse does with java code. See the *Transformer * classes in this package for more information about which classes are transformed and how they are * transformed. */ public class EclipsePatcher extends Agent { // At some point I'd like the agent to be capable of auto-detecting if its on eclipse or on ecj. This class is a sure sign we're not in ecj but in eclipse. -ReinierZ @SuppressWarnings("unused") private static final String ECLIPSE_SIGNATURE_CLASS = "org/eclipse/core/runtime/adaptor/EclipseStarter"; @Override public void runAgent(String agentArgs, Instrumentation instrumentation, boolean injected) throws Exception { String[] args = agentArgs == null ? new String[0] : agentArgs.split(":"); boolean forceEcj = false; boolean forceEclipse = false; for (String arg : args) { if (arg.trim().equalsIgnoreCase("ECJ")) forceEcj = true; if (arg.trim().equalsIgnoreCase("ECLIPSE")) forceEclipse = true; } if (forceEcj && forceEclipse) { forceEcj = false; forceEclipse = false; } boolean ecj; if (forceEcj) ecj = true; else if (forceEclipse) ecj = false; else ecj = injected; registerPatchScripts(instrumentation, injected, ecj); } private static void registerPatchScripts(Instrumentation instrumentation, boolean reloadExistingClasses, boolean ecjOnly) { ScriptManager sm = new ScriptManager(); sm.registerTransformer(instrumentation); if (!ecjOnly) { EquinoxClassLoader.addPrefix("lombok."); EquinoxClassLoader.registerScripts(sm); } patchAvoidReparsingGeneratedCode(sm); if (!ecjOnly) { patchCatchReparse(sm); patchIdentifierEndReparse(sm); patchRetrieveEllipsisStartPosition(sm); patchSetGeneratedFlag(sm); patchHideGeneratedNodes(sm); patchLiveDebug(sm); patchPostCompileHookEclipse(sm); patchFixSourceTypeConverter(sm); } else { patchPostCompileHookEcj(sm); } patchLombokizeAST(sm); patchEcjTransformers(sm, ecjOnly); if (reloadExistingClasses) sm.reloadClasses(instrumentation); } private static void patchPostCompileHookEclipse(ScriptManager sm) { sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.core.builder.IncrementalImageBuilder", "writeClassFileContents")) .target(new MethodTarget("org.eclipse.jdt.internal.core.builder.AbstractImageBuilder", "writeClassFileContents")) .methodToWrap(new Hook("org.eclipse.jdt.internal.compiler.ClassFile", "getBytes", "byte[]")) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "runPostCompiler", "byte[]", "byte[]", "java.lang.String")) .requestExtra(StackRequest.PARAM3) .transplant() .build()); } private static void patchPostCompileHookEcj(ScriptManager sm) { sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.compiler.tool.EclipseCompilerImpl", "outputClassFiles")) .methodToWrap(new Hook("javax.tools.JavaFileObject", "openOutputStream", "java.io.OutputStream")) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "runPostCompiler", "java.io.OutputStream", "java.io.OutputStream")) .build()); sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.compiler.util.Util", "writeToDisk")) .methodToWrap(new Hook("java.io.BufferedOutputStream", "<init>", "void", "java.io.OutputStream", "int")) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "runPostCompiler", "java.io.BufferedOutputStream", "java.io.BufferedOutputStream", "java.lang.String", "java.lang.String")) .requestExtra(StackRequest.PARAM2, StackRequest.PARAM3) .build()); } private static void patchHideGeneratedNodes(ScriptManager sm) { sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget("org.eclipse.jdt.internal.corext.dom.LinkedNodeFinder", "findByNode")) .target(new MethodTarget("org.eclipse.jdt.internal.corext.dom.LinkedNodeFinder", "findByBinding")) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "removeGeneratedSimpleNames", "org.eclipse.jdt.core.dom.SimpleName[]", "org.eclipse.jdt.core.dom.SimpleName[]")) .request(StackRequest.RETURN_VALUE).build()); patchRefactorScripts(sm); patchFormatters(sm); } private static void patchFormatters(ScriptManager sm) { sm.addScript(ScriptBuilder.setSymbolDuringMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy", "format", "void")) .callToWrap(new Hook("org.eclipse.jdt.internal.corext.util.CodeFormatterUtil", "reformat", "org.eclipse.text.edits.TextEdit", "int", "java.lang.String", "int", "int", "int", "java.lang.String", "java.util.Map")) .symbol("lombok.disable").build()); } private static void patchRefactorScripts(ScriptManager sm) { sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget("org.eclipse.jdt.core.dom.rewrite.ASTRewrite", "replace")) .target(new MethodTarget("org.eclipse.jdt.core.dom.rewrite.ASTRewrite", "remove")) .decisionMethod(new Hook("lombok.eclipse.agent.PatchFixes", "skipRewritingGeneratedNodes", "boolean", "org.eclipse.jdt.core.dom.ASTNode")) .transplant().request(StackRequest.PARAM1).build()); sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor", "addConstructorRenames")) .methodToWrap(new Hook("org.eclipse.jdt.core.IType", "getMethods", "org.eclipse.jdt.core.IMethod[]")) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "removeGeneratedMethods", "org.eclipse.jdt.core.IMethod[]", "org.eclipse.jdt.core.IMethod[]")) .transplant().build()); } private static void patchCatchReparse(ScriptManager sm) { sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "retrieveStartingCatchPosition")) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "fixRetrieveStartingCatchPosition", "int", "int", "int")) .transplant().request(StackRequest.RETURN_VALUE, StackRequest.PARAM1).build()); } private static void patchIdentifierEndReparse(ScriptManager sm) { sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "retrieveIdentifierEndPosition")) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "fixRetrieveIdentifierEndPosition", "int", "int", "int")) .transplant().request(StackRequest.RETURN_VALUE, StackRequest.PARAM2).build()); } private static void patchRetrieveEllipsisStartPosition(ScriptManager sm) { sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "retrieveEllipsisStartPosition")) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "fixRetrieveEllipsisStartPosition", "int", "int", "int")) .transplant().request(StackRequest.RETURN_VALUE, StackRequest.PARAM2).build()); } private static void patchSetGeneratedFlag(ScriptManager sm) { sm.addScript(ScriptBuilder.addField() .targetClass("org.eclipse.jdt.internal.compiler.ast.ASTNode") .fieldName("$generatedBy") .fieldType("Lorg/eclipse/jdt/internal/compiler/ast/ASTNode;") .setPublic().setTransient().build()); sm.addScript(ScriptBuilder.addField() .targetClass("org.eclipse.jdt.core.dom.ASTNode") .fieldName("$isGenerated").fieldType("Z") .setPublic().setTransient().build()); sm.addScript(ScriptBuilder.wrapReturnValue() .target(new TargetMatcher() { @Override public boolean matches(String classSpec, String methodName, String descriptor) { if (!"convert".equals(methodName)) return false; List<String> fullDesc = MethodTarget.decomposeFullDesc(descriptor); if ("V".equals(fullDesc.get(0))) return false; if (fullDesc.size() < 2) return false; if (!fullDesc.get(1).startsWith("Lorg/eclipse/jdt/internal/compiler/ast/")) return false; return true; } @Override public Collection<String> getAffectedClasses() { return Collections.singleton("org.eclipse.jdt.core.dom.ASTConverter"); } }).request(StackRequest.PARAM1, StackRequest.RETURN_VALUE) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "setIsGeneratedFlag", "void", "org.eclipse.jdt.core.dom.ASTNode", "org.eclipse.jdt.internal.compiler.ast.ASTNode")) .transplant().build()); sm.addScript(ScriptBuilder.wrapMethodCall() .target(new TargetMatcher() { @Override public boolean matches(String classSpec, String methodName, String descriptor) { if (!methodName.startsWith("convert")) return false; List<String> fullDesc = MethodTarget.decomposeFullDesc(descriptor); if (fullDesc.size() < 2) return false; if (!fullDesc.get(1).startsWith("Lorg/eclipse/jdt/internal/compiler/ast/")) return false; return true; } @Override public Collection<String> getAffectedClasses() { return Collections.singleton("org.eclipse.jdt.core.dom.ASTConverter"); } }).methodToWrap(new Hook("org.eclipse.jdt.core.dom.SimpleName", "<init>", "void", "org.eclipse.jdt.core.dom.AST")) .requestExtra(StackRequest.PARAM1) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "setIsGeneratedFlagForSimpleName", "void", "org.eclipse.jdt.core.dom.SimpleName", "java.lang.Object")) .transplant().build()); } /** * XXX LIVE DEBUG * * Adds patches to improve error reporting in cases of extremely rare bugs that are hard to reproduce. These should be removed * once the issue has been solved! */ private static void patchLiveDebug(ScriptManager sm) { sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget( "org.eclipse.jdt.internal.compiler.ast.MethodDeclaration", "resolveStatements", "void")) .decisionMethod(new Hook("lombok.eclipse.agent.PatchFixes", "debugPrintStateOfScope", "boolean", "java.lang.Object")) .request(StackRequest.THIS).build()); } private static void patchAvoidReparsingGeneratedCode(ScriptManager sm) { final String PARSER_SIG = "org.eclipse.jdt.internal.compiler.parser.Parser"; sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget(PARSER_SIG, "parse", "void", "org.eclipse.jdt.internal.compiler.ast.MethodDeclaration", "org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration")) .decisionMethod(new Hook("lombok.eclipse.agent.PatchFixes", "checkBit24", "boolean", "java.lang.Object")) .request(StackRequest.PARAM1).build()); sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget(PARSER_SIG, "parse", "void", "org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration", "org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration", "boolean")) .decisionMethod(new Hook("lombok.eclipse.agent.PatchFixes", "checkBit24", "boolean", "java.lang.Object")) .request(StackRequest.PARAM1).build()); sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget(PARSER_SIG, "parse", "void", "org.eclipse.jdt.internal.compiler.ast.Initializer", "org.eclipse.jdt.internal.compiler.ast.TypeDeclaration", "org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration")) .decisionMethod(new Hook("lombok.eclipse.agent.PatchFixes", "checkBit24", "boolean", "java.lang.Object")) .request(StackRequest.PARAM1).build()); } private static void patchLombokizeAST(ScriptManager sm) { sm.addScript(ScriptBuilder.addField() .targetClass("org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration") .fieldName("$lombokAST").fieldType("Ljava/lang/Object;") .setPublic().setTransient().build()); final String PARSER_SIG = "org.eclipse.jdt.internal.compiler.parser.Parser"; final String CUD_SIG = "org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration"; sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget(PARSER_SIG, "getMethodBodies", "void", CUD_SIG)) .wrapMethod(new Hook("lombok.eclipse.TransformEclipseAST", "transform", "void", PARSER_SIG, CUD_SIG)) .request(StackRequest.THIS, StackRequest.PARAM1).build()); sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget(PARSER_SIG, "endParse", CUD_SIG, "int")) .wrapMethod(new Hook("lombok.eclipse.TransformEclipseAST", "transform_swapped", "void", CUD_SIG, PARSER_SIG)) .request(StackRequest.THIS, StackRequest.RETURN_VALUE).build()); } private static void patchEcjTransformers(ScriptManager sm, boolean ecj) { addPatchesForDelegate(sm, ecj); addPatchesForVal(sm); if (!ecj) addPatchesForValEclipse(sm); } private static void addPatchesForDelegate(ScriptManager sm, boolean ecj) { final String CLASSSCOPE_SIG = "org.eclipse.jdt.internal.compiler.lookup.ClassScope"; sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget(CLASSSCOPE_SIG, "buildFieldsAndMethods", "void")) .request(StackRequest.THIS) .decisionMethod(new Hook(PatchDelegate.class.getName(), "handleDelegateForType", "boolean", CLASSSCOPE_SIG)) .build()); } private static void addPatchesForValEclipse(ScriptManager sm) { final String LOCALDECLARATION_SIG = "org.eclipse.jdt.internal.compiler.ast.LocalDeclaration"; final String PARSER_SIG = "org.eclipse.jdt.internal.compiler.parser.Parser"; final String VARIABLEDECLARATIONSTATEMENT_SIG = "org.eclipse.jdt.core.dom.VariableDeclarationStatement"; final String ASTCONVERTER_SIG = "org.eclipse.jdt.core.dom.ASTConverter"; sm.addScript(ScriptBuilder.addField() .fieldName("$initCopy") .fieldType("Lorg/eclipse/jdt/internal/compiler/ast/ASTNode;") .setPublic() .setTransient() .targetClass("org.eclipse.jdt.internal.compiler.ast.LocalDeclaration") .build()); sm.addScript(ScriptBuilder.addField() .fieldName("$iterableCopy") .fieldType("Lorg/eclipse/jdt/internal/compiler/ast/ASTNode;") .setPublic() .setTransient() .targetClass("org.eclipse.jdt.internal.compiler.ast.LocalDeclaration") .build()); sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget(PARSER_SIG, "consumeExitVariableWithInitialization", "void")) .request(StackRequest.THIS) .wrapMethod(new Hook("lombok.eclipse.agent.PatchValEclipsePortal", "copyInitializationOfLocalDeclaration", "void", "java.lang.Object")) .build()); sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget(PARSER_SIG, "consumeEnhancedForStatementHeader", "void")) .request(StackRequest.THIS) .wrapMethod(new Hook("lombok.eclipse.agent.PatchValEclipsePortal", "copyInitializationOfForEachIterable", "void", "java.lang.Object")) .build()); sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget(ASTCONVERTER_SIG, "setModifiers", "void", VARIABLEDECLARATIONSTATEMENT_SIG, LOCALDECLARATION_SIG)) .wrapMethod(new Hook("lombok.eclipse.agent.PatchValEclipsePortal", "addFinalAndValAnnotationToVariableDeclarationStatement", "void", "java.lang.Object", "java.lang.Object", "java.lang.Object")) .request(StackRequest.THIS, StackRequest.PARAM1, StackRequest.PARAM2).build()); } private static void addPatchesForVal(ScriptManager sm) { final String LOCALDECLARATION_SIG = "org.eclipse.jdt.internal.compiler.ast.LocalDeclaration"; final String FOREACHSTATEMENT_SIG = "org.eclipse.jdt.internal.compiler.ast.ForeachStatement"; final String EXPRESSION_SIG = "org.eclipse.jdt.internal.compiler.ast.Expression"; final String BLOCKSCOPE_SIG = "org.eclipse.jdt.internal.compiler.lookup.BlockScope"; final String TYPEBINDING_SIG = "org.eclipse.jdt.internal.compiler.lookup.TypeBinding"; sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget(LOCALDECLARATION_SIG, "resolve", "void", BLOCKSCOPE_SIG)) .request(StackRequest.THIS, StackRequest.PARAM1) .decisionMethod(new Hook("lombok.eclipse.agent.PatchVal", "handleValForLocalDeclaration", "boolean", LOCALDECLARATION_SIG, BLOCKSCOPE_SIG)) .build()); sm.addScript(ScriptBuilder.replaceMethodCall() .target(new MethodTarget(LOCALDECLARATION_SIG, "resolve", "void", BLOCKSCOPE_SIG)) .methodToReplace(new Hook(EXPRESSION_SIG, "resolveType", TYPEBINDING_SIG, BLOCKSCOPE_SIG)) .requestExtra(StackRequest.THIS) .replacementMethod(new Hook("lombok.eclipse.agent.PatchVal", "skipResolveInitializerIfAlreadyCalled2", TYPEBINDING_SIG, EXPRESSION_SIG, BLOCKSCOPE_SIG, LOCALDECLARATION_SIG)) .build()); sm.addScript(ScriptBuilder.replaceMethodCall() .target(new MethodTarget(FOREACHSTATEMENT_SIG, "resolve", "void", BLOCKSCOPE_SIG)) .methodToReplace(new Hook(EXPRESSION_SIG, "resolveType", TYPEBINDING_SIG, BLOCKSCOPE_SIG)) .replacementMethod(new Hook("lombok.eclipse.agent.PatchVal", "skipResolveInitializerIfAlreadyCalled", TYPEBINDING_SIG, EXPRESSION_SIG, BLOCKSCOPE_SIG)) .build()); sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget(FOREACHSTATEMENT_SIG, "resolve", "void", BLOCKSCOPE_SIG)) .request(StackRequest.THIS, StackRequest.PARAM1) .decisionMethod(new Hook("lombok.eclipse.agent.PatchVal", "handleValForForEach", "boolean", FOREACHSTATEMENT_SIG, BLOCKSCOPE_SIG)) .build()); } private static void patchFixSourceTypeConverter(ScriptManager sm) { final String SOURCE_TYPE_CONVERTER_SIG = "org.eclipse.jdt.internal.compiler.parser.SourceTypeConverter"; final String I_ANNOTATABLE_SIG = "org.eclipse.jdt.core.IAnnotatable"; final String ANNOTATION_SIG = "org.eclipse.jdt.internal.compiler.ast.Annotation"; sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget(SOURCE_TYPE_CONVERTER_SIG, "convertAnnotations", ANNOTATION_SIG + "[]", I_ANNOTATABLE_SIG)) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "convertAnnotations", ANNOTATION_SIG + "[]", ANNOTATION_SIG + "[]", I_ANNOTATABLE_SIG)) .request(StackRequest.PARAM1, StackRequest.RETURN_VALUE).build()); } }
src/eclipseAgent/lombok/eclipse/agent/EclipsePatcher.java
/* * Copyright © 2009-2011 Reinier Zwitserloot and Roel Spilker. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package lombok.eclipse.agent; import java.lang.instrument.Instrumentation; import java.util.Collection; import java.util.Collections; import java.util.List; import lombok.core.Agent; import lombok.patcher.Hook; import lombok.patcher.MethodTarget; import lombok.patcher.ScriptManager; import lombok.patcher.StackRequest; import lombok.patcher.TargetMatcher; import lombok.patcher.equinox.EquinoxClassLoader; import lombok.patcher.scripts.ScriptBuilder; /** * This is a java-agent that patches some of eclipse's classes so AST Nodes are handed off to Lombok * for modification before Eclipse actually uses them to compile, render errors, show code outlines, * create auto-completion dialogs, and anything else eclipse does with java code. See the *Transformer * classes in this package for more information about which classes are transformed and how they are * transformed. */ public class EclipsePatcher extends Agent { // At some point I'd like the agent to be capable of auto-detecting if its on eclipse or on ecj. This class is a sure sign we're not in ecj but in eclipse. -ReinierZ @SuppressWarnings("unused") private static final String ECLIPSE_SIGNATURE_CLASS = "org/eclipse/core/runtime/adaptor/EclipseStarter"; @Override public void runAgent(String agentArgs, Instrumentation instrumentation, boolean injected) throws Exception { String[] args = agentArgs == null ? new String[0] : agentArgs.split(":"); boolean forceEcj = false; boolean forceEclipse = false; for (String arg : args) { if (arg.trim().equalsIgnoreCase("ECJ")) forceEcj = true; if (arg.trim().equalsIgnoreCase("ECLIPSE")) forceEclipse = true; } if (forceEcj && forceEclipse) { forceEcj = false; forceEclipse = false; } boolean ecj; if (forceEcj) ecj = true; else if (forceEclipse) ecj = false; else ecj = injected; registerPatchScripts(instrumentation, injected, ecj); } private static void registerPatchScripts(Instrumentation instrumentation, boolean reloadExistingClasses, boolean ecjOnly) { ScriptManager sm = new ScriptManager(); sm.registerTransformer(instrumentation); if (!ecjOnly) { EquinoxClassLoader.addPrefix("lombok."); EquinoxClassLoader.registerScripts(sm); } patchAvoidReparsingGeneratedCode(sm); if (!ecjOnly) { patchLombokizeAST(sm); patchCatchReparse(sm); patchIdentifierEndReparse(sm); patchRetrieveEllipsisStartPosition(sm); patchSetGeneratedFlag(sm); patchHideGeneratedNodes(sm); patchLiveDebug(sm); patchPostCompileHookEclipse(sm); patchFixSourceTypeConverter(sm); } else { patchPostCompileHookEcj(sm); } patchEcjTransformers(sm, ecjOnly); if (reloadExistingClasses) sm.reloadClasses(instrumentation); } private static void patchPostCompileHookEclipse(ScriptManager sm) { sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.core.builder.IncrementalImageBuilder", "writeClassFileContents")) .target(new MethodTarget("org.eclipse.jdt.internal.core.builder.AbstractImageBuilder", "writeClassFileContents")) .methodToWrap(new Hook("org.eclipse.jdt.internal.compiler.ClassFile", "getBytes", "byte[]")) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "runPostCompiler", "byte[]", "byte[]", "java.lang.String")) .requestExtra(StackRequest.PARAM3) .transplant() .build()); } private static void patchPostCompileHookEcj(ScriptManager sm) { sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.compiler.tool.EclipseCompilerImpl", "outputClassFiles")) .methodToWrap(new Hook("javax.tools.JavaFileObject", "openOutputStream", "java.io.OutputStream")) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "runPostCompiler", "java.io.OutputStream", "java.io.OutputStream")) .build()); sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.compiler.util.Util", "writeToDisk")) .methodToWrap(new Hook("java.io.BufferedOutputStream", "<init>", "void", "java.io.OutputStream", "int")) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "runPostCompiler", "java.io.BufferedOutputStream", "java.io.BufferedOutputStream", "java.lang.String", "java.lang.String")) .requestExtra(StackRequest.PARAM2, StackRequest.PARAM3) .build()); } private static void patchHideGeneratedNodes(ScriptManager sm) { sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget("org.eclipse.jdt.internal.corext.dom.LinkedNodeFinder", "findByNode")) .target(new MethodTarget("org.eclipse.jdt.internal.corext.dom.LinkedNodeFinder", "findByBinding")) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "removeGeneratedSimpleNames", "org.eclipse.jdt.core.dom.SimpleName[]", "org.eclipse.jdt.core.dom.SimpleName[]")) .request(StackRequest.RETURN_VALUE).build()); patchRefactorScripts(sm); patchFormatters(sm); } private static void patchFormatters(ScriptManager sm) { sm.addScript(ScriptBuilder.setSymbolDuringMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.ui.text.java.JavaFormattingStrategy", "format", "void")) .callToWrap(new Hook("org.eclipse.jdt.internal.corext.util.CodeFormatterUtil", "reformat", "org.eclipse.text.edits.TextEdit", "int", "java.lang.String", "int", "int", "int", "java.lang.String", "java.util.Map")) .symbol("lombok.disable").build()); } private static void patchRefactorScripts(ScriptManager sm) { sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget("org.eclipse.jdt.core.dom.rewrite.ASTRewrite", "replace")) .target(new MethodTarget("org.eclipse.jdt.core.dom.rewrite.ASTRewrite", "remove")) .decisionMethod(new Hook("lombok.eclipse.agent.PatchFixes", "skipRewritingGeneratedNodes", "boolean", "org.eclipse.jdt.core.dom.ASTNode")) .transplant().request(StackRequest.PARAM1).build()); sm.addScript(ScriptBuilder.wrapMethodCall() .target(new MethodTarget("org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor", "addConstructorRenames")) .methodToWrap(new Hook("org.eclipse.jdt.core.IType", "getMethods", "org.eclipse.jdt.core.IMethod[]")) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "removeGeneratedMethods", "org.eclipse.jdt.core.IMethod[]", "org.eclipse.jdt.core.IMethod[]")) .transplant().build()); } private static void patchCatchReparse(ScriptManager sm) { sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "retrieveStartingCatchPosition")) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "fixRetrieveStartingCatchPosition", "int", "int", "int")) .transplant().request(StackRequest.RETURN_VALUE, StackRequest.PARAM1).build()); } private static void patchIdentifierEndReparse(ScriptManager sm) { sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "retrieveIdentifierEndPosition")) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "fixRetrieveIdentifierEndPosition", "int", "int", "int")) .transplant().request(StackRequest.RETURN_VALUE, StackRequest.PARAM2).build()); } private static void patchRetrieveEllipsisStartPosition(ScriptManager sm) { sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget("org.eclipse.jdt.core.dom.ASTConverter", "retrieveEllipsisStartPosition")) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "fixRetrieveEllipsisStartPosition", "int", "int", "int")) .transplant().request(StackRequest.RETURN_VALUE, StackRequest.PARAM2).build()); } private static void patchSetGeneratedFlag(ScriptManager sm) { sm.addScript(ScriptBuilder.addField() .targetClass("org.eclipse.jdt.internal.compiler.ast.ASTNode") .fieldName("$generatedBy") .fieldType("Lorg/eclipse/jdt/internal/compiler/ast/ASTNode;") .setPublic().setTransient().build()); sm.addScript(ScriptBuilder.addField() .targetClass("org.eclipse.jdt.core.dom.ASTNode") .fieldName("$isGenerated").fieldType("Z") .setPublic().setTransient().build()); sm.addScript(ScriptBuilder.wrapReturnValue() .target(new TargetMatcher() { @Override public boolean matches(String classSpec, String methodName, String descriptor) { if (!"convert".equals(methodName)) return false; List<String> fullDesc = MethodTarget.decomposeFullDesc(descriptor); if ("V".equals(fullDesc.get(0))) return false; if (fullDesc.size() < 2) return false; if (!fullDesc.get(1).startsWith("Lorg/eclipse/jdt/internal/compiler/ast/")) return false; return true; } @Override public Collection<String> getAffectedClasses() { return Collections.singleton("org.eclipse.jdt.core.dom.ASTConverter"); } }).request(StackRequest.PARAM1, StackRequest.RETURN_VALUE) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "setIsGeneratedFlag", "void", "org.eclipse.jdt.core.dom.ASTNode", "org.eclipse.jdt.internal.compiler.ast.ASTNode")) .transplant().build()); sm.addScript(ScriptBuilder.wrapMethodCall() .target(new TargetMatcher() { @Override public boolean matches(String classSpec, String methodName, String descriptor) { if (!methodName.startsWith("convert")) return false; List<String> fullDesc = MethodTarget.decomposeFullDesc(descriptor); if (fullDesc.size() < 2) return false; if (!fullDesc.get(1).startsWith("Lorg/eclipse/jdt/internal/compiler/ast/")) return false; return true; } @Override public Collection<String> getAffectedClasses() { return Collections.singleton("org.eclipse.jdt.core.dom.ASTConverter"); } }).methodToWrap(new Hook("org.eclipse.jdt.core.dom.SimpleName", "<init>", "void", "org.eclipse.jdt.core.dom.AST")) .requestExtra(StackRequest.PARAM1) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "setIsGeneratedFlagForSimpleName", "void", "org.eclipse.jdt.core.dom.SimpleName", "java.lang.Object")) .transplant().build()); } /** * XXX LIVE DEBUG * * Adds patches to improve error reporting in cases of extremely rare bugs that are hard to reproduce. These should be removed * once the issue has been solved! */ private static void patchLiveDebug(ScriptManager sm) { sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget( "org.eclipse.jdt.internal.compiler.ast.MethodDeclaration", "resolveStatements", "void")) .decisionMethod(new Hook("lombok.eclipse.agent.PatchFixes", "debugPrintStateOfScope", "boolean", "java.lang.Object")) .request(StackRequest.THIS).build()); } private static void patchAvoidReparsingGeneratedCode(ScriptManager sm) { final String PARSER_SIG = "org.eclipse.jdt.internal.compiler.parser.Parser"; sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget(PARSER_SIG, "parse", "void", "org.eclipse.jdt.internal.compiler.ast.MethodDeclaration", "org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration")) .decisionMethod(new Hook("lombok.eclipse.agent.PatchFixes", "checkBit24", "boolean", "java.lang.Object")) .request(StackRequest.PARAM1).build()); sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget(PARSER_SIG, "parse", "void", "org.eclipse.jdt.internal.compiler.ast.ConstructorDeclaration", "org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration", "boolean")) .decisionMethod(new Hook("lombok.eclipse.agent.PatchFixes", "checkBit24", "boolean", "java.lang.Object")) .request(StackRequest.PARAM1).build()); sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget(PARSER_SIG, "parse", "void", "org.eclipse.jdt.internal.compiler.ast.Initializer", "org.eclipse.jdt.internal.compiler.ast.TypeDeclaration", "org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration")) .decisionMethod(new Hook("lombok.eclipse.agent.PatchFixes", "checkBit24", "boolean", "java.lang.Object")) .request(StackRequest.PARAM1).build()); } private static void patchLombokizeAST(ScriptManager sm) { sm.addScript(ScriptBuilder.addField() .targetClass("org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration") .fieldName("$lombokAST").fieldType("Ljava/lang/Object;") .setPublic().setTransient().build()); final String PARSER_SIG = "org.eclipse.jdt.internal.compiler.parser.Parser"; final String CUD_SIG = "org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration"; sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget(PARSER_SIG, "getMethodBodies", "void", CUD_SIG)) .wrapMethod(new Hook("lombok.eclipse.TransformEclipseAST", "transform", "void", PARSER_SIG, CUD_SIG)) .request(StackRequest.THIS, StackRequest.PARAM1).build()); sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget(PARSER_SIG, "endParse", CUD_SIG, "int")) .wrapMethod(new Hook("lombok.eclipse.TransformEclipseAST", "transform_swapped", "void", CUD_SIG, PARSER_SIG)) .request(StackRequest.THIS, StackRequest.RETURN_VALUE).build()); } private static void patchEcjTransformers(ScriptManager sm, boolean ecj) { addPatchesForDelegate(sm, ecj); addPatchesForVal(sm); if (!ecj) addPatchesForValEclipse(sm); } private static void addPatchesForDelegate(ScriptManager sm, boolean ecj) { final String CLASSSCOPE_SIG = "org.eclipse.jdt.internal.compiler.lookup.ClassScope"; sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget(CLASSSCOPE_SIG, "buildFieldsAndMethods", "void")) .request(StackRequest.THIS) .decisionMethod(new Hook(PatchDelegate.class.getName(), "handleDelegateForType", "boolean", CLASSSCOPE_SIG)) .build()); } private static void addPatchesForValEclipse(ScriptManager sm) { final String LOCALDECLARATION_SIG = "org.eclipse.jdt.internal.compiler.ast.LocalDeclaration"; final String PARSER_SIG = "org.eclipse.jdt.internal.compiler.parser.Parser"; final String VARIABLEDECLARATIONSTATEMENT_SIG = "org.eclipse.jdt.core.dom.VariableDeclarationStatement"; final String ASTCONVERTER_SIG = "org.eclipse.jdt.core.dom.ASTConverter"; sm.addScript(ScriptBuilder.addField() .fieldName("$initCopy") .fieldType("Lorg/eclipse/jdt/internal/compiler/ast/ASTNode;") .setPublic() .setTransient() .targetClass("org.eclipse.jdt.internal.compiler.ast.LocalDeclaration") .build()); sm.addScript(ScriptBuilder.addField() .fieldName("$iterableCopy") .fieldType("Lorg/eclipse/jdt/internal/compiler/ast/ASTNode;") .setPublic() .setTransient() .targetClass("org.eclipse.jdt.internal.compiler.ast.LocalDeclaration") .build()); sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget(PARSER_SIG, "consumeExitVariableWithInitialization", "void")) .request(StackRequest.THIS) .wrapMethod(new Hook("lombok.eclipse.agent.PatchValEclipsePortal", "copyInitializationOfLocalDeclaration", "void", "java.lang.Object")) .build()); sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget(PARSER_SIG, "consumeEnhancedForStatementHeader", "void")) .request(StackRequest.THIS) .wrapMethod(new Hook("lombok.eclipse.agent.PatchValEclipsePortal", "copyInitializationOfForEachIterable", "void", "java.lang.Object")) .build()); sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget(ASTCONVERTER_SIG, "setModifiers", "void", VARIABLEDECLARATIONSTATEMENT_SIG, LOCALDECLARATION_SIG)) .wrapMethod(new Hook("lombok.eclipse.agent.PatchValEclipsePortal", "addFinalAndValAnnotationToVariableDeclarationStatement", "void", "java.lang.Object", "java.lang.Object", "java.lang.Object")) .request(StackRequest.THIS, StackRequest.PARAM1, StackRequest.PARAM2).build()); } private static void addPatchesForVal(ScriptManager sm) { final String LOCALDECLARATION_SIG = "org.eclipse.jdt.internal.compiler.ast.LocalDeclaration"; final String FOREACHSTATEMENT_SIG = "org.eclipse.jdt.internal.compiler.ast.ForeachStatement"; final String EXPRESSION_SIG = "org.eclipse.jdt.internal.compiler.ast.Expression"; final String BLOCKSCOPE_SIG = "org.eclipse.jdt.internal.compiler.lookup.BlockScope"; final String TYPEBINDING_SIG = "org.eclipse.jdt.internal.compiler.lookup.TypeBinding"; sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget(LOCALDECLARATION_SIG, "resolve", "void", BLOCKSCOPE_SIG)) .request(StackRequest.THIS, StackRequest.PARAM1) .decisionMethod(new Hook("lombok.eclipse.agent.PatchVal", "handleValForLocalDeclaration", "boolean", LOCALDECLARATION_SIG, BLOCKSCOPE_SIG)) .build()); sm.addScript(ScriptBuilder.replaceMethodCall() .target(new MethodTarget(LOCALDECLARATION_SIG, "resolve", "void", BLOCKSCOPE_SIG)) .methodToReplace(new Hook(EXPRESSION_SIG, "resolveType", TYPEBINDING_SIG, BLOCKSCOPE_SIG)) .requestExtra(StackRequest.THIS) .replacementMethod(new Hook("lombok.eclipse.agent.PatchVal", "skipResolveInitializerIfAlreadyCalled2", TYPEBINDING_SIG, EXPRESSION_SIG, BLOCKSCOPE_SIG, LOCALDECLARATION_SIG)) .build()); sm.addScript(ScriptBuilder.replaceMethodCall() .target(new MethodTarget(FOREACHSTATEMENT_SIG, "resolve", "void", BLOCKSCOPE_SIG)) .methodToReplace(new Hook(EXPRESSION_SIG, "resolveType", TYPEBINDING_SIG, BLOCKSCOPE_SIG)) .replacementMethod(new Hook("lombok.eclipse.agent.PatchVal", "skipResolveInitializerIfAlreadyCalled", TYPEBINDING_SIG, EXPRESSION_SIG, BLOCKSCOPE_SIG)) .build()); sm.addScript(ScriptBuilder.exitEarly() .target(new MethodTarget(FOREACHSTATEMENT_SIG, "resolve", "void", BLOCKSCOPE_SIG)) .request(StackRequest.THIS, StackRequest.PARAM1) .decisionMethod(new Hook("lombok.eclipse.agent.PatchVal", "handleValForForEach", "boolean", FOREACHSTATEMENT_SIG, BLOCKSCOPE_SIG)) .build()); } private static void patchFixSourceTypeConverter(ScriptManager sm) { final String SOURCE_TYPE_CONVERTER_SIG = "org.eclipse.jdt.internal.compiler.parser.SourceTypeConverter"; final String I_ANNOTATABLE_SIG = "org.eclipse.jdt.core.IAnnotatable"; final String ANNOTATION_SIG = "org.eclipse.jdt.internal.compiler.ast.Annotation"; sm.addScript(ScriptBuilder.wrapReturnValue() .target(new MethodTarget(SOURCE_TYPE_CONVERTER_SIG, "convertAnnotations", ANNOTATION_SIG + "[]", I_ANNOTATABLE_SIG)) .wrapMethod(new Hook("lombok.eclipse.agent.PatchFixes", "convertAnnotations", ANNOTATION_SIG + "[]", ANNOTATION_SIG + "[]", I_ANNOTATABLE_SIG)) .request(StackRequest.PARAM1, StackRequest.RETURN_VALUE).build()); } }
-javaagent:lombok.jar=ECJ should now work to enable lombok in any ecj-based tool including ecj itself.
src/eclipseAgent/lombok/eclipse/agent/EclipsePatcher.java
-javaagent:lombok.jar=ECJ should now work to enable lombok in any ecj-based tool including ecj itself.
<ide><path>rc/eclipseAgent/lombok/eclipse/agent/EclipsePatcher.java <ide> patchAvoidReparsingGeneratedCode(sm); <ide> <ide> if (!ecjOnly) { <del> patchLombokizeAST(sm); <ide> patchCatchReparse(sm); <ide> patchIdentifierEndReparse(sm); <ide> patchRetrieveEllipsisStartPosition(sm); <ide> patchPostCompileHookEcj(sm); <ide> } <ide> <add> patchLombokizeAST(sm); <ide> patchEcjTransformers(sm, ecjOnly); <ide> <ide> if (reloadExistingClasses) sm.reloadClasses(instrumentation);
Java
lgpl-2.1
error: pathspec 'bio/webapp/src/org/intermine/bio/web/widget/PrideExperimentURLQuery.java' did not match any file(s) known to git
d37793d82fd941ae457d3269436377f7d8f868e3
1
julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine
package org.intermine.bio.web.widget; /* * Copyright (C) 2002-2008 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.ArrayList; import java.util.List; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.path.Path; import org.intermine.web.logic.bag.InterMineBag; import org.intermine.web.logic.query.Constraint; import org.intermine.web.logic.query.MainHelper; import org.intermine.web.logic.query.OrderBy; import org.intermine.web.logic.query.PathNode; import org.intermine.web.logic.query.PathQuery; import org.intermine.web.logic.widget.WidgetURLQuery; /** * Builds a query to get all the employees (in bag) associated with specified dept. * @author Dominik Grimm and Michael Menden */ public class PrideExperimentURLQuery implements WidgetURLQuery { InterMineBag bag; String key; ObjectStore os; /** * @param key value selected by user to display * @param bag bag included in query * @param os object store */ public PrideExperimentURLQuery(ObjectStore os, InterMineBag bag, String key) { this.bag = bag; this.key = key; this.os = os; } /** * {@inheritDoc} */ public PathQuery generatePathQuery() { Model model = os.getModel(); PathQuery q = new PathQuery(model); List<Path> view = new ArrayList<Path>(); Path pride = MainHelper.makePath(model, q, "Protein.proteinIdentifications.prideExperiment.title"); Path proteinId = MainHelper.makePath(model, q, "Protein.primaryIdentifier"); Path proteinAcc = MainHelper.makePath(model, q, "Protein.primaryAccession"); Path proteinName = MainHelper.makePath(model, q, "Protein.name"); view.add(pride); view.add(proteinId); view.add(proteinAcc); view.add(proteinName); q.setView(view); String bagType = bag.getType(); ConstraintOp constraintOp = ConstraintOp.IN; String constraintValue = bag.getName(); String label = null, id = null, code = q.getUnusedConstraintCode(); Constraint c = new Constraint(constraintOp, constraintValue, false, label, code, id, null); q.addNode(bagType).getConstraints().add(c); // prideExperiment constraintOp = ConstraintOp.EQUALS; code = q.getUnusedConstraintCode(); PathNode expressedNode = q.addNode("Protein.proteinIdentifications.prideExperiment.title"); Constraint expressedConstraint = new Constraint(constraintOp, key, false, label, code, id, null); expressedNode.getConstraints().add(expressedConstraint); q.setConstraintLogic("A and B"); q.syncLogicExpression("and"); List<OrderBy> sortOrder = new ArrayList<OrderBy>(); sortOrder.add(new OrderBy(pride, "asc")); q.setSortOrder(sortOrder); return q; } }
bio/webapp/src/org/intermine/bio/web/widget/PrideExperimentURLQuery.java
added new PrideExperimentURLQuery class Former-commit-id: ee08b4125792099c7b7f67f372fb39c2f0867a74
bio/webapp/src/org/intermine/bio/web/widget/PrideExperimentURLQuery.java
added new PrideExperimentURLQuery class
<ide><path>io/webapp/src/org/intermine/bio/web/widget/PrideExperimentURLQuery.java <add>package org.intermine.bio.web.widget; <add> <add>/* <add> * Copyright (C) 2002-2008 FlyMine <add> * <add> * This code may be freely distributed and modified under the <add> * terms of the GNU Lesser General Public Licence. This should <add> * be distributed with the code. See the LICENSE file for more <add> * information or http://www.gnu.org/copyleft/lesser.html. <add> * <add> */ <add> <add>import java.util.ArrayList; <add>import java.util.List; <add> <add>import org.intermine.metadata.Model; <add>import org.intermine.objectstore.ObjectStore; <add>import org.intermine.objectstore.query.ConstraintOp; <add>import org.intermine.path.Path; <add>import org.intermine.web.logic.bag.InterMineBag; <add>import org.intermine.web.logic.query.Constraint; <add>import org.intermine.web.logic.query.MainHelper; <add>import org.intermine.web.logic.query.OrderBy; <add>import org.intermine.web.logic.query.PathNode; <add>import org.intermine.web.logic.query.PathQuery; <add>import org.intermine.web.logic.widget.WidgetURLQuery; <add> <add>/** <add> * Builds a query to get all the employees (in bag) associated with specified dept. <add> * @author Dominik Grimm and Michael Menden <add> */ <add> <add>public class PrideExperimentURLQuery implements WidgetURLQuery <add>{ <add> InterMineBag bag; <add> String key; <add> ObjectStore os; <add> <add> /** <add> * @param key value selected by user to display <add> * @param bag bag included in query <add> * @param os object store <add> */ <add> public PrideExperimentURLQuery(ObjectStore os, InterMineBag bag, String key) { <add> this.bag = bag; <add> this.key = key; <add> this.os = os; <add> } <add> <add> /** <add> * {@inheritDoc} <add> */ <add> public PathQuery generatePathQuery() { <add> <add> Model model = os.getModel(); <add> PathQuery q = new PathQuery(model); <add> <add> List<Path> view = new ArrayList<Path>(); <add> <add> Path pride = MainHelper.makePath(model, q, <add> "Protein.proteinIdentifications.prideExperiment.title"); <add> Path proteinId = MainHelper.makePath(model, q, "Protein.primaryIdentifier"); <add> Path proteinAcc = MainHelper.makePath(model, q, "Protein.primaryAccession"); <add> Path proteinName = MainHelper.makePath(model, q, "Protein.name"); <add> <add> view.add(pride); <add> view.add(proteinId); <add> view.add(proteinAcc); <add> view.add(proteinName); <add> <add> q.setView(view); <add> <add> String bagType = bag.getType(); <add> ConstraintOp constraintOp = ConstraintOp.IN; <add> String constraintValue = bag.getName(); <add> String label = null, id = null, code = q.getUnusedConstraintCode(); <add> Constraint c = new Constraint(constraintOp, constraintValue, false, label, code, id, null); <add> q.addNode(bagType).getConstraints().add(c); <add> <add> // prideExperiment <add> constraintOp = ConstraintOp.EQUALS; <add> code = q.getUnusedConstraintCode(); <add> PathNode expressedNode = q.addNode("Protein.proteinIdentifications.prideExperiment.title"); <add> Constraint expressedConstraint <add> = new Constraint(constraintOp, key, false, label, code, id, null); <add> expressedNode.getConstraints().add(expressedConstraint); <add> <add> q.setConstraintLogic("A and B"); <add> q.syncLogicExpression("and"); <add> <add> List<OrderBy> sortOrder = new ArrayList<OrderBy>(); <add> sortOrder.add(new OrderBy(pride, "asc")); <add> <add> <add> q.setSortOrder(sortOrder); <add> <add> return q; <add> } <add>}
Java
cc0-1.0
23b71039a9d025e072023ebd1e557ce0d3b28b64
0
GGJG2016/EvilBunnyGod,GGJG2016/EvilBunnyGod,GGJG2016/EvilBunnyGod
package at.ggjg.evg.entities; import at.ggjg.evg.State; import at.ggjg.evg.gestures.Sequence; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.utils.Array; import java.util.Random; import at.ggjg.evg.helpers.Assets; import at.ggjg.evg.helpers.Bounds; import at.ggjg.evg.mechanic.World; /** * Created by christophergalle on 30/01/16. */ public class Cornfield extends GameObject { private static final float SCALING_FACTOR = 1.2f; public TextureRegion tr; public TextureRegion bunniesmakingloooove; public Array<Bunny> bunnies = new Array<Bunny>(); Random r = new Random(); public float cooldown = 0; public Cornfield(Float posX, Float posY) { super(posX, posY); } @Override public void update(World world, float deltaTime) { stateTime+=deltaTime; cooldown-= deltaTime; if(bunnies.size>=2 && stateTime >= r.nextInt(10) + 5) { Bunny haeschjen = new Bunny(this.position.x, this.position.y); haeschjen.init(world); world.bunnies.add(haeschjen); world.entities.add(haeschjen); bunnies.add(haeschjen); for (Bunny bunny: bunnies) { bunny.state = State.IDLE; bunny.stateTime = 0; } cooldown = 25; bunnies.removeRange(0,bunnies.size-1); } } @Override public void init(World world) { tr = Assets.farm; bunniesmakingloooove = Assets.nastyBunnies; acceptedGesture = Sequence.SequenceName.SQUARE; origin.x = dimension.x / 2; origin.y = dimension.y / 2; scale.set(SCALING_FACTOR, SCALING_FACTOR); bounds = new Bounds(position.x, position.y, scale.x, scale.y); } @Override public void render(SpriteBatch batch) { batch.draw(tr, position.x, position.y, scale.x,scale.y); if(bunnies.size>=2) batch.draw(bunniesmakingloooove, position.x, position.y, scale.x,scale.y); } @Override public void onGestureAction() { } public void addBunny(Bunny bunny) { if(bunnies.size > 2 || cooldown>0) return; bunnies.add(bunny); bunny.state = State.SCHNACKSELN; bunny.stateTime = 0; this.stateTime = 0; } }
core/src/at/ggjg/evg/entities/Cornfield.java
package at.ggjg.evg.entities; import at.ggjg.evg.State; import at.ggjg.evg.gestures.Sequence; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.utils.Array; import java.util.Random; import at.ggjg.evg.helpers.Assets; import at.ggjg.evg.helpers.Bounds; import at.ggjg.evg.mechanic.World; /** * Created by christophergalle on 30/01/16. */ public class Cornfield extends GameObject { private static final float SCALING_FACTOR = 1.2f; public TextureRegion tr; public TextureRegion bunniesmakingloooove; public Array<Bunny> bunnies = new Array<Bunny>(); Random r = new Random(); public float cooldown = 0; public Cornfield(Float posX, Float posY) { super(posX, posY); } @Override public void update(World world, float deltaTime) { stateTime+=deltaTime; cooldown-= deltaTime; if(bunnies.size>=2 && stateTime >= r.nextInt(10) + 5) { Bunny haeschjen = new Bunny(this.position.x, this.position.y); haeschjen.init(world); world.bunnies.add(haeschjen); world.entities.add(haeschjen); bunnies.add(haeschjen); for (Bunny bunny: bunnies) { bunny.state = State.IDLE; bunny.stateTime = 0; } cooldown = 25; bunnies.removeRange(0,bunnies.size-1); } } @Override public void init(World world) { tr = Assets.farm; bunniesmakingloooove = Assets.nastyBunnies; acceptedGesture = Sequence.SequenceName.SQUARE; origin.x = dimension.x / 2; origin.y = dimension.y / 2; scale.set(SCALING_FACTOR, SCALING_FACTOR); bounds = new Bounds(position.x, position.y, scale.x, scale.y); } @Override public void render(SpriteBatch batch) { batch.draw(tr, position.x, position.y, scale.x,scale.y); if(bunnies.size>=2) batch.draw(bunniesmakingloooove, position.x, position.y, scale.x,scale.y); } @Override public void onGestureAction() { } public void addBunny(Bunny bunny) { if(bunnies.size > 2 || cooldown>0){ if(bunny.state != State.IDLE) { bunny.state = State.IDLE; bunny.stateTime = 0; } } else{ bunnies.add(bunny); bunny.state = State.SCHNACKSELN; bunny.stateTime = 0; this.stateTime = 0; } } }
Fix Cornfield
core/src/at/ggjg/evg/entities/Cornfield.java
Fix Cornfield
<ide><path>ore/src/at/ggjg/evg/entities/Cornfield.java <ide> } <ide> <ide> public void addBunny(Bunny bunny) { <del> if(bunnies.size > 2 || cooldown>0){ <del> if(bunny.state != State.IDLE) { <del> bunny.state = State.IDLE; <del> bunny.stateTime = 0; <del> } <del> } <del> else{ <add> if(bunnies.size > 2 || cooldown>0) <add> return; <ide> bunnies.add(bunny); <ide> bunny.state = State.SCHNACKSELN; <ide> bunny.stateTime = 0; <ide> this.stateTime = 0; <ide> } <del> } <ide> }
JavaScript
mit
9c782211ccc42bf22d38574f3c01ddcc75f7cdf7
0
jbaicoianu/cyclone-physics-js,jbaicoianu/cyclone-physics-js
elation.require([], function() { elation.extend("physics.processor.base", function(parent) { this.parent = parent; this._tmpvec = new THREE.Vector3(); this._tmpquat = new THREE.Quaternion(); this._tmpmat = new THREE.Matrix4(); this.update = function(objects, t, active) { if (typeof active == 'undefined') active = []; for (var i = 0; i < objects.length; i++) { var obj = objects[i]; obj.updateState(); if (!obj.state.sleeping) { active.push(obj); } if (obj.children.length > 0) { this.update(obj.children, t, active); } } return active; } this.iterate = function(objects, t) { console.log('iterate in base', this.parent); } this.collide = function(t) { if (t == 0) return; // paused, do nothing var collisions = []; var potentials = []; // FIXME - Brute force for now. We should use octrees or BVH here var objects = this.parent.getObjects(); for (var i = 0; i < objects.length-1; i++) { var obj1 = objects[i]; if (obj1.collider) { // && obj1.collider.radius) { for (var j = i+1; j < objects.length; j++) { var obj2 = objects[j]; //if (obj2.collider && obj2.collider.radius && !(obj1.state.sleeping && obj2.state.sleeping) && obj1.isPotentiallyColliding(obj2)) { if (obj2.collider && !(obj1.state.sleeping && obj2.state.sleeping)) { potentials.push([obj1, obj2]); } } } } if (potentials.length > 0) { for (var i = 0; i < potentials.length; i++) { var obj1 = potentials[i][0], obj2 = potentials[i][1]; // Get list of all contact points between the two objects var contacts = obj1.getContacts(obj2, collisions, t); /* if (contacts && contacts.length > 0) { // Resolve the deepest contact first var deepest = this.getDeepestContact(contacts); collisions.push(deepest); } */ } //console.log(potentials.length + ' potential crashes:', potentials, collisions); } return collisions; } this.getDeepestContact = function(contacts) { var deepest = 0; for (var i = 0; i < contacts.length; i++) { if (contacts[i].penetration < contacts[deepest].penetration) { deepest = i; } } return contacts[deepest]; } this.resolve = function(t, contacts) { if (contacts.length == 0) { return; } if (true) { var linearChange = [ new THREE.Vector3(), new THREE.Vector3() ]; var angularChange = [ new THREE.Vector3(), new THREE.Vector3() ]; for (var i = 0; i < contacts.length; i++) { contacts[i].resolve(t, linearChange, angularChange); } } else { this.prepareContacts(contacts, t); this.adjustPositions(contacts, t); this.adjustVelocities(contacts, t); } } this.prepareContacts = function(contacts, t) { for (var i = 0; i < contacts.length; i++) { var contact = contacts[i]; contact.calculateInternals(t); // Fire physics_collide event for each body involved // FIXME - should only fire once per object-pair var events = elation.events.fire({type: 'physics_collide', element: contact.bodies[0], data: contact}); events.concat(elation.events.fire({type: 'physics_collide', element: contact.bodies[1], data: contact})); } } this.adjustPositions = function(contacts, t) { // TODO - class-wide settings var positionIterations = 100; var positionEpsilon = 1e-2; // closure scratch variables var deltaPosition = new THREE.Vector3(); var linearChange = [ new THREE.Vector3(), new THREE.Vector3() ]; var angularChange = [ new THREE.Vector3(), new THREE.Vector3() ]; var iteration = 0, numcontacts = contacts.length, max; while (iteration < positionIterations) { max = positionEpsilon; var idx = numcontacts; for (var i = 0; i < numcontacts; i++) { if (contacts[i].penetration > max) { max = contacts[i].penetration; idx = i; } } if (idx == numcontacts) break; var lastcontact = contacts[idx]; lastcontact.applyPositionChange(linearChange, angularChange, max); console.log('apply change', lastcontact); // Updating position might have changed penetration of other bodies, so update them for (var i = 0; i < numcontacts; i++) { var contact = contacts[i]; // check each body in contact for (var b = 0; b < 2; b++) { if (!contact.bodies[b]) continue; // match against each body in the newly resolved contact for (var d = 0; d < 2; d++) { if (contact.bodies[b] == lastcontact.bodies[d]) { deltaPosition.crossVectors(angularChange[d], contact.relativePositions[b]).add(linearChange[d]); contact.penetration += deltaPosition.dot(contact.normal) * (b ? 1 : -1); console.log('update penetration', contact); } } } } iteration++; } } this.adjustVelocities = function(contacts, t) { /* // FIXME - split this out correctly! for (var i = 0; i < contacts.length; i++) { var contact = contacts[i]; // Check to see if preventDefault was called in any event handlers var process = true; for (var j = 0; j < events.length; j++) { process = process && events[j].returnValue; } // If not already handled, fall back on default physically-simulated bounce handling if (process) { contact.applyVelocityChange(t); elation.events.fire({type: 'physics_collision_resolved', element: contact.bodies[0], data: contact}); elation.events.fire({type: 'physics_collision_resolved', element: contact.bodies[1], data: contact}); } } */ // TODO - class-wide settings var velocityIterations = 100; var velocityEpsilon = 1e-2; // closure scratch variables var deltaVel = new THREE.Vector3(); var velocityChange = [ new THREE.Vector3(), new THREE.Vector3() ]; var rotationChange = [ new THREE.Vector3(), new THREE.Vector3() ]; var iteration = 0, numcontacts = contacts.length, max; while (iteration < velocityIterations) { max = velocityEpsilon; var idx = numcontacts; for (var i = 0; i < numcontacts; i++) { // Find the fastest-moving contact if (contacts[i].desiredDeltaVelocity > max) { max = contacts[i].desiredDeltaVelocity; idx = i; } } console.log('iter', max, idx); if (idx == numcontacts) break; // Resolve velocity for this contact contacts[idx].applyVelocityChange(velocityChange, rotationChange); // Recompute closing velocities for other contacts which may have changed for (var i = 0; i < numcontacts; i++) { for (var b = 0; b < 2; b++) { if (!contacts[i].bodies[b]) continue; for (var d = 0; d < 2; d++) { if (contacts[i].bodies[b] == contacts[idx].bodies[d]) { deltaVel.crossVectors(rotationChange[d], contacts[i].relativePositions[b]).add(velocityChange[d]).applyMatrix4(contacts[i].contactToWorld); console.log('update velocity', contacts[i], deltaVel.toArray()); if (b == 1) deltaVel.multiplyScalar(-1); contacts[i].velocity.add(deltaVel); contacts[i].calculateDesiredDeltaVelocity(t); } } } } iteration++; } } }); elation.extend("physics.processor.cpu", function(parent) { elation.physics.processor.base.call(this, parent); this.iterate = function(objects, t) { if (t == 0) return; // paused, do nothing var framedata = {}; for (var i = 0; i < objects.length; i++) { objects[i].updateAcceleration(framedata); var scaledtime = objects[i].getTimescale() * t; if (objects[i].state.accelerating || objects[i].state.moving) { this.iterateAxis(objects[i], 'x', scaledtime); this.iterateAxis(objects[i], 'y', scaledtime); this.iterateAxis(objects[i], 'z', scaledtime); } if (objects[i].state.rotating) { this.iterateRotation(objects[i], scaledtime); } objects[i].updateState(framedata); if (!objects[i].state.sleeping) { elation.events.fire({type: "physics_update", element: objects[i], data: t}); } } } this.iterateAxis = function(obj, axis, t) { var pos = obj.position[axis], vel = obj.velocity[axis], accel = obj.acceleration[axis]; vel += accel * t; pos += vel * t; obj.position[axis] = pos; obj.velocity[axis] = vel * Math.pow(obj.linearDamping, t); } this.iterateRotation = function(obj, t) { this._tmpvec.copy(obj.angularacceleration).multiplyScalar(t); obj.angular.add(this._tmpvec).multiplyScalar(Math.pow(obj.angularDamping, t)); this._tmpvec.copy(obj.angular); var theta = this._tmpvec.length(); this._tmpvec.divideScalar(theta); this._tmpquat.setFromAxisAngle(this._tmpvec, theta*t); obj.orientation.multiply(this._tmpquat); } }, false, elation.physics.processor.base); elation.extend("physics.processor.worker", function(parent) { elation.physics.processor.base.call(this, parent); this.worker = new WebWorker('cyclone-worker.js'); this.iterate = function(objects, t) { if (t == 0) return; // paused, do nothing for (var i = 0; i < objects.length; i++) { objects[i].updateAcceleration(); if (objects[i].state.accelerating || objects[i].state.moving) { this.iterateAxis(objects[i], 'x', t); this.iterateAxis(objects[i], 'y', t); this.iterateAxis(objects[i], 'z', t); } if (objects[i].state.rotating) { this.iterateRotation(objects[i], t); } objects[i].updateState(); if (!objects[i].state.sleeping) { elation.events.fire({type: "physics_update", element: objects[i], data: t}); } } } this.iterateAxis = function(obj, axis, t) { this._tmpvec.set(obj.position[axis], obj.velocity[axis], obj.acceleration[axis]); this._tmpvec.applyMatrix4(this.parent.physicsmatrix); obj.position[axis] = this._tmpvec.x; obj.velocity[axis] = this._tmpvec.y * Math.pow(obj.linearDamping, t); } this.iterateRotation = function(obj, t) { this._tmpvec.copy(obj.angularacceleration).multiplyScalar(t); obj.angular.add(this._tmpvec).multiplyScalar(Math.pow(obj.angularDamping, t)); this._tmpvec.copy(obj.angular); var theta = this._tmpvec.length(); this._tmpvec.divideScalar(theta); this._tmpquat.setFromAxisAngle(this._tmpvec, theta*t); obj.orientation.multiply(this._tmpquat); } }, false, elation.physics.processor.base); elation.extend("physics.processor.gpu", function(parent) { elation.physics.processor.base.call(this, parent); // TODO: // - pack linear+angular pos/vel/accel into texture (OES_texture_float?) // - glsl shader multiplies each point by the update matrix, results returned as image // - glReadPixels to read back result, map updates back to objects this.iterate = function(objects, t) { console.log('iterate in gpu not implemented yet', this.parent, objects); } }, false, elation.physics.processor.base); });
scripts/processors.js
elation.require([], function() { elation.extend("physics.processor.base", function(parent) { this.parent = parent; this._tmpvec = new THREE.Vector3(); this._tmpquat = new THREE.Quaternion(); this._tmpmat = new THREE.Matrix4(); this.update = function(objects, t, active) { if (typeof active == 'undefined') active = []; for (var i = 0; i < objects.length; i++) { var obj = objects[i]; obj.updateState(); if (!obj.state.sleeping) { active.push(obj); } if (obj.children.length > 0) { this.update(obj.children, t, active); } } return active; } this.iterate = function(objects, t) { console.log('iterate in base', this.parent); } this.collide = function(t) { if (t == 0) return; // paused, do nothing var collisions = []; var potentials = []; // FIXME - Brute force for now. We should use octrees or BVH here var objects = this.parent.getObjects(); for (var i = 0; i < objects.length-1; i++) { var obj1 = objects[i]; if (obj1.collider) { // && obj1.collider.radius) { for (var j = i+1; j < objects.length; j++) { var obj2 = objects[j]; //if (obj2.collider && obj2.collider.radius && !(obj1.state.sleeping && obj2.state.sleeping) && obj1.isPotentiallyColliding(obj2)) { if (obj2.collider && !(obj1.state.sleeping && obj2.state.sleeping)) { potentials.push([obj1, obj2]); } } } } if (potentials.length > 0) { for (var i = 0; i < potentials.length; i++) { var obj1 = potentials[i][0], obj2 = potentials[i][1]; // Get list of all contact points between the two objects var contacts = obj1.getContacts(obj2, collisions); /* if (contacts && contacts.length > 0) { // Resolve the deepest contact first var deepest = this.getDeepestContact(contacts); collisions.push(deepest); } */ } //console.log(potentials.length + ' potential crashes:', potentials, collisions); } return collisions; } this.getDeepestContact = function(contacts) { var deepest = 0; for (var i = 0; i < contacts.length; i++) { if (contacts[i].penetration < contacts[deepest].penetration) { deepest = i; } } return contacts[deepest]; } this.resolve = function(t, contacts) { if (contacts.length == 0) { return; } if (true) { var linearChange = [ new THREE.Vector3(), new THREE.Vector3() ]; var angularChange = [ new THREE.Vector3(), new THREE.Vector3() ]; for (var i = 0; i < contacts.length; i++) { contacts[i].resolve(t, linearChange, angularChange); } } else { this.prepareContacts(contacts, t); this.adjustPositions(contacts, t); this.adjustVelocities(contacts, t); } } this.prepareContacts = function(contacts, t) { for (var i = 0; i < contacts.length; i++) { var contact = contacts[i]; contact.calculateInternals(t); // Fire physics_collide event for each body involved // FIXME - should only fire once per object-pair var events = elation.events.fire({type: 'physics_collide', element: contact.bodies[0], data: contact}); events.concat(elation.events.fire({type: 'physics_collide', element: contact.bodies[1], data: contact})); } } this.adjustPositions = function(contacts, t) { // TODO - class-wide settings var positionIterations = 100; var positionEpsilon = 1e-2; // closure scratch variables var deltaPosition = new THREE.Vector3(); var linearChange = [ new THREE.Vector3(), new THREE.Vector3() ]; var angularChange = [ new THREE.Vector3(), new THREE.Vector3() ]; var iteration = 0, numcontacts = contacts.length, max; while (iteration < positionIterations) { max = positionEpsilon; var idx = numcontacts; for (var i = 0; i < numcontacts; i++) { if (contacts[i].penetration > max) { max = contacts[i].penetration; idx = i; } } if (idx == numcontacts) break; var lastcontact = contacts[idx]; lastcontact.applyPositionChange(linearChange, angularChange, max); console.log('apply change', lastcontact); // Updating position might have changed penetration of other bodies, so update them for (var i = 0; i < numcontacts; i++) { var contact = contacts[i]; // check each body in contact for (var b = 0; b < 2; b++) { if (!contact.bodies[b]) continue; // match against each body in the newly resolved contact for (var d = 0; d < 2; d++) { if (contact.bodies[b] == lastcontact.bodies[d]) { deltaPosition.crossVectors(angularChange[d], contact.relativePositions[b]).add(linearChange[d]); contact.penetration += deltaPosition.dot(contact.normal) * (b ? 1 : -1); console.log('update penetration', contact); } } } } iteration++; } } this.adjustVelocities = function(contacts, t) { /* // FIXME - split this out correctly! for (var i = 0; i < contacts.length; i++) { var contact = contacts[i]; // Check to see if preventDefault was called in any event handlers var process = true; for (var j = 0; j < events.length; j++) { process = process && events[j].returnValue; } // If not already handled, fall back on default physically-simulated bounce handling if (process) { contact.applyVelocityChange(t); elation.events.fire({type: 'physics_collision_resolved', element: contact.bodies[0], data: contact}); elation.events.fire({type: 'physics_collision_resolved', element: contact.bodies[1], data: contact}); } } */ // TODO - class-wide settings var velocityIterations = 100; var velocityEpsilon = 1e-2; // closure scratch variables var deltaVel = new THREE.Vector3(); var velocityChange = [ new THREE.Vector3(), new THREE.Vector3() ]; var rotationChange = [ new THREE.Vector3(), new THREE.Vector3() ]; var iteration = 0, numcontacts = contacts.length, max; while (iteration < velocityIterations) { max = velocityEpsilon; var idx = numcontacts; for (var i = 0; i < numcontacts; i++) { // Find the fastest-moving contact if (contacts[i].desiredDeltaVelocity > max) { max = contacts[i].desiredDeltaVelocity; idx = i; } } console.log('iter', max, idx); if (idx == numcontacts) break; // Resolve velocity for this contact contacts[idx].applyVelocityChange(velocityChange, rotationChange); // Recompute closing velocities for other contacts which may have changed for (var i = 0; i < numcontacts; i++) { for (var b = 0; b < 2; b++) { if (!contacts[i].bodies[b]) continue; for (var d = 0; d < 2; d++) { if (contacts[i].bodies[b] == contacts[idx].bodies[d]) { deltaVel.crossVectors(rotationChange[d], contacts[i].relativePositions[b]).add(velocityChange[d]).applyMatrix4(contacts[i].contactToWorld); console.log('update velocity', contacts[i], deltaVel.toArray()); if (b == 1) deltaVel.multiplyScalar(-1); contacts[i].velocity.add(deltaVel); contacts[i].calculateDesiredDeltaVelocity(t); } } } } iteration++; } } }); elation.extend("physics.processor.cpu", function(parent) { elation.physics.processor.base.call(this, parent); this.iterate = function(objects, t) { if (t == 0) return; // paused, do nothing var framedata = {}; for (var i = 0; i < objects.length; i++) { objects[i].updateAcceleration(framedata); var scaledtime = objects[i].getTimescale() * t; if (objects[i].state.accelerating || objects[i].state.moving) { this.iterateAxis(objects[i], 'x', scaledtime); this.iterateAxis(objects[i], 'y', scaledtime); this.iterateAxis(objects[i], 'z', scaledtime); } if (objects[i].state.rotating) { this.iterateRotation(objects[i], scaledtime); } objects[i].updateState(framedata); if (!objects[i].state.sleeping) { elation.events.fire({type: "physics_update", element: objects[i], data: t}); } } } this.iterateAxis = function(obj, axis, t) { var pos = obj.position[axis], vel = obj.velocity[axis], accel = obj.acceleration[axis]; vel += accel * t; pos += vel * t; obj.position[axis] = pos; obj.velocity[axis] = vel * Math.pow(obj.linearDamping, t); } this.iterateRotation = function(obj, t) { this._tmpvec.copy(obj.angularacceleration).multiplyScalar(t); obj.angular.add(this._tmpvec).multiplyScalar(Math.pow(obj.angularDamping, t)); this._tmpvec.copy(obj.angular); var theta = this._tmpvec.length(); this._tmpvec.divideScalar(theta); this._tmpquat.setFromAxisAngle(this._tmpvec, theta*t); obj.orientation.multiply(this._tmpquat); } }, false, elation.physics.processor.base); elation.extend("physics.processor.worker", function(parent) { elation.physics.processor.base.call(this, parent); this.worker = new WebWorker('cyclone-worker.js'); this.iterate = function(objects, t) { if (t == 0) return; // paused, do nothing for (var i = 0; i < objects.length; i++) { objects[i].updateAcceleration(); if (objects[i].state.accelerating || objects[i].state.moving) { this.iterateAxis(objects[i], 'x', t); this.iterateAxis(objects[i], 'y', t); this.iterateAxis(objects[i], 'z', t); } if (objects[i].state.rotating) { this.iterateRotation(objects[i], t); } objects[i].updateState(); if (!objects[i].state.sleeping) { elation.events.fire({type: "physics_update", element: objects[i], data: t}); } } } this.iterateAxis = function(obj, axis, t) { this._tmpvec.set(obj.position[axis], obj.velocity[axis], obj.acceleration[axis]); this._tmpvec.applyMatrix4(this.parent.physicsmatrix); obj.position[axis] = this._tmpvec.x; obj.velocity[axis] = this._tmpvec.y * Math.pow(obj.linearDamping, t); } this.iterateRotation = function(obj, t) { this._tmpvec.copy(obj.angularacceleration).multiplyScalar(t); obj.angular.add(this._tmpvec).multiplyScalar(Math.pow(obj.angularDamping, t)); this._tmpvec.copy(obj.angular); var theta = this._tmpvec.length(); this._tmpvec.divideScalar(theta); this._tmpquat.setFromAxisAngle(this._tmpvec, theta*t); obj.orientation.multiply(this._tmpquat); } }, false, elation.physics.processor.base); elation.extend("physics.processor.gpu", function(parent) { elation.physics.processor.base.call(this, parent); // TODO: // - pack linear+angular pos/vel/accel into texture (OES_texture_float?) // - glsl shader multiplies each point by the update matrix, results returned as image // - glReadPixels to read back result, map updates back to objects this.iterate = function(objects, t) { console.log('iterate in gpu not implemented yet', this.parent, objects); } }, false, elation.physics.processor.base); });
Pass timestep to collision contact processor
scripts/processors.js
Pass timestep to collision contact processor
<ide><path>cripts/processors.js <ide> for (var i = 0; i < potentials.length; i++) { <ide> var obj1 = potentials[i][0], obj2 = potentials[i][1]; <ide> // Get list of all contact points between the two objects <del> var contacts = obj1.getContacts(obj2, collisions); <add> var contacts = obj1.getContacts(obj2, collisions, t); <ide> /* <ide> if (contacts && contacts.length > 0) { <ide> // Resolve the deepest contact first
Java
lgpl-2.1
3440f8cdb2ee075e051da389affa4267177489f7
0
elsiklab/intermine,zebrafishmine/intermine,joshkh/intermine,kimrutherford/intermine,elsiklab/intermine,elsiklab/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,joshkh/intermine,kimrutherford/intermine,joshkh/intermine,joshkh/intermine,drhee/toxoMine,zebrafishmine/intermine,tomck/intermine,tomck/intermine,kimrutherford/intermine,kimrutherford/intermine,elsiklab/intermine,drhee/toxoMine,drhee/toxoMine,joshkh/intermine,tomck/intermine,kimrutherford/intermine,elsiklab/intermine,JoeCarlson/intermine,zebrafishmine/intermine,tomck/intermine,elsiklab/intermine,zebrafishmine/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,joshkh/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,JoeCarlson/intermine,kimrutherford/intermine,drhee/toxoMine,tomck/intermine,drhee/toxoMine,zebrafishmine/intermine,elsiklab/intermine,justincc/intermine,tomck/intermine,drhee/toxoMine,justincc/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,JoeCarlson/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,zebrafishmine/intermine,tomck/intermine,justincc/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,justincc/intermine,JoeCarlson/intermine,tomck/intermine,justincc/intermine,elsiklab/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,justincc/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,justincc/intermine,zebrafishmine/intermine,drhee/toxoMine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,JoeCarlson/intermine,drhee/toxoMine,elsiklab/intermine
package org.intermine.webservice.server.template.result; /* * Copyright (C) 2002-2011 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import junit.framework.TestCase; import org.apache.log4j.Logger; import org.intermine.TestUtil; import org.intermine.api.template.TemplateQuery; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.pathquery.PathConstraint; import org.intermine.pathquery.PathConstraintAttribute; import org.intermine.pathquery.PathConstraintLookup; import org.intermine.pathquery.PathQuery; import org.intermine.webservice.server.WebServiceConstants; /** * @author Jakub Kulaviak, dbutano **/ public class TemplateResultLinkGeneratorTest extends TestCase { private String prefix = "http://localhost:8080/query/" + WebServiceConstants.MODULE_NAME; private static final Logger LOG = Logger.getLogger(TemplateResultLinkGeneratorTest.class); public void testExtraValueLink() { PathQuery ret = new PathQuery(TestUtil.getModel()); PathConstraint c1 = new PathConstraintLookup("Gene.name", "zen", "Drosophila_melanogaster"); TemplateQuery tmpl = new TemplateQuery("template1", "title", "comments", ret); tmpl.addConstraint(c1); tmpl.setEditable(c1, true); String link = new TemplateResultLinkGenerator().getHtmlLink("http://localhost:8080/query", tmpl); String expected = prefix + "/template/results?name=template1&constraint1=Gene.name&op1=LOOKUP&value1=zen&" + "extra1=Drosophila_melanogaster&format=tab&size=" + TemplateResultLinkGenerator.DEFAULT_RESULT_SIZE + "&layout=minelink|paging"; assertEquals(expected, link); } public void testMultipleConstraintsLink() { PathQuery ret = new PathQuery(TestUtil.getModel()); PathConstraint c1 = new PathConstraintAttribute("Gene.name", ConstraintOp.MATCHES, "zen"); PathConstraint c2 = new PathConstraintAttribute("Gene.length", ConstraintOp.LESS_THAN, "100"); TemplateQuery tmpl = new TemplateQuery("template1", "title", "comments", ret); tmpl.addConstraint(c1); tmpl.setEditable(c1, true); tmpl.addConstraint(c2); tmpl.setEditable(c2, true); String link = new TemplateResultLinkGenerator() .getHtmlLink("http://localhost:8080/query", tmpl); String expected = prefix + "/template/results?name=template1" + "&constraint1=Gene.name&op1=LIKE&value1=zen" + "&constraint2=Gene.length&op2=lt&value2=100" + "&format=tab&size=" + TemplateResultLinkGenerator.DEFAULT_RESULT_SIZE + "&layout=minelink|paging"; assertEquals(expected, link); } }
intermine/web/test/src/org/intermine/webservice/server/template/result/TemplateResultLinkGeneratorTest.java
package org.intermine.webservice.server.template.result; /* * Copyright (C) 2002-2011 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import junit.framework.TestCase; import org.apache.log4j.Logger; import org.intermine.TestUtil; import org.intermine.api.template.TemplateQuery; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.pathquery.PathConstraint; import org.intermine.pathquery.PathConstraintAttribute; import org.intermine.pathquery.PathConstraintLookup; import org.intermine.pathquery.PathQuery; import org.intermine.webservice.server.WebServiceConstants; /** * @author Jakub Kulaviak, dbutano **/ public class TemplateResultLinkGeneratorTest extends TestCase { private String prefix = "http://localhost:8080/query/" + WebServiceConstants.MODULE_NAME; private static final Logger LOG = Logger.getLogger(TemplateResultLinkGeneratorTest.class); public void testExtraValueLink() { PathQuery ret = new PathQuery(TestUtil.getModel()); PathConstraint c1 = new PathConstraintLookup("Gene.name", "zen", "Drosophila_melanogaster"); TemplateQuery tmpl = new TemplateQuery("template1", "title", "comments", ret); tmpl.addConstraint(c1); tmpl.setEditable(c1, true); String link = new TemplateResultLinkGenerator().getHtmlLink("http://localhost:8080/query", tmpl); String expected = prefix + "/template/results?name=template1&constraint1=Gene.name&op1=LOOKUP&value1=zen&" + "extra1=Drosophila_melanogaster&format=tab&size=" + TemplateResultLinkGenerator.DEFAULT_RESULT_SIZE + "&layout=minelink|paging"; LOG.error("testExtraValueLink().expected:" + expected); LOG.error("testExtraValueLink().actual:" + link); assertEquals(expected, link); } public void testMultipleConstraintsLink() { PathQuery ret = new PathQuery(TestUtil.getModel()); PathConstraint c1 = new PathConstraintAttribute("Gene.name", ConstraintOp.MATCHES, "zen"); PathConstraint c2 = new PathConstraintAttribute("Gene.length", ConstraintOp.LESS_THAN, "100"); TemplateQuery tmpl = new TemplateQuery("template1", "title", "comments", ret); tmpl.addConstraint(c1); tmpl.setEditable(c1, true); tmpl.addConstraint(c2); tmpl.setEditable(c2, true); String link = new TemplateResultLinkGenerator() .getHtmlLink("http://localhost:8080/query", tmpl); String expected = prefix + "/template/results?name=template1" + "&constraint1=Gene.name&op1=LIKE&value1=zen" + "&constraint2=Gene.length&op2=lt&value2=100" + "&format=tab&size=" + TemplateResultLinkGenerator.DEFAULT_RESULT_SIZE + "&layout=minelink|paging"; LOG.error("testMultipleConstraintsLink().expected:" + expected); LOG.error("testMultipleConstraintsLink().actual:" + link); assertEquals(expected, link); } }
remove debug output
intermine/web/test/src/org/intermine/webservice/server/template/result/TemplateResultLinkGeneratorTest.java
remove debug output
<ide><path>ntermine/web/test/src/org/intermine/webservice/server/template/result/TemplateResultLinkGeneratorTest.java <ide> String expected = prefix + "/template/results?name=template1&constraint1=Gene.name&op1=LOOKUP&value1=zen&" <ide> + "extra1=Drosophila_melanogaster&format=tab&size=" + TemplateResultLinkGenerator.DEFAULT_RESULT_SIZE + "&layout=minelink|paging"; <ide> <del> LOG.error("testExtraValueLink().expected:" + expected); <del> LOG.error("testExtraValueLink().actual:" + link); <del> <ide> assertEquals(expected, link); <ide> } <ide> <ide> + "&format=tab&size=" + TemplateResultLinkGenerator.DEFAULT_RESULT_SIZE <ide> + "&layout=minelink|paging"; <ide> <del> LOG.error("testMultipleConstraintsLink().expected:" + expected); <del> LOG.error("testMultipleConstraintsLink().actual:" + link); <del> <ide> assertEquals(expected, link); <ide> } <ide>
Java
bsd-3-clause
0d15bf0b7a654370f53a8ae1314f871ed4986a5b
0
ctrimble/JavaCL,ctrimble/JavaCL,n0mer/JavaCL,n0mer/JavaCL,n0mer/JavaCL,ctrimble/JavaCL
/* Copyright (c) 2009 Olivier Chafik, All Rights Reserved This file is part of JNAerator (http://jnaerator.googlecode.com/). JNAerator is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JNAerator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with JNAerator. If not, see <http://www.gnu.org/licenses/>. */ package com.ochafik.lang.jnaerator; import static com.ochafik.lang.SyntaxUtils.as; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.classLiteral; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.expr; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.ident; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.memberRef; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.thisRef; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.cast; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.methodCall; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.staticField; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.thisField; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.typeRef; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.varRef; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import java.nio.ShortBuffer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.TreeMap; import java.util.regex.Pattern; import org.rococoa.ObjCClass; import org.rococoa.ObjCObject; import org.rococoa.cocoa.foundation.NSObject; import org.bridj.FlagSet; import org.bridj.ValuedEnum; import org.bridj.SizeT; import org.bridj.ann.CLong; import org.bridj.ann.Ptr; import org.bridj.util.DefaultParameterizedType; import com.ochafik.lang.SyntaxUtils; import com.ochafik.lang.jnaerator.JNAeratorConfig.GenFeatures; import com.ochafik.lang.jnaerator.parser.Annotation; import com.ochafik.lang.jnaerator.parser.Arg; import com.ochafik.lang.jnaerator.parser.Declaration; import com.ochafik.lang.jnaerator.parser.Declarator; import com.ochafik.lang.jnaerator.parser.Define; import com.ochafik.lang.jnaerator.parser.Element; import com.ochafik.lang.jnaerator.parser.Enum; import com.ochafik.lang.jnaerator.parser.Expression; import com.ochafik.lang.jnaerator.parser.Function; import com.ochafik.lang.jnaerator.parser.Identifier; import com.ochafik.lang.jnaerator.parser.ModifiableElement; import com.ochafik.lang.jnaerator.parser.Modifier; import com.ochafik.lang.jnaerator.parser.ModifierType; import com.ochafik.lang.jnaerator.parser.ObjCppParser; import com.ochafik.lang.jnaerator.parser.Scanner; import com.ochafik.lang.jnaerator.parser.Struct; import com.ochafik.lang.jnaerator.parser.TypeRef; import com.ochafik.lang.jnaerator.parser.VariablesDeclaration; import com.ochafik.lang.jnaerator.parser.Declarator.ArrayDeclarator; import com.ochafik.lang.jnaerator.parser.Enum.EnumItem; import com.ochafik.lang.jnaerator.parser.Expression.AssignmentOp; import com.ochafik.lang.jnaerator.parser.Expression.AssignmentOperator; import com.ochafik.lang.jnaerator.parser.Expression.BinaryOp; import com.ochafik.lang.jnaerator.parser.Expression.BinaryOperator; import com.ochafik.lang.jnaerator.parser.Expression.Cast; import com.ochafik.lang.jnaerator.parser.Expression.Constant; import com.ochafik.lang.jnaerator.parser.Expression.EmptyArraySize; import com.ochafik.lang.jnaerator.parser.Expression.FunctionCall; import com.ochafik.lang.jnaerator.parser.Expression.MemberRef; import com.ochafik.lang.jnaerator.parser.Expression.MemberRefStyle; import com.ochafik.lang.jnaerator.parser.Expression.New; import com.ochafik.lang.jnaerator.parser.Expression.TypeRefExpression; import com.ochafik.lang.jnaerator.parser.Expression.UnaryOp; import com.ochafik.lang.jnaerator.parser.Expression.UnaryOperator; import com.ochafik.lang.jnaerator.parser.Expression.VariableRef; import com.ochafik.lang.jnaerator.parser.Identifier.QualifiedIdentifier; import com.ochafik.lang.jnaerator.parser.Identifier.SimpleIdentifier; import com.ochafik.lang.jnaerator.parser.StoredDeclarations.TypeDef; import com.ochafik.lang.jnaerator.parser.TypeRef.ArrayRef; import com.ochafik.lang.jnaerator.parser.TypeRef.FunctionSignature; import com.ochafik.lang.jnaerator.parser.TypeRef.Pointer; import com.ochafik.lang.jnaerator.parser.TypeRef.Primitive; import com.ochafik.lang.jnaerator.parser.TypeRef.SimpleTypeRef; import com.ochafik.lang.jnaerator.parser.TypeRef.TaggedTypeRef; import com.ochafik.lang.jnaerator.parser.TypeRef.TargettedTypeRef; import com.ochafik.lang.jnaerator.runtime.CGFloatByReference; import com.ochafik.lang.jnaerator.runtime.CharByReference; import com.ochafik.lang.jnaerator.runtime.NativeSize; import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; import com.ochafik.lang.jnaerator.runtime.globals.Global; import com.ochafik.lang.jnaerator.runtime.globals.GlobalByte; import com.ochafik.lang.jnaerator.runtime.globals.GlobalCGFloat; import com.ochafik.lang.jnaerator.runtime.globals.GlobalChar; import com.ochafik.lang.jnaerator.runtime.globals.GlobalDouble; import com.ochafik.lang.jnaerator.runtime.globals.GlobalFloat; import com.ochafik.lang.jnaerator.runtime.globals.GlobalInt; import com.ochafik.lang.jnaerator.runtime.globals.GlobalLong; import com.ochafik.lang.jnaerator.runtime.globals.GlobalNativeLong; import com.ochafik.lang.jnaerator.runtime.globals.GlobalNativeSize; import com.ochafik.lang.jnaerator.runtime.globals.GlobalShort; import com.ochafik.util.listenable.Pair; import com.ochafik.util.string.StringUtils; import com.sun.jna.Native; import com.sun.jna.WString; import com.sun.jna.ptr.ByReference; import com.sun.jna.ptr.ByteByReference; import com.sun.jna.ptr.DoubleByReference; import com.sun.jna.ptr.FloatByReference; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.LongByReference; import com.sun.jna.ptr.NativeLongByReference; import com.sun.jna.ptr.PointerByReference; import com.sun.jna.ptr.ShortByReference; public class TypeConversion implements ObjCppParser.ObjCParserHelper { Result result; public boolean allowUnknownPointers = true, allowFakePointers = false; public TypeConversion(Result result) { super(); this.result = result; initTypes(); } //public Set<Identifier> fakePointersSink; public enum TypeConversionMode { PrimitiveOrBufferParameter, NativeParameter, NativeParameterWithStructsPtrPtrs, FieldType, ReturnType, ExpressionType, StaticallySizedArrayField, PrimitiveReturnType, PointedValue } public Map<JavaPrim, Class<? extends ByReference>> primToByReference = new HashMap<JavaPrim, Class<? extends ByReference>>(); public Map<JavaPrim, Class<? extends Global>> primToGlobal = new HashMap<JavaPrim, Class<? extends Global>>(); public Map<JavaPrim, Class<? extends Buffer>> primToBuffer = new HashMap<JavaPrim, Class<? extends Buffer>>(); public final Set<String> byReferenceClassesNames = new HashSet<String>(); Map<String, JavaPrim> javaPrims = new TreeMap<String, JavaPrim>(); protected void prim(String from, JavaPrim to) { javaPrims.put(from, to); } public boolean isObjCppPrimitive(String s) { return javaPrims.containsKey(s); } public enum JavaPrim { Void(null, null, ESize.Zero), Char(Character.TYPE, Character.class, ESize.CharSize), Long(java.lang.Long.TYPE, java.lang.Long.class, ESize.Eight), Int(Integer.TYPE, Integer.class, ESize.Four), Short(java.lang.Short.TYPE, java.lang.Short.class, ESize.Two), Byte(java.lang.Byte.TYPE, java.lang.Byte.class, ESize.One), Boolean(java.lang.Boolean.TYPE, java.lang.Boolean.class, ESize.One), Float(java.lang.Float.TYPE, java.lang.Float.class, ESize.Four), Double(java.lang.Double.TYPE, java.lang.Double.class, ESize.Eight), NativeLong(com.sun.jna.NativeLong.class, com.sun.jna.NativeLong.class, ESize.StaticSizeField), NativeSize(NativeSize.class, NativeSize.class, ESize.StaticSizeField), NSInteger(org.rococoa.cocoa.foundation.NSInteger.class, org.rococoa.cocoa.foundation.NSInteger.class, ESize.StaticSizeField), NSUInteger(org.rococoa.cocoa.foundation.NSUInteger.class, org.rococoa.cocoa.foundation.NSUInteger.class, ESize.StaticSizeField), CGFloat(org.rococoa.cocoa.CGFloat.class, org.rococoa.cocoa.CGFloat.class, ESize.StaticSizeField); public final Class<?> type, wrapperType; public final String simpleName, name; public final boolean isPrimitive; public enum ESize { One(expr(1)), Two(expr(2)), Four(expr(4)), Eight(expr(8)), StaticSizeField(null) { @Override public Expression sizeof(JavaPrim p) { return staticField(p.type, "SIZE"); } }, CharSize(null) { @Override public Expression sizeof(JavaPrim p) { return staticField(Native.class, "WCHAR_SIZE"); } }, Zero(expr(0)); private final Expression sizeOfExpression; ESize(Expression sizeOfExpression) { this.sizeOfExpression = sizeOfExpression; } public Expression sizeof(JavaPrim p) { return sizeOfExpression.clone(); } } public final ESize size; private static Map<String, JavaPrim> nameToPrim; public static JavaPrim getJavaPrim(String name) { if (nameToPrim == null) { nameToPrim = new HashMap<String, JavaPrim>(); for (JavaPrim p : values()) { nameToPrim.put(p.simpleName, p); } } return nameToPrim.get(name); } JavaPrim(Class<?> type, Class<?> wrapperType, ESize size) { this.type = type; this.wrapperType = wrapperType; this.size = size; this.name = type == null ? "void" : type.getName(); this.isPrimitive = type == null || type.isPrimitive(); this.simpleName = type == null ? "void" : type.getSimpleName(); } } public Expression typeLiteral(TypeRef c) { if (c != null && c.toString().equals("?")) return new Constant(Constant.Type.Null, null); if (c instanceof SimpleTypeRef && result.config.runtime == JNAeratorConfig.Runtime.BridJ) { Identifier id = ((SimpleTypeRef) c).getName(); SimpleIdentifier sid = id.resolveLastSimpleIdentifier(); if (!sid.getTemplateArguments().isEmpty()) { Identifier erased = id.eraseTemplateArguments(); List<Expression> exprs = new ArrayList<Expression>(); exprs.add(typeLiteral(typeRef(erased.clone()))); for (Expression t : sid.getTemplateArguments()) { if (t instanceof Expression.TypeRefExpression) { exprs.add(typeLiteral(((Expression.TypeRefExpression) t).getType().clone())); } } return methodCall(expr(typeRef(DefaultParameterizedType.class)), "paramType", exprs.toArray(new Expression[exprs.size()])); } } return memberRef(expr(c), MemberRefStyle.Dot, "class"); } public void initTypes() { prim("void", JavaPrim.Void); prim("UTF32Char", JavaPrim.Char); prim("unichar", JavaPrim.Char); prim("int64_t", JavaPrim.Long); prim("uint64_t", JavaPrim.Long); prim("u_int64_t", JavaPrim.Long); prim("long long", JavaPrim.Long); prim("long long int", JavaPrim.Long); prim("long int", JavaPrim.Int); prim("LONGLONG", JavaPrim.Long); prim("ULONGLONG", JavaPrim.Long); prim("INT", JavaPrim.Int); prim("UINT", JavaPrim.Int); prim("SHORT", JavaPrim.Short); prim("USHORT", JavaPrim.Short); prim("BYTE", JavaPrim.Byte); prim("UBYTE", JavaPrim.Byte); prim("DOUBLE", JavaPrim.Double); prim("FLOAT", JavaPrim.Float); prim("WORD", JavaPrim.Short); prim("DWORD", JavaPrim.Int); if (result.config.runtime == JNAeratorConfig.Runtime.BridJ) prim("BOOL", JavaPrim.Int); else prim("BOOL", JavaPrim.Boolean); prim("DWORD64", JavaPrim.Long); prim("LONG64", JavaPrim.Long); prim("UInt64", JavaPrim.Long); prim("SInt64", JavaPrim.Long); prim("__int64", JavaPrim.Long); prim("__int64_t", JavaPrim.Long); prim("int32_t", JavaPrim.Int); prim("uint32_t", JavaPrim.Int); prim("__int32_t", JavaPrim.Int); prim("__uint32_t", JavaPrim.Int); prim("u_int32_t", JavaPrim.Int); prim("uint32", JavaPrim.Int); prim("int32", JavaPrim.Int); prim("int", JavaPrim.Int); //prim("NSUInteger", JavaPrim.NativeSize); //prim("NSInteger", JavaPrim.NativeSize); prim("SInt32", JavaPrim.Int); prim("UInt32", JavaPrim.Int); prim("GLint", JavaPrim.Int); prim("GLuint", JavaPrim.Int); prim("GLenum", JavaPrim.Int); prim("GLsizei", JavaPrim.Int); prim("__darwin_size_t", JavaPrim.Int); prim("__int32", JavaPrim.Int); prim("NSInteger", JavaPrim.NSInteger); prim("NSUInteger", JavaPrim.NSUInteger); prim("CGFloat", JavaPrim.CGFloat); JavaPrim longPrim = result.config.gccLong ? JavaPrim.NativeSize : JavaPrim.NativeLong; prim("long", longPrim); prim("LONG", longPrim); prim("ULONG", longPrim); JavaPrim sizePrim = result.config.sizeAsLong ? longPrim : JavaPrim.NativeSize; prim("size_t", sizePrim); prim("ptrdiff_t", sizePrim); prim("int16_t", JavaPrim.Short); prim("uint16_t", JavaPrim.Short); prim("__int16_t", JavaPrim.Short); prim("__uint16_t", JavaPrim.Short); prim("u_int16_t", JavaPrim.Short); prim("uint16", JavaPrim.Short); prim("int16", JavaPrim.Short); prim("SInt16", JavaPrim.Short); prim("UInt16", JavaPrim.Short); prim("short", JavaPrim.Short); prim("WCHAR", JavaPrim.Short); prim("wchar_t", result.config.wcharAsShort ? JavaPrim.Short : JavaPrim.Char); prim("__int16", JavaPrim.Short); prim("int8_t", JavaPrim.Byte); prim("uint8_t", JavaPrim.Byte); prim("u_int8_t", JavaPrim.Byte); prim("__uint8_t", JavaPrim.Byte); prim("__int8_t", JavaPrim.Byte); prim("SInt8", JavaPrim.Byte); prim("UInt8", JavaPrim.Byte); prim("char", JavaPrim.Byte); prim("unsigned char", JavaPrim.Byte); prim("__unsigned char", JavaPrim.Byte); prim("signed char", JavaPrim.Byte); prim("__signed char", JavaPrim.Byte); prim("SignedByte", JavaPrim.Byte); prim("__int8", JavaPrim.Byte); prim("float", JavaPrim.Float); prim("NSFloat", JavaPrim.Float); prim("CGFloat", JavaPrim.Float); prim("double_t", JavaPrim.Double); prim("double", JavaPrim.Double); prim("NSDouble", JavaPrim.Double); prim("CGDouble", JavaPrim.Double); prim("bool", JavaPrim.Boolean); prim("Boolean", JavaPrim.Boolean); prim("boolean_t", JavaPrim.Boolean); primToByReference.put(JavaPrim.Int, IntByReference.class); primToByReference.put(JavaPrim.Char, CharByReference.class); primToByReference.put(JavaPrim.Short, ShortByReference.class); primToByReference.put(JavaPrim.Byte, ByteByReference.class); primToByReference.put(JavaPrim.Long, LongByReference.class); primToByReference.put(JavaPrim.Float, FloatByReference.class); primToByReference.put(JavaPrim.Double, DoubleByReference.class); primToByReference.put(JavaPrim.NativeLong, NativeLongByReference.class); primToByReference.put(JavaPrim.NativeSize, NativeSizeByReference.class); primToByReference.put(JavaPrim.NSInteger, NativeSizeByReference.class); primToByReference.put(JavaPrim.NSUInteger, NativeSizeByReference.class); primToByReference.put(JavaPrim.CGFloat, CGFloatByReference.class); //primsByReference.put(JavaPrim.Void, PointerByReference.class); for (Class<?> c : primToByReference.values()) { byReferenceClassesNames.add(c.getName()); } // byReferenceClassesNames.add(PointerByReference.class.getName()); primToGlobal.put(JavaPrim.Int, GlobalInt.class); primToGlobal.put(JavaPrim.Char, GlobalChar.class); primToGlobal.put(JavaPrim.Short, GlobalShort.class); primToGlobal.put(JavaPrim.Byte, GlobalByte.class); primToGlobal.put(JavaPrim.Long, GlobalLong.class); primToGlobal.put(JavaPrim.Float, GlobalFloat.class); primToGlobal.put(JavaPrim.Double, GlobalDouble.class); primToGlobal.put(JavaPrim.NativeLong, GlobalNativeLong.class); primToGlobal.put(JavaPrim.NativeSize, GlobalNativeSize.class); primToGlobal.put(JavaPrim.NSInteger, GlobalNativeSize.class); primToGlobal.put(JavaPrim.NSUInteger, GlobalNativeSize.class); primToGlobal.put(JavaPrim.CGFloat, GlobalCGFloat.class); primToBuffer.put(JavaPrim.Int, IntBuffer.class); primToBuffer.put(JavaPrim.Char, CharBuffer.class); primToBuffer.put(JavaPrim.Short, ShortBuffer.class); primToBuffer.put(JavaPrim.Byte, ByteBuffer.class); primToBuffer.put(JavaPrim.Long, LongBuffer.class); primToBuffer.put(JavaPrim.Float, FloatBuffer.class); primToBuffer.put(JavaPrim.Double, DoubleBuffer.class); //primToBuffer.put(JavaPrim.NativeLong, NativeLongByReference.class); } Map<String, TypeRef> manualTypeDefs = new HashMap<String, TypeRef>(); public Pair<TypeDef, Declarator> getTypeDef(Identifier name) { if (name == null) { return null; } Pair<TypeDef, Declarator> p = result.typeDefs.get(name); if (p == null) { return null; } Declarator value = p.getValue(); String rname = value == null ? null : value.resolveName(); if (rname != null) { if (name.equals("id")) { return null; } if (name.equals("SEL")) { return null; } if (name.equals("IMP")) { return null; } if (name.equals("Class")) { return null; } if (name.equals("BOOL")) { if (rname.equals("byte")) { return null; } } } return p; } public TypeRef resolveTypeDef(TypeRef valueType, final Identifier libraryClassName, final boolean convertToJavaRef, final boolean convertEnumToJavaRef) { if (valueType == null) { return null; } // if (valueType.toString().equals("CGFunctionEvaluateCallback")) // valueType = valueType; if (valueType instanceof TaggedTypeRef && convertToJavaRef) { TaggedTypeRef ttr = (TaggedTypeRef) valueType; if (ttr.getTag() != null) { TypeRef ref = ttr instanceof Struct ? typeRef(findStructRef(ttr.getTag(), libraryClassName)) : ttr instanceof Enum && convertEnumToJavaRef ? findEnum(ttr.getTag(), libraryClassName) : null; if (ref == null && convertEnumToJavaRef) { return ref; } } } final TypeRef valueTypeCl = valueType.clone(); Arg holder = new Arg(); holder.setValueType(valueTypeCl); valueTypeCl.accept(new Scanner() { java.util.Stack<String> names = new java.util.Stack<String>(); int depth = 0; @Override public void visitSimpleTypeRef(SimpleTypeRef simpleTypeRef) { depth++; try { Identifier name = ((SimpleTypeRef) simpleTypeRef).getName(); if (name == null) { return; } String nameStr = name.toString(); if (nameStr == null) { return; } if (JavaPrim.getJavaPrim(nameStr) != null) { return; } if (names.contains(nameStr)) { return; } names.push(nameStr); try { if (resolvesToPrimitive(nameStr)) { return; } super.visitSimpleTypeRef(simpleTypeRef); if (simpleTypeRef.isMarkedAsResolved()) { return; } // Identifier oc = findObjCClassIdent(name); // if (oc != null) { // name.replaceBy(oc); // } Pair<TypeDef, Declarator> p = getTypeDef(name); if (p != null) { TypeRef tr = p.getFirst().getValueType();//as(p.getSecond().mutateType(p.getFirst().getValueType()), TypeRef.class); if (tr instanceof Enum && !convertEnumToJavaRef) { simpleTypeRef.replaceBy(typeRef(int.class)); return; } if (tr instanceof TaggedTypeRef) { Identifier name2 = result.declarationsConverter.getActualTaggedTypeName((TaggedTypeRef) tr); if (name2 != null) { name = name2; } } if (convertToJavaRef) { if (tr instanceof TaggedTypeRef) { TaggedTypeRef s = (TaggedTypeRef) tr; if (s.isForwardDeclaration()) { return; } // if (tr instanceof Enum) { // tr = typeRef(s.getTag().clone()); // } else { Identifier ident = result.getTaggedTypeIdentifierInJava(s); if (ident != null) { tr = typeRef(ident);//findRef(name, s, libraryClassName)); }// } } else if (tr instanceof FunctionSignature) { tr = findCallbackRef((FunctionSignature) tr, libraryClassName); } } String strs = simpleTypeRef.toString(); String trs = tr == null ? null : tr.toString(); if (trs != null && !strs.equals(trs)) { TypeRef clo = tr.clone(); simpleTypeRef.replaceBy(clo); if (depth < 30) { clo.accept(this); } else { System.err.println("Infinite loop in type conversion ? " + tr); } } return; } TypeRef manualTypeRef = manualTypeDefs.get(name); if (manualTypeRef != null) { if (!convertToJavaRef) { return; } simpleTypeRef.replaceBy(manualTypeRef); return; } TypeRef structRef = typeRef(result.typeConverter.findStructRef(name, libraryClassName)); if (structRef != null) { if (!convertToJavaRef) { return; } simpleTypeRef.replaceBy(structRef); } TypeRef enumRef = result.typeConverter.findEnum(name, libraryClassName); if (enumRef != null) { if (!convertToJavaRef || !convertEnumToJavaRef) { return; } simpleTypeRef.replaceBy(enumRef); } Define define = result.defines.get(name); Expression expression = define == null ? null : define.getValue(); if (expression != null) { if (!convertToJavaRef) { return; } Identifier fieldName = null; if (expression instanceof Expression.VariableRef) { fieldName = ((Expression.VariableRef) expression).getName(); } else if (expression instanceof MemberRef) { fieldName = ((MemberRef) expression).getName(); } if (fieldName != null && !fieldName.equals(name)) { simpleTypeRef.replaceBy(resolveTypeDef(new TypeRef.SimpleTypeRef(fieldName), libraryClassName, true /*convertToJavaRef*/, convertEnumToJavaRef)); return; } } } finally { names.pop(); } } finally { depth--; } } }); TypeRef tr = holder.getValueType(); // tr.setParentElement(valueType.getParentElement()); return tr;// == null ? null : tr.clone(); } public boolean resolvesToPrimitive(String name) { return javaPrims.containsKey(name); } // TypeRef getPrimitiveRef(TypeRef valueType, String callerLibraryClass) { // JavaPrim prim = getPrimitive(valueType, callerLibraryClass); // if (prim == null) // return null; // // TypeRef tr = typeRef(prim); // if (valueType.isUnsigned()) // tr.addAnnotation(new Annotation(Unsigned.class)); // if (valueType.isUnsigned()) // tr.addAnnotation(new Annotation(Unsigned.class)); // // return tr; // } public static class JavaPrimitive extends Primitive { JavaPrim javaPrim; public JavaPrimitive() { } public JavaPrimitive(JavaPrim javaPrim) { super(); setName(ident(javaPrim == JavaPrim.Void ? Void.TYPE : javaPrim.type)); this.javaPrim = javaPrim; } public JavaPrim getJavaPrim() { return javaPrim; } public void setJavaPrim(JavaPrim javaPrim) { this.javaPrim = javaPrim; } } public JavaPrim getPrimitive(TypeRef valueType, Identifier libraryClassName) { valueType = resolveTypeDef(valueType, libraryClassName, true, true); if (valueType == null) { return null; } Identifier name = null; List<Modifier> mods = valueType.getModifiers(); int longCount = ModifierType.Long.countIn(mods); if (valueType instanceof JavaPrimitive) { return ((JavaPrimitive) valueType).getJavaPrim(); } if (valueType instanceof Primitive) { name = ((Primitive) valueType).getName(); if (name == null) { if (longCount == 1) { name = ident("long"); } else if (longCount > 1) { name = ident("long long"); } else if (valueType.hasModifier(ModifierType.Short)) { name = ident("short"); } else { name = ident("int"); } } } else if (valueType instanceof SimpleTypeRef) { name = ((SimpleTypeRef) valueType).getName(); } if (name == null) { return null; } JavaPrim p = JavaPrim.getJavaPrim(name.toString()); if (p != null && !p.isPrimitive) { return p; } boolean isLong = false; String str; if ((isLong = valueType.getModifiers().contains("long")) || valueType.getModifiers().contains("short")) { str = (isLong ? "long " : "short ") + name; } else { str = name.toString(); } JavaPrim type = javaPrims.get(str); if (type == JavaPrim.Int && longCount > 1) { return JavaPrim.Long; } return type; } public Identifier findStructRef(Identifier name, Identifier libraryClassName) { return findStructRef(result.structsByName.get(name), name, libraryClassName); } public Identifier findStructRef(Struct s, Identifier name, Identifier libraryClassName) { if (s == null || s.isForwardDeclaration()) { Pair<TypeDef, Declarator> pair = getTypeDef(name); if (pair == null) { return null; } if (pair.getFirst() == null || pair.getSecond() == null) { return null; } Object td = pair.getSecond().mutateType(pair.getFirst().getValueType()); if (!(td instanceof Struct)) { return null; } s = (Struct) td; } if (s == null && result.config.runtime == JNAeratorConfig.Runtime.BridJ) { String ns = name.toString(); Class<?> cl = null; if (ns.equals("IUnknown")) cl = org.bridj.cpp.com.IUnknown.class; else if (ns.equals("GUID")) cl = org.bridj.cpp.com.GUID.class; else if (ns.equals("RECT")) cl = org.bridj.cpp.com.RECT.class; if (cl != null) return ident(cl); } return result.getTaggedTypeIdentifierInJava(s); /* name = result.declarationsConverter.getActualTaggedTypeName((TaggedTypeRef) pair.getFirst().getValueType()); return findRef(name, s, libraryClassName, !result.config.putTopStructsInSeparateFiles); } else { return result.getTaggedTypeIdentifierInJava(s); //name = result.declarationsConverter.getActualTaggedTypeName(s); }*/ } public Identifier findStructRef(Struct s, Identifier libraryClassName) { switch (s.getType()) { case ObjCClass: case ObjCProtocol: return result.objectiveCGenerator.getFullClassName(s); default: return findStructRef(s, result.declarationsConverter.getActualTaggedTypeName(s), libraryClassName); } } // public String find(String name, Element e, String callerLibraryClass) { // if (e == null) // return null; // String library = result.getLibrary(e); // if (library == null) // return null; // SimpleIdentifier libClass = result.getLibraryClassFullName(library); // return SyntaxUtils.equal(libClass, callerLibraryClass) ? name : libClass + "." + name; // } public Identifier libMember(Identifier libClass, Identifier libraryClassName, Identifier member) { //return ident(SyntaxUtils.equal(libClass, libraryClassName) ? null : libClass, member); return ident(libClass, member); //return member; //TODODODODODODODODOoOOOOO } public Identifier findRef(Identifier name, Element e, Identifier libraryClassName, boolean inLibClass) { if (e == null || !name.isPlain()) { return null; } String library = result.getLibrary(e); if (library == null) { return null; } // e = e.getParentElement(); Struct parentStruct = e instanceof Struct ? (Struct) e : e.findParentOfType(Struct.class); if (!inLibClass && parentStruct != null) { if (parentStruct == e) { return ident(result.getLibraryPackage(library), name); } return ident(result.getTaggedTypeIdentifierInJava(parentStruct), name); } return libMember(result.getLibraryClassFullName(library), libraryClassName, name); } public SimpleTypeRef findEnum(Identifier name, Identifier libraryClassName) { Enum s = result.enumsByName.get(name); if (s == null) { return null; } return findEnumRef(s, libraryClassName); } public SimpleTypeRef findEnumRef(Enum s, Identifier libraryClassName) { if (result.config.runtime == JNAeratorConfig.Runtime.BridJ) return typeRef(result.getTaggedTypeIdentifierInJava(s)); Identifier name = result.declarationsConverter.getActualTaggedTypeName(s); String library = result.getLibrary(s); if (library == null) { return null; } Identifier libClass = result.getLibraryClassFullName(library); //return new SimpleTypeRef(SyntaxUtils.equal(libClass, callerLibraryClass) ? name : libClass + "." + name); /*if (result.config.runtime == JNAeratorConfig.Runtime.BridJ) { return typeRef(findRef(name, s, libraryClassName, result.config.putTopStructsInSeparateFiles)); }*/ SimpleTypeRef tr = new SimpleTypeRef("int"); if (result.config.features.contains(JNAeratorConfig.GenFeatures.EnumTypeLocationComments)) { tr.setCommentBefore("@see " + (SyntaxUtils.equal(libClass, libraryClassName) ? name : libClass + "#" + name)); } // if (s.getTag() != null) // tr.setCommentBefore("@see enums in " + s.getTag()); return tr; } public static Expression javaStaticFieldRef(Identifier javaClass, Identifier fieldName) { return memberRef( expr(typeRef(javaClass)), MemberRefStyle.Dot, fieldName); } public Expression findDefine(Identifier name) { Define s = result.defines.get(name); String library = s == null ? null : result.getLibrary(s); return library == null ? null : javaStaticFieldRef(result.getLibraryClassFullName(library), name); } public Identifier inferCallBackName(FunctionSignature functionSignature, boolean prependNamespaces, boolean qualify, Identifier libraryClassName) { List<String> nameElements = new ArrayList<String>(); Identifier name = functionSignature.getFunction().getName(); if (name != null) { name = name.clone(); } Identifier parentIdent = null; Element parent = functionSignature.getParentElement(); boolean firstParent = true; while (parent != null) { if (parent instanceof Struct) { parentIdent = findStructRef((Struct) parent, null); break; } else if (firstParent) { if (name == null && parent instanceof TypeDef) { Declarator simpleSto = null; for (Declarator sto : ((TypeDef) parent).getDeclarators()) { String stoName = sto.resolveName(); if (stoName == null) { continue; } if (!(sto instanceof ArrayDeclarator)) { boolean weirdName = stoName.startsWith("_") || stoName.endsWith("_"); if (simpleSto == null || (simpleSto.resolveName().startsWith("_") || simpleSto.resolveName().endsWith("_")) && !weirdName) { simpleSto = sto; } if (!weirdName) { break; } } if (stoName != null) { name = new SimpleIdentifier(stoName); } } } else if (name == null && parent instanceof Arg) { Arg arg = (Arg) parent; Function f = SyntaxUtils.as(arg.getParentElement(), Function.class); if (f != null) { name = new SimpleIdentifier(f.getName() + "_" + arg.getName()); break; } } else if (firstParent) { // if (//parent instanceof VariablesDeclaration || // parent instanceof FunctionPointerDeclaration // //|| parent instanceof TypeDef // ) { // nameElements.add("Callback"); // } } } parent = parent.getParentElement(); firstParent = false; } if (qualify && parentIdent == null) { //if (libraryClassName != null) // parentIdent = libraryClassName; //else { String library = result.getLibrary(functionSignature); if (library != null) { parentIdent = result.getLibraryClassFullName(library); } //} } if (prependNamespaces) { if (name == null) { name = new SimpleIdentifier("callback"); } nameElements.add(name.toString()); return ident(qualify ? parentIdent : null, StringUtils.implode(nameElements, "_")); } else { return ident(qualify ? parentIdent : null, name); } } public TypeRef findCallbackRef(Identifier name, Identifier libraryClassName) { FunctionSignature s = result.callbacksByName.get(name); if (s == null) { return null; } // Struct parentStruct = s.findParentOfType(Struct.class); // if (parentStruct != null && (parentStruct.getType() == Struct.Type.ObjCClass || parentStruct.getType() == Struct.Type.ObjCProtocol)) { // //Identifier structName = result.declarationsConverter.getActualTaggedTypeName(parentStruct); // return //result.result.getObjCClass(parentStruct.getName()). // typeRef(//libMember(structName, libraryClassName, // inferCallBackName(s, true, true)//) // ); // } return findCallbackRef(s, libraryClassName); } public TypeRef findCallbackRef(FunctionSignature s, Identifier callerLibraryClass) { String library = result.getLibrary(s); if (library == null) { return null; } // Struct parentStruct = s.findParentOfType(Struct.class); // if (parentStruct != null && (parentStruct.getType() == Struct.Type.ObjCClass || parentStruct.getType() == Struct.Type.ObjCProtocol)) { // Identifier structName = result.declarationsConverter.getActualTaggedTypeName(parentStruct); // return // typeRef(ident(structName, inferCallBackName(s, true, true))); // } return typeRef(inferCallBackName(s, true, true, callerLibraryClass)); // return typeRef(libMember(result.getLibraryClassFullName(library), callerLibraryClass, inferCallBackName(s, true, true))); //typeRef(ident(result.getLibraryClassFullName(library), inferCallBackName(s, true))); } static TypeRef primRef(JavaPrim p) { if (p == null) { return null; } return new JavaPrimitive(p); // return new SimpleTypeRef(toString(p)); } boolean isResolved(SimpleTypeRef tr) { return tr != null && (tr.isMarkedAsResolved() || isResolved(tr.getName())); } boolean isResolved(Identifier i) { if (i == null || i.isPlain()) { return false; } return (i instanceof Identifier.QualifiedIdentifier) && Identifier.QualificationSeparator.Dot.equals(((Identifier.QualifiedIdentifier) i).getSeparator()); } public enum ConvType { Enum, Pointer, Primitive, Struct, NativeLong, NativeSize, Void, Callback } public class NL4JConversion { public ConvType type; public TypeRef typeRef, indirectType; public List<Expression> arrayLengths; public Expression bits; public Expression getExpr, setExpr; public boolean wideString, readOnly, isPtr, byValue, nativeSize, cLong, isUndefined; public Charset charset; public final List<Annotation> annotations = new ArrayList<Annotation>(); //public String structIOFieldGetterNameRadix; public String pointerFieldGetterNameRadix; public Expression arrayLength() { Expression length = null; for (Expression m : arrayLengths) { m.setParenthesis(true); if (length == null) length = m.clone(); else length = expr(length, BinaryOperator.Multiply, m.clone()); } return length.setParenthesis(arrayLengths.size() > 1); } public TypeRef getIndirectTypeRef() { if (type == ConvType.Void) { return typeRef(ident("?")); } if (result.config.runtime == JNAeratorConfig.Runtime.BridJ) { if (type == ConvType.NativeSize) { return typeRef(SizeT.class); } if (type == ConvType.NativeLong) { return typeRef(org.bridj.CLong.class); } } TypeRef t = indirectType == null ? typeRef : indirectType; return t == null ? null : t.clone(); } public <M extends ModifiableElement> M annotateRawType(M element) throws UnsupportedConversionException { element.addAnnotations(annotations); if (type != null) { switch (type) { case Enum: case Primitive: case Void: break; case NativeLong: element.addAnnotation(new Annotation(CLong.class)); break; case NativeSize: element.addAnnotation(new Annotation(Ptr.class)); break; case Pointer: element.addAnnotation(new Annotation(Ptr.class)); break; case Struct: //throw new UnsupportedConversionException(typeRef, "Struct by value not supported yet"); break; default: throw new UnsupportedConversionException(typeRef, "Not supported"); } } return element; } public <M extends ModifiableElement> M annotateTypedType(M element) throws UnsupportedConversionException { element.addAnnotations(annotations); if (type != ConvType.Pointer) { annotateRawType(element); } return element; } } static Map<String, Pair<Integer, Class<?>>> buffersAndArityByType = new HashMap<String, Pair<Integer, Class<?>>>(); static Map<String, Pair<Integer, Class<?>>> arraysAndArityByType = new HashMap<String, Pair<Integer, Class<?>>>(); static Map<String, String> pointerFieldGetterNameRadixByType = new HashMap<String, String>(); static { Object[] data = new Object[]{ "char", Byte.TYPE, byte[].class, ByteBuffer.class, "Char", "long", Long.TYPE, long[].class, LongBuffer.class, "Long", "int", Integer.TYPE, int[].class, IntBuffer.class, "Int", "short", Short.TYPE, short[].class, ShortBuffer.class, "Short", "wchar_t", Character.TYPE, char[].class, CharBuffer.class, "WChar", "double", Double.TYPE, double[].class, DoubleBuffer.class, "Double", "float", Float.TYPE, float[].class, FloatBuffer.class, "Float", "bool", Boolean.TYPE, boolean[].class, null, "Bool" }; for (int arity : new int[]{1, 2, 4, 8, 16}) { String suffix = arity == 1 ? "" : arity + ""; for (int i = 0; i < data.length; i += 5) { String rawType = (String) data[i]; Class<?> scalClass = (Class<?>) data[i + 1]; Class<?> arrClass = (Class<?>) data[i + 2]; Class<?> buffClass = (Class<?>) data[i + 3]; String radix = (String) data[i + 4]; Pair<Integer, Class<?>> buffPair = new Pair<Integer, Class<?>>(arity, arity == 1 ? scalClass : buffClass), arrPair = new Pair<Integer, Class<?>>(arity, arity == 1 ? scalClass : arrClass); for (String type : new String[]{rawType + suffix, "u" + rawType + suffix}) { buffersAndArityByType.put(type, buffPair); arraysAndArityByType.put(type, arrPair); pointerFieldGetterNameRadixByType.put(type, radix); } } } } public NL4JConversion convertTypeToNL4J(TypeRef valueType, Identifier libraryClassName, Expression structIOExpr, Expression valueExpr, int fieldIndex, int bits) throws UnsupportedConversionException { TypeRef original = valueType; //if (valueType != null && valueType.toString().contains("MonoDomain")) // valueType = (TypeRef)valueType; valueType = resolveTypeDef(valueType, libraryClassName, true, true); //Expression offsetExpr = structIOExpr == null ? null : methodCall(structIOExpr, "getFieldOffset", expr(fieldIndex)); //Expression bitOffsetExpr = structIOExpr == null || bits <= 0 ? null : methodCall(structIOExpr, "getFieldBitOffset", expr(fieldIndex)); //Expression bitLengthExpr = structIOExpr == null || bits <= 0 ? null : methodCall(structIOExpr, "getFieldBitLength", expr(fieldIndex)); NL4JConversion conv = new NL4JConversion(); if (valueType == null) { conv.type = ConvType.Void; conv.typeRef = primRef(JavaPrim.Void); return conv; } //if (valueType instanceof Struct) // valueType = typeRef(findStructRef((Struct)valueType, libraryClassName)); if (valueType instanceof TargettedTypeRef) { TypeRef targetRef = ((TargettedTypeRef) valueType).getTarget(); if (valueType instanceof Pointer.ArrayRef) { Pointer.ArrayRef arrayRef = (Pointer.ArrayRef) valueType; List<Expression> sizes = new ArrayList<Expression>(); for (Expression dim : arrayRef.flattenDimensions()) { if (dim == null || dim instanceof EmptyArraySize) continue; Expression m = result.typeConverter.convertExpressionToJava(dim, libraryClassName, false).getFirst(); m.setParenthesis(false); sizes.add(m); } if (!sizes.isEmpty()) conv.arrayLengths = sizes; } try { NL4JConversion targetConv = convertTypeToNL4J(targetRef, libraryClassName, null, null, -1, -1); //if (result.isFakePointer(libraryClassName)) if (targetConv.isUndefined && allowFakePointers && original instanceof SimpleTypeRef) { conv.isPtr = true; conv.type = ConvType.Pointer; conv.typeRef = typeRef(result.getFakePointer(libraryClassName, ((SimpleTypeRef)original).getName().clone())); if (structIOExpr != null) { if (conv.arrayLengths == null) conv.setExpr = methodCall(structIOExpr.clone(), "setPointerField", thisRef(), expr(fieldIndex), valueExpr); conv.getExpr = methodCall(structIOExpr.clone(), "getTypedPointerField", thisRef(), expr(fieldIndex)); } return conv; } TypeRef pointedTypeRef = targetConv.getIndirectTypeRef(); if (targetConv.type != ConvType.Void) { if (targetConv.type == ConvType.NativeSize) pointedTypeRef = typeRef(SizeT.class); else if (targetConv.type == ConvType.NativeLong) pointedTypeRef = typeRef(CLong.class); } if (pointedTypeRef != null) { conv.isPtr = true; conv.type = ConvType.Pointer; conv.typeRef = typeRef(ident(result.config.runtime.pointerClass, expr(pointedTypeRef.clone()))); if (structIOExpr != null) { if (conv.arrayLengths == null) conv.setExpr = methodCall(structIOExpr.clone(), "setPointerField", thisRef(), expr(fieldIndex), valueExpr); conv.getExpr = methodCall(structIOExpr.clone(), "getPointerField", thisRef(), expr(fieldIndex)); } return conv; } } catch (UnsupportedConversionException ex) { conv.isPtr = true; conv.type = ConvType.Pointer; conv.typeRef = typeRef(result.config.runtime.pointerClass); return conv; /*if (valueType instanceof TypeRef.Pointer && targetRef instanceof SimpleTypeRef && allowFakePointers) { conv.typeRef = typeRef(result.getFakePointer(libraryClassName, ((SimpleTypeRef)targetRef).getName().clone())); if (structIOExpr != null) { if (conv.arrayLengths == null) conv.setExpr = methodCall(structIOExpr.clone(), "setPointerField", thisRef(), expr(fieldIndex), valueExpr); conv.getExpr = methodCall(structIOExpr.clone(), "getTypedPointerField", thisRef(), expr(fieldIndex)); } return conv; }//*/ /*if (valueType instanceof TypeRef.Pointer && targetRef instanceof SimpleTypeRef && allowFakePointers) { conv.typeRef = typeRef(ident(result.config.runtime.pointerClass, expr(typeRef(result.getUndefinedType(libraryClassName, ((SimpleTypeRef)targetRef).getName().clone()))))); if (structIOExpr != null) { if (conv.arrayLengths == null) conv.setExpr = methodCall(structIOExpr.clone(), "setPointerField", thisRef(), expr(fieldIndex), valueExpr); conv.getExpr = methodCall(structIOExpr.clone(), "getTypedPointerField", thisRef(), expr(fieldIndex)); } return conv; }*/ } } else {//if (valueType instanceof SimpleTypeRef || valueType instanceof TaggedTypeRef || valueType) { JavaPrim prim = getPrimitive(valueType, libraryClassName); if (prim != null) { String radix; switch (prim) { case NativeLong: conv.type = ConvType.NativeLong; conv.typeRef = typeRef(Long.TYPE); conv.indirectType = typeRef(org.bridj.CLong.class); radix = "CLong"; break; case NativeSize: conv.type = ConvType.NativeSize; conv.typeRef = typeRef(Long.TYPE); conv.indirectType = typeRef(org.bridj.SizeT.class); radix = "SizeT"; break; case Void: conv.type = ConvType.Void; conv.typeRef = primRef(prim); radix = null; break; default: conv.type = ConvType.Primitive; conv.typeRef = primRef(prim); conv.indirectType = typeRef(prim.wrapperType); radix = StringUtils.capitalize(prim.type.getName()); break; } if (structIOExpr != null && radix != null) { conv.setExpr = methodCall(structIOExpr.clone(), "set" + radix + "Field", thisRef(), expr(fieldIndex), valueExpr); conv.getExpr = methodCall(structIOExpr.clone(), "get" + radix + "Field", thisRef(), expr(fieldIndex)); } return conv; } else { Identifier valueName = valueType instanceof SimpleTypeRef ? ((SimpleTypeRef)valueType).getName() : null; // Structs if (valueType instanceof Struct) conv.typeRef = typeRef(findStructRef((Struct)valueType, libraryClassName)); else if (result.structsFullNames.contains(valueName)) conv.typeRef = valueType; else conv.typeRef = typeRef(findStructRef(valueName, libraryClassName)); if (conv.typeRef != null) { //conv.setExpr = methodCall(structPeerExpr.clone(), "set" + radix, offsetExpr.clone(), valueExpr); if (structIOExpr != null) { conv.getExpr = methodCall(structIOExpr, "getNativeObjectField", thisRef(), expr(fieldIndex)); //conv.getExpr = new Expression.New(conv.typeRef, (Expression)methodCall(structIOExpr.clone(), "offset", offsetExpr.clone())); } conv.type = ConvType.Struct; return conv; } // Enums if (valueType instanceof Enum) conv.typeRef = findEnumRef((Enum)valueType, libraryClassName); else if (result.enumsFullNames.contains(valueName)) conv.typeRef = valueType; else conv.typeRef = findEnum(valueName, libraryClassName); if (conv.typeRef != null) { if (structIOExpr != null) { conv.setExpr = methodCall(structIOExpr, "setEnumField", thisRef(), expr(fieldIndex), valueExpr); conv.getExpr = methodCall(structIOExpr, "getEnumField", thisRef(), expr(fieldIndex));//expr(typeRef(FlagSet.class)), "fromValue", methodCall(structPeerExpr.clone(), "getInt", expr(fieldIndex)), classLiteral(conv.typeRef.clone())); } conv.type = ConvType.Enum; conv.typeRef = typeRef(ident(ValuedEnum.class, expr(conv.typeRef))); return conv; } // Callbacks conv.typeRef = conv.typeRef = result.callbacksFullNames.contains(valueName) ? valueType : valueType instanceof FunctionSignature ? findCallbackRef((FunctionSignature)valueType, libraryClassName) : findCallbackRef(valueName, libraryClassName); if (conv.typeRef != null) { if (structIOExpr != null) { conv.setExpr = methodCall(structIOExpr.clone(), "setPointerField", thisRef(), expr(fieldIndex), valueExpr); conv.getExpr = methodCall(structIOExpr.clone(), "getPointerField", thisRef(), expr(fieldIndex)); } conv.type = ConvType.Pointer; conv.typeRef = typeRef(ident(result.config.runtime.pointerClass, expr(conv.typeRef))); return conv; } } } if (valueType instanceof SimpleTypeRef && allowFakePointers) { conv.typeRef = typeRef(result.getUndefinedType(libraryClassName, ((SimpleTypeRef)valueType).getName().clone())); conv.isUndefined = true; return conv; } throw new UnsupportedConversionException(original, "Unsupported type"); } @SuppressWarnings("unchecked") Pair<TypeRef, List<Annotation>> toRawNL4JType(TypeRef nl4jType) throws UnsupportedConversionException { if (!(nl4jType instanceof SimpleTypeRef)) { throw new UnsupportedConversionException(nl4jType, "Not a known type : " + nl4jType); } Pair<TypeRef, List<Annotation>> ret = new Pair<TypeRef, List<Annotation>>(nl4jType.clone(), Collections.EMPTY_LIST); if (nl4jType instanceof TypeRef.Primitive) { return ret; } SimpleTypeRef str = (SimpleTypeRef) nl4jType; Identifier strn = str.getName(); if (strn.equals(result.config.runtime.pointerClass.getName())) { ret.setSecond(Arrays.asList(new Annotation(Ptr.class))); ret.setFirst(typeRef(JavaPrim.Long.type)); } else if (strn.equals(ValuedEnum.class.getName())) { ret.setFirst(typeRef(JavaPrim.Int.type)); } else { throw new UnsupportedConversionException(nl4jType, "No raw conversion available yet for type " + nl4jType); } return ret; } /* public static class NL4JTypeConversion { public enum Type { Enum, Pointer, Primitive, Struct, NativeLong, NativeSize, Void, Callback } public NL4JTypeConversion(TypeRef directType, TypeRef indirectType, Type type) { this.directType = directType; this.indirectType = indirectType; this.type = type; } private final TypeRef directType, indirectType; public final Type type; public <M extends ModifiableElement> M annotateRawType(M element) throws UnsupportedConversionException { if (type != null) switch (type) { case Enum: case Primitive: case Void: break; case NativeLong: element.addAnnotation(new Annotation(CLong.class)); break; case NativeSize: element.addAnnotation(new Annotation(Ptr.class)); break; case Pointer: element.addAnnotation(new Annotation(Ptr.class)); break; case Struct: throw new UnsupportedConversionException(directType, "Struct by value not supported yet"); default: throw new UnsupportedConversionException(directType, "Not supported"); } return element; } public <M extends ModifiableElement> M annotateTypedType(M element) throws UnsupportedConversionException { if (type != Type.Pointer) annotateRawType(element); return element; } public TypeRef getTypedTypeRef() { return directType == null ? typeRef("void") : directType.clone(); } public TypeRef getIndirectTypeRef() { if (type == NL4JTypeConversion.Type.Void) return typeRef(ident("?")); TypeRef t = indirectType == null ? directType : indirectType; return t == null ? null : t.clone(); } public TypeRef getRawType() throws UnsupportedConversionException { if (type == null) { return directType.clone(); } switch (type) { case Enum: return typeRef(Integer.TYPE); case Pointer: return typeRef(Long.TYPE); case Void: return typeRef("void"); case Primitive: case NativeLong: case NativeSize: return getTypedTypeRef(); case Struct: throw new UnsupportedConversionException(getTypedTypeRef(), "Struct by value not supported yet"); default: throw new UnsupportedConversionException(getTypedTypeRef(), "Not supported"); } } } NL4JTypeConversion toNL4JType(TypeRef valueType, java.util.Stack<String> namesStack, Identifier library) throws UnsupportedConversionException { if (valueType instanceof TargettedTypeRef) { TargettedTypeRef ttr = (TargettedTypeRef)valueType; NL4JTypeConversion targetConv = toNL4JType(ttr.getTarget(), namesStack, library); TypeRef pointedTypeRef = targetConv.getIndirectTypeRef(); if (targetConv.type != NL4JTypeConversion.Type.Void) { try { if (targetConv.type == NL4JTypeConversion.Type.NativeSize) pointedTypeRef = typeRef(SizeT.class); else if (targetConv.type == NL4JTypeConversion.Type.NativeLong) pointedTypeRef = typeRef(CLong.class); else { String s = targetConv.getRawType().toString(); if (s.equals(Byte.TYPE.getName()) && (result.config.charPtrAsString || valueType.hasModifier(ModifierType.__const))) return new NL4JTypeConversion( typeRef(ident(result.config.runtime.pointerClass, expr(typeRef(String.class)))), null, NL4JTypeConversion.Type.Pointer ); } } catch (UnsupportedConversionException ex) { } } return new NL4JTypeConversion( typeRef( ident( result.config.runtime.pointerClass, expr(pointedTypeRef) ) ), null, NL4JTypeConversion.Type.Pointer ); } if (valueType instanceof SimpleTypeRef) { JavaPrim prim = getPrimitive(valueType, null); if (prim != null) { switch (prim) { case NativeLong: return new NL4JTypeConversion(typeRef(Long.TYPE), typeRef(Long.class), NL4JTypeConversion.Type.NativeLong); case NativeSize: return new NL4JTypeConversion(typeRef(Long.TYPE), typeRef(Long.class), NL4JTypeConversion.Type.NativeSize); case Void: return new NL4JTypeConversion(null, null, NL4JTypeConversion.Type.Void); default: return new NL4JTypeConversion(typeRef(prim.type), typeRef(prim.wrapperType), NL4JTypeConversion.Type.Primitive); } } Identifier name = ((SimpleTypeRef)valueType).getName(); if (name == null) return null; if (namesStack == null) namesStack = new Stack<String>(); String nameStr = name.toString(); if (nameStr == null || namesStack.contains(nameStr)) return null; namesStack.push(nameStr); try { Pair<TypeDef,Declarator> p = getTypeDef(name); if (p != null) { TypeRef tr = p.getFirst().getValueType();//as(p.getSecond().mutateType(p.getFirst().getValueType()), TypeRef.class); if (tr instanceof TaggedTypeRef) { TaggedTypeRef ttr = (TaggedTypeRef)tr; Identifier name2 = result.declarationsConverter.getActualTaggedTypeName(ttr); if (name2 != null) { name = name2; nameStr = name.toString(); } //if (ttr.isForwardDeclaration()) // return; TypeRef javaRef = typeRef(result.getTaggedTypeIdentifierInJava(ttr)); if (tr instanceof Enum) { return new NL4JTypeConversion(toNL4JEnum(javaRef), null, NL4JTypeConversion.Type.Enum); } else if (tr instanceof Struct) { return new NL4JTypeConversion(javaRef, null, NL4JTypeConversion.Type.Struct); } } else if (tr instanceof FunctionSignature) { return new NL4JTypeConversion(typeRef(ident(result.config.runtime.pointerClass, expr(findCallbackRef((FunctionSignature)tr, null)))), null, NL4JTypeConversion.Type.Pointer); } else { String strs = valueType.toString(); String trs = tr == null ? null : tr.toString(); if (trs != null && !strs.equals(trs)) { try { TypeRef clo = tr.clone(); return toNL4JType(clo, namesStack, library); } catch (UnsupportedConversionException ex) { if (tr instanceof TypeRef.Pointer && allowFakePointers) { return new NL4JTypeConversion( typeRef(result.getFakePointer(library, name.clone())), null, null ); } else throw ex; } } } } TypeRef manualTypeRef = manualTypeDefs.get(nameStr); if (manualTypeRef != null) return toNL4JType(manualTypeRef, namesStack, library); TypeRef structRef = typeRef(findStructRef(name, null)); if (structRef != null) { return new NL4JTypeConversion(structRef.clone(), null, NL4JTypeConversion.Type.Struct); } TypeRef enumRef = findEnum(name, null); if (enumRef != null) { return new NL4JTypeConversion(toNL4JEnum(enumRef), null, NL4JTypeConversion.Type.Enum); } Define define = result.defines.get(nameStr); Expression expression = define == null ? null : define.getValue(); if (expression != null) { Identifier fieldName = null; if (expression instanceof Expression.VariableRef) fieldName = ((Expression.VariableRef) expression).getName(); else if (expression instanceof MemberRef) fieldName = ((MemberRef) expression).getName(); if (fieldName != null && !fieldName.equals(name)) return toNL4JType(new TypeRef.SimpleTypeRef(fieldName), namesStack, library); } } finally { namesStack.pop(); } } throw new UnsupportedConversionException(valueType, "Unsupported type"); } TypeRef toNL4JEnum(TypeRef enumResolvedJavaRef) { return typeRef(ident(ValuedEnum.class, expr(enumResolvedJavaRef.clone()))); } */ public Expression getFlatArraySizeExpression(Pointer.ArrayRef arrayRef, Identifier callerLibraryName) throws UnsupportedConversionException { Expression mul = null; List<Expression> dims = arrayRef.flattenDimensions(); for (int i = dims.size(); i-- != 0;) { Expression x = dims.get(i); if (x == null || x instanceof EmptyArraySize) { return null; //javaType = jr = new ArrayRef(typeRef(Pointer.class)); //break; } else { Pair<Expression, TypeRef> c = result.typeConverter.convertExpressionToJava(x, callerLibraryName, false); c.getFirst().setParenthesis(dims.size() > 1); if (mul == null) { mul = c.getFirst(); } else { mul = expr(c.getFirst(), BinaryOperator.Multiply, mul); } } } return mul; } Pattern wstringPat = Pattern.compile("(__)?const wchar_t\\*"), stringPat = Pattern.compile("(__)?const char\\*"), wstringPtrPtrPat = Pattern.compile("(__)?const wchar_t\\*\\*"), stringPtrPtrPat = Pattern.compile("(__)?const char\\*\\*"); protected boolean isString(String typeRefAsString, boolean wide) { if (wide) { return wstringPat.matcher(typeRefAsString).matches() || result.config.charPtrAsString && typeRefAsString.equals("wchar_t*"); } else { return stringPat.matcher(typeRefAsString).matches() || result.config.charPtrAsString && typeRefAsString.equals("char*"); } } protected boolean isStringPtrPtr(String typeRefAsString, boolean wide) { if (wide) { return wstringPtrPtrPat.matcher(typeRefAsString).matches() || result.config.charPtrAsString && typeRefAsString.equals("wchar_t**"); } else { return stringPtrPtrPat.matcher(typeRefAsString).matches() || result.config.charPtrAsString && typeRefAsString.equals("char**"); } } public TypeRef convertTypeToJNA(TypeRef valueType, TypeConversionMode conversionMode, Identifier libraryClassName) throws UnsupportedConversionException { // if (String.valueOf(valueType).contains("MonoImageOpenStatus")) // valueType.toString(); TypeRef original = valueType; valueType = resolveTypeDef(valueType, libraryClassName, true, false); // if (String.valueOf(valueType).contains("MonoObject")) // valueType.toString(); String valueTypeString = String.valueOf(valueType); if (valueTypeString.matches("void\\s*\\*") || valueTypeString.matches("const\\s*void\\s*\\*")) { //valueType = (TypeRef)valueType; if (original instanceof Pointer && result.config.features.contains(GenFeatures.TypedPointersForForwardDeclarations) && allowFakePointers) { Pointer p = (Pointer) original; if (p.getTarget() instanceof SimpleTypeRef) { if (isResolved((SimpleTypeRef) p.getTarget())) { return p.getTarget(); } Identifier name = ((SimpleTypeRef) p.getTarget()).getName(); if (!"void".equals(name.toString()) && name.isPlain()) { // int i = name.lastIndexOf('.'); // if (i >= 0) // name = name.substring(i + 1); return typeRef(result.getFakePointer(libraryClassName, name)); } } } } else { if (conversionMode == TypeConversionMode.ReturnType && result.config.stringifyConstCStringReturnValues) { if (isString(valueTypeString, false)) { return typeRef(String.class); } else if (isString(valueTypeString, true)) { return typeRef(WString.class); } } else if (conversionMode == TypeConversionMode.PrimitiveOrBufferParameter) { if (isString(valueTypeString, false)) { return typeRef(String.class); } else if (isString(valueTypeString, true)) { return typeRef(WString.class); } else if (isStringPtrPtr(valueTypeString, false)) { return arrayRef(typeRef(String.class)); } else if (isStringPtrPtr(valueTypeString, true)) { return arrayRef(typeRef(WString.class)); } /*else if (conversionMode == TypeConversionMode.PrimitiveOrBufferParameter) { if (valueTypeString.matches("char\\*")) return typeRef(StringPointer.ByValue.class); else if (valueTypeString.matches("wchar_t\\*")) return typeRef(WStringPointer.ByValue.class); }*/ } } if (valueType instanceof Primitive) { JavaPrim prim = getPrimitive(valueType, libraryClassName); if (prim != null) { return primRef(prim); } // if (!valueType.getModifiers().contains("long")) // return valueType.toString(); } if (valueType instanceof TaggedTypeRef) { Identifier name = result.declarationsConverter.getActualTaggedTypeName((TaggedTypeRef) valueType); if (name != null) { if (valueType instanceof Enum) { TypeRef tr = findEnum(name, libraryClassName); if (tr != null) { TypeRef intRef = primRef(JavaPrim.Int); intRef.setCommentBefore(tr.getCommentBefore()); return intRef; } } else if (valueType instanceof Struct) { Identifier tr = findStructRef(name, libraryClassName); if (tr != null) { switch (conversionMode) { case PointedValue: case NativeParameterWithStructsPtrPtrs: case NativeParameter: case PrimitiveOrBufferParameter: case ReturnType: case PrimitiveReturnType: case FieldType: return typeRef(tr); case StaticallySizedArrayField: case ExpressionType: default: return typeRef(ident(tr, ident("ByValue"))); } } } } } if (valueType instanceof FunctionSignature) { TypeRef tr = findCallbackRef((FunctionSignature)valueType, libraryClassName); if (tr != null) return tr; else return typeRef(((FunctionSignature)valueType).getFunction().getName().clone()); } if (valueType instanceof TargettedTypeRef) { //TypeRef target = resolveTypeDef(((TargettedTypeRef) valueType).getTarget(), callerLibraryClass); TypeRef target = ((TargettedTypeRef) valueType).getTarget(); boolean staticallySized = valueType instanceof ArrayRef && ((ArrayRef)valueType).hasStaticStorageSize(); TypeRef convArgType = null; JavaPrim prim = getPrimitive(target, libraryClassName); if (prim != null) { if (prim == JavaPrim.Void) return typeRef(result.config.runtime.pointerClass); else convArgType = primRef(prim); } else { Identifier name = null; if (target instanceof SimpleTypeRef) name = ((SimpleTypeRef) target).getName(); else if (target instanceof Struct) { Struct struct = (Struct)target; if (struct == null) { valueType = resolveTypeDef(original, libraryClassName, true, false); struct = null; } else { name = result.declarationsConverter.getActualTaggedTypeName(struct); } } else if (target instanceof FunctionSignature) { TypeRef tr = findCallbackRef((FunctionSignature)target, libraryClassName); if (tr != null) { if (valueType instanceof TypeRef.ArrayRef) { return new TypeRef.ArrayRef(tr); } else { return tr; } } //else // return typeRef(((FunctionSignature)valueType).getFunction().getName()); } else if (target instanceof Pointer) { if (conversionMode == TypeConversionMode.NativeParameter) return typeRef(PointerByReference.class); Pointer pt = ((Pointer)target); TypeRef ptarget = pt.getTarget(); if (ptarget instanceof SimpleTypeRef) { SimpleTypeRef ptargett = (SimpleTypeRef) ptarget; Identifier tname = ptargett.getName(); if (result.structsFullNames.contains(tname)) { if (conversionMode == TypeConversionMode.FieldType) return typeRef(PointerByReference.class); else return new ArrayRef(typeRef(ident(ptargett.getName(), "ByReference"))); } else if ((tname = result.findFakePointer(tname)) != null) return new ArrayRef(typeRef(tname.clone())); } } if (name != null) { /// Pointer to Objective-C class ? convArgType = findObjCClass(name); boolean isQualStruct = result.structsFullNames.contains(name); if (convArgType == null || isQualStruct) { /// Pointer to C structure Identifier structRef = isQualStruct ? name : findStructRef(name, libraryClassName); if (structRef != null) {//result.cStructNames.contains(name)) { switch (conversionMode) { case ExpressionType: case FieldType: convArgType = valueType instanceof TypeRef.ArrayRef ? typeRef(structRef) : typeRef(ident(structRef, ident("ByReference"))); if (valueType instanceof Pointer) return convArgType; break; default: if (isQualStruct && (valueType instanceof ArrayRef) && ( conversionMode == TypeConversionMode.NativeParameterWithStructsPtrPtrs || conversionMode == TypeConversionMode.PrimitiveOrBufferParameter )) return arrayRef(typeRef(structRef)); convArgType = typeRef(structRef); if (valueType instanceof Pointer) return convArgType; break; } } else { try { convArgType = convertTypeToJNA(target, conversionMode, libraryClassName); if (result.isUndefinedType(convArgType)) { if (allowFakePointers && original instanceof SimpleTypeRef) return typeRef(result.getFakePointer(libraryClassName, ((SimpleTypeRef)original).getName().clone())); else convArgType = typeRef(result.config.runtime.pointerClass); } if (convArgType != null && result.callbacksFullNames.contains(ident(convArgType.toString())) && !(valueType instanceof ArrayRef)) { TypeRef tr = typeRef(result.config.runtime.pointerClass); if (!result.config.noComments) tr.setCommentBefore("@see " + convArgType); return tr; } prim = getPrimitive(convArgType, libraryClassName); } catch (UnsupportedConversionException ex) { //convArgType = null;//return typeRef(result.config.runtime.pointerClass); if (valueType instanceof TypeRef.Pointer && target instanceof TypeRef.SimpleTypeRef && result.config.features.contains(JNAeratorConfig.GenFeatures.TypedPointersForForwardDeclarations) && allowFakePointers ) { if (isResolved((SimpleTypeRef) target)) { return target; } // int i = name.lastIndexOf('.'); // if (i >= 0) { // name = name.substring(i + 1); // } return typeRef(result.getFakePointer(libraryClassName, name)); } else { return typeRef(result.config.runtime.pointerClass); } } } } } else { try { convArgType = convertTypeToJNA(target, conversionMode, libraryClassName); prim = getPrimitive(convArgType, libraryClassName); } catch (UnsupportedConversionException ex) { //convArgType = null;// return typeRef(result.config.runtime.pointerClass); } } } switch (conversionMode) { case StaticallySizedArrayField: return new ArrayRef(convArgType); case PrimitiveOrBufferParameter: if (!result.config.noPrimitiveArrays && (target.getModifiers().contains(ModifierType.Const) || valueType.getModifiers().contains(ModifierType.Const))) { return new ArrayRef(convArgType); } Class<? extends Buffer> bc = primToBuffer.get(prim); if (bc != null) { return typeRef(bc); } case ReturnType: case FieldType: if (staticallySized) { return arrayRef(convArgType); } default: if (prim != null) { if (prim == JavaPrim.Byte) { return typeRef(result.config.runtime.pointerClass).importDetails(convArgType, false); } Class<? extends ByReference> byRefClass = primToByReference.get(prim); if (byRefClass != null) { return typeRef(byRefClass).importDetails(convArgType, false); } } if (convArgType != null && !convArgType.toString().equals(result.config.runtime.pointerClass.getName()) && valueType instanceof TypeRef.Pointer && target instanceof TypeRef.SimpleTypeRef) { return convArgType; } } if (target instanceof Pointer) { return typeRef(PointerByReference.class); } if (allowUnknownPointers) { return typeRef(result.config.runtime.pointerClass); } } if (valueType instanceof SimpleTypeRef) { Identifier name = ((SimpleTypeRef) valueType).getName(); if (name == null) { throw new UnsupportedConversionException(valueType, null); } boolean isQualStruct = result.structsFullNames.contains(name); //isQualCallback = result.callbacksFullNames.contains(name); if (!isQualStruct && isResolved((SimpleTypeRef) valueType)) { return valueType; } if (name instanceof SimpleIdentifier) { TypeRef tr = findObjCClass(name); if (tr == null) { tr = findObjCClass(new SimpleIdentifier(((SimpleIdentifier) name).getName())); } if (tr != null) { return tr; } } Identifier structRef = isQualStruct ? name : findStructRef(name, libraryClassName); if (structRef != null) { switch (conversionMode) { case PointedValue: case FieldType: return typeRef(structRef); default: return typeRef(ident(structRef, "ByValue")); } } TypeRef callbackRef = findCallbackRef(name, libraryClassName); if (callbackRef != null) { return callbackRef; } SimpleTypeRef enumTypeRef = findEnum(name, libraryClassName); //FieldRef enumQualifiedName = findEnum(name); if (enumTypeRef != null) { return enumTypeRef; } TypeRef objCClassRef = findObjCClass(name); if (objCClassRef != null) { return objCClassRef; } } JavaPrim prim = getPrimitive(valueType, libraryClassName); if (prim != null) { return primRef(prim); } if (valueType instanceof SimpleTypeRef && allowFakePointers) { return typeRef(result.getUndefinedType(libraryClassName, ((SimpleTypeRef)valueType).getName().clone())); } unknownTypes.add(String.valueOf(valueType)); throw new UnsupportedConversionException(valueType, null); } static Map<String, Class<?>> predefObjCClasses = new HashMap<String, Class<?>>(); static { predefObjCClasses.put("id", ObjCObject.class);//org.rococoa.ID.class); predefObjCClasses.put("SEL", org.rococoa.Selector.class); predefObjCClasses.put("IMP", com.sun.jna.Pointer.class); predefObjCClasses.put("Class", ObjCClass.class); predefObjCClasses.put("Protocol", ObjCClass.class); predefObjCClasses.put("NSObject", NSObject.class); //predefObjCClasses.put("NSClass", NSClass.class); } public Identifier findObjCClassIdent(Identifier name) { if (name instanceof SimpleIdentifier) { SimpleIdentifier sname = (SimpleIdentifier) name; String n = sname.getName(); if (n.equals("id") && sname.getTemplateArguments().size() == 1/* && conversionMode != TypeConversionMode.NativeParameter && conversionMode != TypeConversionMode.NativeParameterWithStructsPtrPtrs*/) { Expression x = sname.getTemplateArguments().get(0); TypeRefExpression trx = x instanceof TypeRefExpression ? (TypeRefExpression) x : null; SimpleTypeRef str = trx.getType() instanceof SimpleTypeRef ? (SimpleTypeRef) trx.getType() : null; if (str != null) { name = str.getName(); } } } Class<?> class1 = predefObjCClasses.get(name.toString()); if (class1 != null) { return ident(class1); } Struct s = result.getObjcCClassOrProtocol(name); if (s != null) { return result.objectiveCGenerator.getFullClassName(s); } return null; } public TypeRef findObjCClass(Identifier name) { return typeRef(findObjCClassIdent(name)); } private TypeRef arrayRef(TypeRef tr) { ArrayRef arrayRef; if (tr instanceof ArrayRef) { arrayRef = (ArrayRef) tr; arrayRef.addDimension(new Expression.EmptyArraySize()); } else { arrayRef = new ArrayRef(tr); } return arrayRef; } Set<String> unknownTypes = new HashSet<String>(); public static <A, B> Pair<A, B> pair(A a, B b) { return new Pair<A, B>(a, b); } public static Pair<Expression, TypeRef> typed(Expression a, TypeRef b) { return new Pair<Expression, TypeRef>(a, b); } public Pair<Expression, TypeRef> convertExpressionToJava(Expression x, Identifier libraryClassName, boolean promoteNativeLongToLong) throws UnsupportedConversionException { Pair<Expression, TypeRef> res = null; if (x instanceof AssignmentOp) { Pair<Expression, TypeRef> convTarget = convertExpressionToJava(((AssignmentOp) x).getTarget(), libraryClassName, promoteNativeLongToLong), convValue = convertExpressionToJava(((AssignmentOp) x).getValue(), libraryClassName, promoteNativeLongToLong); res = typed(expr(convTarget.getFirst(), AssignmentOperator.Equal, convValue.getFirst()), convTarget.getSecond()); } else if (x instanceof BinaryOp) { BinaryOp bop = (BinaryOp) x; Pair<Expression, TypeRef> conv1 = convertExpressionToJava(bop.getFirstOperand(), libraryClassName, promoteNativeLongToLong), conv2 = convertExpressionToJava(bop.getSecondOperand(), libraryClassName, promoteNativeLongToLong); if (conv1 != null && conv2 != null) { TypeRef t1 = conv1.getSecond(), t2 = conv2.getSecond(); Expression x1 = conv1.getFirst(), x2 = conv2.getFirst(); String s1 = String.valueOf(t1), s2 = String.valueOf(t2); TypeRef tr = null; if (bop.getOperator().givesBool) tr = typeRef(boolean.class); else { if (s1.equals(s2)) { tr = t1; } else { JavaPrim p1 = getPrimitive(t1, null), p2 = getPrimitive(t2, null); if (p1 != null && p2 != null) { switch (bop.getOperator()) { case LeftShift: case RightShift: case SignedRightShift: tr = t1; break; default: for (JavaPrim p : new JavaPrim[]{ JavaPrim.Double, JavaPrim.Float, JavaPrim.Long, JavaPrim.NativeSize, JavaPrim.NativeLong, JavaPrim.Int, JavaPrim.Short, JavaPrim.Byte }) { if (p1 == p || p2 == p) { if (promoteNativeLongToLong && (p == JavaPrim.NativeLong || p == JavaPrim.NativeSize)) { p = JavaPrim.Long; } tr = primRef(p); break; } } } } } } res = typed(expr(x1, ((BinaryOp) x).getOperator(), x2), tr); } } else if (x instanceof UnaryOp) { UnaryOperator op = ((UnaryOp) x).getOperator(); if (op == UnaryOperator.Not) { throw new UnsupportedConversionException(x, null); // TODO handle this properly ? } Pair<Expression, TypeRef> conv = convertExpressionToJava(((UnaryOp) x).getOperand(), libraryClassName, promoteNativeLongToLong); res = typed(expr(op, conv.getFirst()), conv.getSecond()); } else if (x instanceof Cast) { TypeRef tpe = ((Cast) x).getType(); Pair<Expression, TypeRef> casted = convertExpressionToJava(((Cast) x).getTarget(), libraryClassName, promoteNativeLongToLong); if (result.config.runtime.hasJNA) { TypeRef tr = convertTypeToJNA(tpe, TypeConversionMode.ExpressionType, libraryClassName); JavaPrim prim = getPrimitive(tr, libraryClassName); if (promoteNativeLongToLong && (prim == JavaPrim.NativeLong || prim == JavaPrim.NativeSize)) { prim = JavaPrim.Long; tr = typeRef(Long.TYPE); } res = typed(casted.getFirst(), tr); if (prim == JavaPrim.NativeLong) { res.setFirst((Expression) new New(typeRef(com.sun.jna.NativeLong.class), casted.getFirst())); } else if (prim == JavaPrim.NativeSize) { res.setFirst((Expression) new New(typeRef(NativeSize.class), casted.getFirst())); } } else { NL4JConversion conv = convertTypeToNL4J(tpe, libraryClassName, null, null, -1, -1); TypeRef tr = conv.typeRef; res = typed(casted.getFirst(), tr); if (conv.isPtr) { res.setFirst(methodCall(expr(typeRef(result.config.runtime.pointerClass)), "pointerToAddress", casted.getFirst())); } } } else if (x instanceof Constant) { Class<?> c = null; Constant jc = ((Constant) x).asJava(); switch (jc.getType()) { case Byte: c = Byte.TYPE; break; case Char: c = Character.TYPE; break; case Double: c = Double.TYPE; break; case Float: c = Float.TYPE; break; case Int: case UInt: case IntegerString: c = Integer.TYPE; break; case ULong: case Long: case LongString: c = Long.TYPE; break; case Short: c = Short.TYPE; break; case String: c = String.class; break; } if (c != null) { res = typed(((Constant) x).asJava(), typeRef(c)); } } else if (x instanceof VariableRef) { VariableRef fr = (VariableRef) x; Identifier name = fr.getName(); if (name != null) { Define define = result.defines.get(name); if (define != null && define.getValue() != null) { if (x.toString().equals(define.getValue().toString())) { res = null; // avoid some nasty loops } else { Expression defineValue = define.getValue(); if (defineValue instanceof Constant) { Constant constant = (Constant) defineValue; res = typed(findDefine(name), convertToJavaType(constant.getType())); } if (res == null) { res = convertExpressionToJava(defineValue, libraryClassName, promoteNativeLongToLong); } } } else { String sname = name.toString(); if (sname.equals("True") || sname.equals("true")) { res = typed(expr(Constant.Type.Bool, true), primRef(JavaPrim.Boolean)); } else if (sname.equals("False") || sname.equals("false")) { res = typed(expr(Constant.Type.Bool, false), primRef(JavaPrim.Boolean)); } else { EnumItem enumItem = result.enumItems.get(name); if (enumItem != null) { res = typed(findEnumItem(enumItem), typeRef(Integer.TYPE)); } else { VariablesDeclaration constant = result.globalVariablesByName.get(name); if (constant != null) { res = typed(varRef(findRef(name, constant, libraryClassName, true)), null); } else { res = typed(new VariableRef(name), null); } } } } } } else if (x instanceof FunctionCall) { FunctionCall fc = (FunctionCall) x; if ("sizeof".equals(String.valueOf(fc.getFunction())) && fc.getArguments().size() == 1) { TypeRefExpression typeEx = SyntaxUtils.as(fc.getArguments().get(0).getValue(), TypeRefExpression.class); if (typeEx != null) { res = typed(sizeofToJava(typeEx.getType(), libraryClassName), typeRef(Integer.TYPE)); } } } if (x instanceof TypeRefExpression) { TypeRefExpression tre = (TypeRefExpression) x; TypeRef tr = tre.getType(); if (tr instanceof SimpleTypeRef) { SimpleTypeRef str = (SimpleTypeRef) tr; Identifier ident = str.getName(); if (ident != null) { if (result.enumItemsFullName.contains(ident)) { res = typed(tre, typeRef(Integer.TYPE)); } } } if (res == null) { if (tr.isMarkedAsResolved()) { res = typed(tre, tr); } else { TypeRef conv = convertTypeToJNA(tr, TypeConversionMode.ExpressionType, libraryClassName); res = typed(new TypeRefExpression(conv), conv); } } } if (res == null) { // return convertExpressionToJava(x); throw new UnsupportedConversionException(x, null); } if (res.getFirst() == null) { return null; } res.getFirst().setParenthesis(x.getParenthesis()); return (Pair<Expression, TypeRef>) res; } public TypeRef convertToJavaType(Constant.Type type) { switch (type) { case Bool: return typeRef(Boolean.TYPE); case IntegerString: case UInt: case Int: return typeRef(Integer.TYPE); case LongString: case ULong: case Long: return typeRef(Long.TYPE); case Short: return typeRef(Short.TYPE); case Byte: return typeRef(Byte.TYPE); case Float: return typeRef(Float.TYPE); case Double: return typeRef(Double.TYPE); case String: return typeRef(String.class); default: return null; } } private Expression sizeofToJava(TypeRef type, Identifier libraryClassName) throws UnsupportedConversionException { type = resolveTypeDef(type, libraryClassName, true, false); // type = type; Expression res = null; if (type instanceof Pointer) { res = memberRef(expr(typeRef(result.config.runtime.pointerClass)), MemberRefStyle.Dot, "SIZE"); } else if (type instanceof ArrayRef) { res = sizeofToJava(((ArrayRef) type).getTarget(), libraryClassName); if (res == null) { return null; } ArrayRef ar = (ArrayRef) type; for (Expression x : ar.getDimensions()) { Expression c = convertExpressionToJava(x, libraryClassName, false).getFirst(); res = expr(res, Expression.BinaryOperator.Multiply, c); } } else if (type instanceof SimpleTypeRef || type instanceof Primitive) { JavaPrim prim = getPrimitive(type, libraryClassName); if (prim != null) { res = sizeof(prim); } else { Identifier structRef = findStructRef(((SimpleTypeRef) type).getName(), libraryClassName); if (structRef == null) { structRef = findStructRef(((SimpleTypeRef) type).getName().resolveLastSimpleIdentifier(), libraryClassName); } if (structRef != null) { return methodCall(new New(typeRef(structRef)), MemberRefStyle.Dot, "size"); } } } else if (type instanceof Struct) { Struct s = (Struct) type; if (s != null) { Identifier structName = result.declarationsConverter.getActualTaggedTypeName(s); Identifier structRef = findStructRef(structName, libraryClassName); if (structRef != null) { return methodCall(new New(typeRef(structRef)), MemberRefStyle.Dot, "size"); } else { for (Declaration d : s.getDeclarations()) { if (d instanceof VariablesDeclaration) { TypeRef varsType = d.getValueType(); for (Declarator sto : ((VariablesDeclaration) d).getDeclarators()) { Expression so = sizeofToJava(as(sto.mutateType(varsType), TypeRef.class), libraryClassName); if (so == null) { return null; } if (res == null) { res = so; } else { res = expr(res, Expression.BinaryOperator.Plus, so); } } } } } } } return res; } private Expression sizeof(JavaPrim prim) { return prim.size.sizeof(prim); } private Expression findEnumItem(EnumItem enumItem) { String library = result.getLibrary(enumItem); if (library == null) { return null; } Element parent = enumItem.getParentElement(); if (parent == null || !(parent instanceof Enum)) { return null; } Enum e = (Enum) parent; Identifier ident = ident(result.getLibraryClassFullName(library), result.declarationsConverter.getActualTaggedTypeName(e), ident(enumItem.getName())); return expr(typeRef(ident).setMarkedAsResolved(true)); } /// @see http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html public static Set<String> JAVA_KEYWORDS = new HashSet<String>(Arrays.asList( "null", "true", "false", "abstract", "continue", "for", "new", "switch", "assert", "default", "goto", "package", "synchronized", "boolean", "do", "if", "private", "this", "break", "double", "implements", "protected", "throw", "byte", "else", "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", "native", "super", "while", "wait" // not allowed for function names )); //static String keywords = " true false double float wait new null boolean return class public protected private "; public Identifier getValidJavaArgumentName(Identifier name) { return getValidJavaIdentifier(name); } public Identifier getValidJavaMethodName(Identifier name) { String nameStr = name.toString(); String newName = null; if (nameStr.matches("operator[^\\w]+")) { String op = nameStr.substring("operator".length()); //int nArgs = method.getArgs().size(); String suffix = null; java.lang.Enum<?> e = Expression.getAnyOperator(op); if (e == null) { if (op.equals("()")) { suffix = "parenthesis"; } else if (op.equals("[]")) { suffix = "brackets"; } else if (op.equals("->")) { suffix = "arrow"; } } else { suffix = e.name(); } if (suffix != null) { newName = "operator" + StringUtils.capitalize(suffix); } }/* else if (nameStr.startsWith("~")) { newName = getValidJavaIdentifierString(ident(nameStr.substring(1))) + "Destructor"; }*/ if (newName == null) { newName = getValidJavaIdentifierString(name); } else if (result.config.beautifyNames) { newName = beautify(newName); } return ident(newName); } String beautify(String name) { String newName = StringUtils.uncapitalize(StringUtils.underscoredToCamel(name)); if (name.endsWith("_")) { newName += "$"; } return newName; } public boolean isJavaKeyword(String name) { return JAVA_KEYWORDS.contains(name); } public Identifier getValidJavaIdentifier(Identifier name) { return ident(getValidJavaIdentifierString(name)); } public String getValidJavaIdentifierString(Identifier name) { if (name == null) { return null; } if (isJavaKeyword(name.toString())) { return name + "$"; } else { String newName = name.toString().replace('-', '_').replaceAll("[^\\w]", "\\$"); if (result.config.beautifyNames) { newName = beautify(newName); } return newName; } } public static String toPrimString(JavaPrim prim) { return prim.name; } public Expression getJavaClassLitteralExpression(TypeRef tr) { JavaPrim prim = result.typeConverter.getPrimitive(tr, null); return prim != null ? classLiteral(prim.type) : typeLiteral(tr.clone()); } public Expression getJavaClassLitteralExpression() { throw new UnsupportedOperationException(getClass().getName() + "." + toString() + " not handled !"); } }
libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/TypeConversion.java
/* Copyright (c) 2009 Olivier Chafik, All Rights Reserved This file is part of JNAerator (http://jnaerator.googlecode.com/). JNAerator is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. JNAerator is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with JNAerator. If not, see <http://www.gnu.org/licenses/>. */ package com.ochafik.lang.jnaerator; import static com.ochafik.lang.SyntaxUtils.as; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.classLiteral; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.expr; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.ident; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.memberRef; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.thisRef; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.cast; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.methodCall; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.staticField; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.thisField; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.typeRef; import static com.ochafik.lang.jnaerator.parser.ElementsHelper.varRef; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import java.nio.ShortBuffer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.TreeMap; import java.util.regex.Pattern; import org.rococoa.ObjCClass; import org.rococoa.ObjCObject; import org.rococoa.cocoa.foundation.NSObject; import org.bridj.FlagSet; import org.bridj.ValuedEnum; import org.bridj.SizeT; import org.bridj.ann.CLong; import org.bridj.ann.Ptr; import org.bridj.util.DefaultParameterizedType; import com.ochafik.lang.SyntaxUtils; import com.ochafik.lang.jnaerator.JNAeratorConfig.GenFeatures; import com.ochafik.lang.jnaerator.parser.Annotation; import com.ochafik.lang.jnaerator.parser.Arg; import com.ochafik.lang.jnaerator.parser.Declaration; import com.ochafik.lang.jnaerator.parser.Declarator; import com.ochafik.lang.jnaerator.parser.Define; import com.ochafik.lang.jnaerator.parser.Element; import com.ochafik.lang.jnaerator.parser.Enum; import com.ochafik.lang.jnaerator.parser.Expression; import com.ochafik.lang.jnaerator.parser.Function; import com.ochafik.lang.jnaerator.parser.Identifier; import com.ochafik.lang.jnaerator.parser.ModifiableElement; import com.ochafik.lang.jnaerator.parser.Modifier; import com.ochafik.lang.jnaerator.parser.ModifierType; import com.ochafik.lang.jnaerator.parser.ObjCppParser; import com.ochafik.lang.jnaerator.parser.Scanner; import com.ochafik.lang.jnaerator.parser.Struct; import com.ochafik.lang.jnaerator.parser.TypeRef; import com.ochafik.lang.jnaerator.parser.VariablesDeclaration; import com.ochafik.lang.jnaerator.parser.Declarator.ArrayDeclarator; import com.ochafik.lang.jnaerator.parser.Enum.EnumItem; import com.ochafik.lang.jnaerator.parser.Expression.AssignmentOp; import com.ochafik.lang.jnaerator.parser.Expression.AssignmentOperator; import com.ochafik.lang.jnaerator.parser.Expression.BinaryOp; import com.ochafik.lang.jnaerator.parser.Expression.BinaryOperator; import com.ochafik.lang.jnaerator.parser.Expression.Cast; import com.ochafik.lang.jnaerator.parser.Expression.Constant; import com.ochafik.lang.jnaerator.parser.Expression.EmptyArraySize; import com.ochafik.lang.jnaerator.parser.Expression.FunctionCall; import com.ochafik.lang.jnaerator.parser.Expression.MemberRef; import com.ochafik.lang.jnaerator.parser.Expression.MemberRefStyle; import com.ochafik.lang.jnaerator.parser.Expression.New; import com.ochafik.lang.jnaerator.parser.Expression.TypeRefExpression; import com.ochafik.lang.jnaerator.parser.Expression.UnaryOp; import com.ochafik.lang.jnaerator.parser.Expression.UnaryOperator; import com.ochafik.lang.jnaerator.parser.Expression.VariableRef; import com.ochafik.lang.jnaerator.parser.Identifier.QualifiedIdentifier; import com.ochafik.lang.jnaerator.parser.Identifier.SimpleIdentifier; import com.ochafik.lang.jnaerator.parser.StoredDeclarations.TypeDef; import com.ochafik.lang.jnaerator.parser.TypeRef.ArrayRef; import com.ochafik.lang.jnaerator.parser.TypeRef.FunctionSignature; import com.ochafik.lang.jnaerator.parser.TypeRef.Pointer; import com.ochafik.lang.jnaerator.parser.TypeRef.Primitive; import com.ochafik.lang.jnaerator.parser.TypeRef.SimpleTypeRef; import com.ochafik.lang.jnaerator.parser.TypeRef.TaggedTypeRef; import com.ochafik.lang.jnaerator.parser.TypeRef.TargettedTypeRef; import com.ochafik.lang.jnaerator.runtime.CGFloatByReference; import com.ochafik.lang.jnaerator.runtime.CharByReference; import com.ochafik.lang.jnaerator.runtime.NativeSize; import com.ochafik.lang.jnaerator.runtime.NativeSizeByReference; import com.ochafik.lang.jnaerator.runtime.globals.Global; import com.ochafik.lang.jnaerator.runtime.globals.GlobalByte; import com.ochafik.lang.jnaerator.runtime.globals.GlobalCGFloat; import com.ochafik.lang.jnaerator.runtime.globals.GlobalChar; import com.ochafik.lang.jnaerator.runtime.globals.GlobalDouble; import com.ochafik.lang.jnaerator.runtime.globals.GlobalFloat; import com.ochafik.lang.jnaerator.runtime.globals.GlobalInt; import com.ochafik.lang.jnaerator.runtime.globals.GlobalLong; import com.ochafik.lang.jnaerator.runtime.globals.GlobalNativeLong; import com.ochafik.lang.jnaerator.runtime.globals.GlobalNativeSize; import com.ochafik.lang.jnaerator.runtime.globals.GlobalShort; import com.ochafik.util.listenable.Pair; import com.ochafik.util.string.StringUtils; import com.sun.jna.Native; import com.sun.jna.WString; import com.sun.jna.ptr.ByReference; import com.sun.jna.ptr.ByteByReference; import com.sun.jna.ptr.DoubleByReference; import com.sun.jna.ptr.FloatByReference; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.LongByReference; import com.sun.jna.ptr.NativeLongByReference; import com.sun.jna.ptr.PointerByReference; import com.sun.jna.ptr.ShortByReference; public class TypeConversion implements ObjCppParser.ObjCParserHelper { Result result; public boolean allowUnknownPointers = true, allowFakePointers = false; public TypeConversion(Result result) { super(); this.result = result; initTypes(); } //public Set<Identifier> fakePointersSink; public enum TypeConversionMode { PrimitiveOrBufferParameter, NativeParameter, NativeParameterWithStructsPtrPtrs, FieldType, ReturnType, ExpressionType, StaticallySizedArrayField, PrimitiveReturnType, PointedValue } public Map<JavaPrim, Class<? extends ByReference>> primToByReference = new HashMap<JavaPrim, Class<? extends ByReference>>(); public Map<JavaPrim, Class<? extends Global>> primToGlobal = new HashMap<JavaPrim, Class<? extends Global>>(); public Map<JavaPrim, Class<? extends Buffer>> primToBuffer = new HashMap<JavaPrim, Class<? extends Buffer>>(); public final Set<String> byReferenceClassesNames = new HashSet<String>(); Map<String, JavaPrim> javaPrims = new TreeMap<String, JavaPrim>(); protected void prim(String from, JavaPrim to) { javaPrims.put(from, to); } public boolean isObjCppPrimitive(String s) { return javaPrims.containsKey(s); } public enum JavaPrim { Void(null, null, ESize.Zero), Char(Character.TYPE, Character.class, ESize.CharSize), Long(java.lang.Long.TYPE, java.lang.Long.class, ESize.Eight), Int(Integer.TYPE, Integer.class, ESize.Four), Short(java.lang.Short.TYPE, java.lang.Short.class, ESize.Two), Byte(java.lang.Byte.TYPE, java.lang.Byte.class, ESize.One), Boolean(java.lang.Boolean.TYPE, java.lang.Boolean.class, ESize.One), Float(java.lang.Float.TYPE, java.lang.Float.class, ESize.Four), Double(java.lang.Double.TYPE, java.lang.Double.class, ESize.Eight), NativeLong(com.sun.jna.NativeLong.class, com.sun.jna.NativeLong.class, ESize.StaticSizeField), NativeSize(NativeSize.class, NativeSize.class, ESize.StaticSizeField), NSInteger(org.rococoa.cocoa.foundation.NSInteger.class, org.rococoa.cocoa.foundation.NSInteger.class, ESize.StaticSizeField), NSUInteger(org.rococoa.cocoa.foundation.NSUInteger.class, org.rococoa.cocoa.foundation.NSUInteger.class, ESize.StaticSizeField), CGFloat(org.rococoa.cocoa.CGFloat.class, org.rococoa.cocoa.CGFloat.class, ESize.StaticSizeField); public final Class<?> type, wrapperType; public final String simpleName, name; public final boolean isPrimitive; public enum ESize { One(expr(1)), Two(expr(2)), Four(expr(4)), Eight(expr(8)), StaticSizeField(null) { @Override public Expression sizeof(JavaPrim p) { return staticField(p.type, "SIZE"); } }, CharSize(null) { @Override public Expression sizeof(JavaPrim p) { return staticField(Native.class, "WCHAR_SIZE"); } }, Zero(expr(0)); private final Expression sizeOfExpression; ESize(Expression sizeOfExpression) { this.sizeOfExpression = sizeOfExpression; } public Expression sizeof(JavaPrim p) { return sizeOfExpression.clone(); } } public final ESize size; private static Map<String, JavaPrim> nameToPrim; public static JavaPrim getJavaPrim(String name) { if (nameToPrim == null) { nameToPrim = new HashMap<String, JavaPrim>(); for (JavaPrim p : values()) { nameToPrim.put(p.simpleName, p); } } return nameToPrim.get(name); } JavaPrim(Class<?> type, Class<?> wrapperType, ESize size) { this.type = type; this.wrapperType = wrapperType; this.size = size; this.name = type == null ? "void" : type.getName(); this.isPrimitive = type == null || type.isPrimitive(); this.simpleName = type == null ? "void" : type.getSimpleName(); } } public Expression typeLiteral(TypeRef c) { if (c instanceof SimpleTypeRef && result.config.runtime == JNAeratorConfig.Runtime.BridJ) { Identifier id = ((SimpleTypeRef) c).getName(); SimpleIdentifier sid = id.resolveLastSimpleIdentifier(); if (!sid.getTemplateArguments().isEmpty()) { Identifier erased = id.eraseTemplateArguments(); List<Expression> exprs = new ArrayList<Expression>(); exprs.add(typeLiteral(typeRef(erased.clone()))); for (Expression t : sid.getTemplateArguments()) { if (t instanceof Expression.TypeRefExpression) { exprs.add(typeLiteral(((Expression.TypeRefExpression) t).getType().clone())); } } return methodCall(expr(typeRef(DefaultParameterizedType.class)), "paramType", exprs.toArray(new Expression[exprs.size()])); } } return memberRef(expr(c), MemberRefStyle.Dot, "class"); } public void initTypes() { prim("void", JavaPrim.Void); prim("UTF32Char", JavaPrim.Char); prim("unichar", JavaPrim.Char); prim("int64_t", JavaPrim.Long); prim("uint64_t", JavaPrim.Long); prim("u_int64_t", JavaPrim.Long); prim("long long", JavaPrim.Long); prim("long long int", JavaPrim.Long); prim("long int", JavaPrim.Int); prim("LONGLONG", JavaPrim.Long); prim("ULONGLONG", JavaPrim.Long); prim("INT", JavaPrim.Int); prim("UINT", JavaPrim.Int); prim("SHORT", JavaPrim.Short); prim("USHORT", JavaPrim.Short); prim("BYTE", JavaPrim.Byte); prim("UBYTE", JavaPrim.Byte); prim("DOUBLE", JavaPrim.Double); prim("FLOAT", JavaPrim.Float); prim("WORD", JavaPrim.Short); prim("DWORD", JavaPrim.Int); if (result.config.runtime == JNAeratorConfig.Runtime.BridJ) prim("BOOL", JavaPrim.Int); else prim("BOOL", JavaPrim.Boolean); prim("DWORD64", JavaPrim.Long); prim("LONG64", JavaPrim.Long); prim("UInt64", JavaPrim.Long); prim("SInt64", JavaPrim.Long); prim("__int64", JavaPrim.Long); prim("__int64_t", JavaPrim.Long); prim("int32_t", JavaPrim.Int); prim("uint32_t", JavaPrim.Int); prim("__int32_t", JavaPrim.Int); prim("__uint32_t", JavaPrim.Int); prim("u_int32_t", JavaPrim.Int); prim("uint32", JavaPrim.Int); prim("int32", JavaPrim.Int); prim("int", JavaPrim.Int); //prim("NSUInteger", JavaPrim.NativeSize); //prim("NSInteger", JavaPrim.NativeSize); prim("SInt32", JavaPrim.Int); prim("UInt32", JavaPrim.Int); prim("GLint", JavaPrim.Int); prim("GLuint", JavaPrim.Int); prim("GLenum", JavaPrim.Int); prim("GLsizei", JavaPrim.Int); prim("__darwin_size_t", JavaPrim.Int); prim("__int32", JavaPrim.Int); prim("NSInteger", JavaPrim.NSInteger); prim("NSUInteger", JavaPrim.NSUInteger); prim("CGFloat", JavaPrim.CGFloat); JavaPrim longPrim = result.config.gccLong ? JavaPrim.NativeSize : JavaPrim.NativeLong; prim("long", longPrim); prim("LONG", longPrim); prim("ULONG", longPrim); JavaPrim sizePrim = result.config.sizeAsLong ? longPrim : JavaPrim.NativeSize; prim("size_t", sizePrim); prim("ptrdiff_t", sizePrim); prim("int16_t", JavaPrim.Short); prim("uint16_t", JavaPrim.Short); prim("__int16_t", JavaPrim.Short); prim("__uint16_t", JavaPrim.Short); prim("u_int16_t", JavaPrim.Short); prim("uint16", JavaPrim.Short); prim("int16", JavaPrim.Short); prim("SInt16", JavaPrim.Short); prim("UInt16", JavaPrim.Short); prim("short", JavaPrim.Short); prim("WCHAR", JavaPrim.Short); prim("wchar_t", result.config.wcharAsShort ? JavaPrim.Short : JavaPrim.Char); prim("__int16", JavaPrim.Short); prim("int8_t", JavaPrim.Byte); prim("uint8_t", JavaPrim.Byte); prim("u_int8_t", JavaPrim.Byte); prim("__uint8_t", JavaPrim.Byte); prim("__int8_t", JavaPrim.Byte); prim("SInt8", JavaPrim.Byte); prim("UInt8", JavaPrim.Byte); prim("char", JavaPrim.Byte); prim("unsigned char", JavaPrim.Byte); prim("__unsigned char", JavaPrim.Byte); prim("signed char", JavaPrim.Byte); prim("__signed char", JavaPrim.Byte); prim("SignedByte", JavaPrim.Byte); prim("__int8", JavaPrim.Byte); prim("float", JavaPrim.Float); prim("NSFloat", JavaPrim.Float); prim("CGFloat", JavaPrim.Float); prim("double_t", JavaPrim.Double); prim("double", JavaPrim.Double); prim("NSDouble", JavaPrim.Double); prim("CGDouble", JavaPrim.Double); prim("bool", JavaPrim.Boolean); prim("Boolean", JavaPrim.Boolean); prim("boolean_t", JavaPrim.Boolean); primToByReference.put(JavaPrim.Int, IntByReference.class); primToByReference.put(JavaPrim.Char, CharByReference.class); primToByReference.put(JavaPrim.Short, ShortByReference.class); primToByReference.put(JavaPrim.Byte, ByteByReference.class); primToByReference.put(JavaPrim.Long, LongByReference.class); primToByReference.put(JavaPrim.Float, FloatByReference.class); primToByReference.put(JavaPrim.Double, DoubleByReference.class); primToByReference.put(JavaPrim.NativeLong, NativeLongByReference.class); primToByReference.put(JavaPrim.NativeSize, NativeSizeByReference.class); primToByReference.put(JavaPrim.NSInteger, NativeSizeByReference.class); primToByReference.put(JavaPrim.NSUInteger, NativeSizeByReference.class); primToByReference.put(JavaPrim.CGFloat, CGFloatByReference.class); //primsByReference.put(JavaPrim.Void, PointerByReference.class); for (Class<?> c : primToByReference.values()) { byReferenceClassesNames.add(c.getName()); } // byReferenceClassesNames.add(PointerByReference.class.getName()); primToGlobal.put(JavaPrim.Int, GlobalInt.class); primToGlobal.put(JavaPrim.Char, GlobalChar.class); primToGlobal.put(JavaPrim.Short, GlobalShort.class); primToGlobal.put(JavaPrim.Byte, GlobalByte.class); primToGlobal.put(JavaPrim.Long, GlobalLong.class); primToGlobal.put(JavaPrim.Float, GlobalFloat.class); primToGlobal.put(JavaPrim.Double, GlobalDouble.class); primToGlobal.put(JavaPrim.NativeLong, GlobalNativeLong.class); primToGlobal.put(JavaPrim.NativeSize, GlobalNativeSize.class); primToGlobal.put(JavaPrim.NSInteger, GlobalNativeSize.class); primToGlobal.put(JavaPrim.NSUInteger, GlobalNativeSize.class); primToGlobal.put(JavaPrim.CGFloat, GlobalCGFloat.class); primToBuffer.put(JavaPrim.Int, IntBuffer.class); primToBuffer.put(JavaPrim.Char, CharBuffer.class); primToBuffer.put(JavaPrim.Short, ShortBuffer.class); primToBuffer.put(JavaPrim.Byte, ByteBuffer.class); primToBuffer.put(JavaPrim.Long, LongBuffer.class); primToBuffer.put(JavaPrim.Float, FloatBuffer.class); primToBuffer.put(JavaPrim.Double, DoubleBuffer.class); //primToBuffer.put(JavaPrim.NativeLong, NativeLongByReference.class); } Map<String, TypeRef> manualTypeDefs = new HashMap<String, TypeRef>(); public Pair<TypeDef, Declarator> getTypeDef(Identifier name) { if (name == null) { return null; } Pair<TypeDef, Declarator> p = result.typeDefs.get(name); if (p == null) { return null; } Declarator value = p.getValue(); String rname = value == null ? null : value.resolveName(); if (rname != null) { if (name.equals("id")) { return null; } if (name.equals("SEL")) { return null; } if (name.equals("IMP")) { return null; } if (name.equals("Class")) { return null; } if (name.equals("BOOL")) { if (rname.equals("byte")) { return null; } } } return p; } public TypeRef resolveTypeDef(TypeRef valueType, final Identifier libraryClassName, final boolean convertToJavaRef, final boolean convertEnumToJavaRef) { if (valueType == null) { return null; } // if (valueType.toString().equals("CGFunctionEvaluateCallback")) // valueType = valueType; if (valueType instanceof TaggedTypeRef && convertToJavaRef) { TaggedTypeRef ttr = (TaggedTypeRef) valueType; if (ttr.getTag() != null) { TypeRef ref = ttr instanceof Struct ? typeRef(findStructRef(ttr.getTag(), libraryClassName)) : ttr instanceof Enum && convertEnumToJavaRef ? findEnum(ttr.getTag(), libraryClassName) : null; if (ref == null && convertEnumToJavaRef) { return ref; } } } final TypeRef valueTypeCl = valueType.clone(); Arg holder = new Arg(); holder.setValueType(valueTypeCl); valueTypeCl.accept(new Scanner() { java.util.Stack<String> names = new java.util.Stack<String>(); int depth = 0; @Override public void visitSimpleTypeRef(SimpleTypeRef simpleTypeRef) { depth++; try { Identifier name = ((SimpleTypeRef) simpleTypeRef).getName(); if (name == null) { return; } String nameStr = name.toString(); if (nameStr == null) { return; } if (JavaPrim.getJavaPrim(nameStr) != null) { return; } if (names.contains(nameStr)) { return; } names.push(nameStr); try { if (resolvesToPrimitive(nameStr)) { return; } super.visitSimpleTypeRef(simpleTypeRef); if (simpleTypeRef.isMarkedAsResolved()) { return; } // Identifier oc = findObjCClassIdent(name); // if (oc != null) { // name.replaceBy(oc); // } Pair<TypeDef, Declarator> p = getTypeDef(name); if (p != null) { TypeRef tr = p.getFirst().getValueType();//as(p.getSecond().mutateType(p.getFirst().getValueType()), TypeRef.class); if (tr instanceof Enum && !convertEnumToJavaRef) { simpleTypeRef.replaceBy(typeRef(int.class)); return; } if (tr instanceof TaggedTypeRef) { Identifier name2 = result.declarationsConverter.getActualTaggedTypeName((TaggedTypeRef) tr); if (name2 != null) { name = name2; } } if (convertToJavaRef) { if (tr instanceof TaggedTypeRef) { TaggedTypeRef s = (TaggedTypeRef) tr; if (s.isForwardDeclaration()) { return; } // if (tr instanceof Enum) { // tr = typeRef(s.getTag().clone()); // } else { Identifier ident = result.getTaggedTypeIdentifierInJava(s); if (ident != null) { tr = typeRef(ident);//findRef(name, s, libraryClassName)); }// } } else if (tr instanceof FunctionSignature) { tr = findCallbackRef((FunctionSignature) tr, libraryClassName); } } String strs = simpleTypeRef.toString(); String trs = tr == null ? null : tr.toString(); if (trs != null && !strs.equals(trs)) { TypeRef clo = tr.clone(); simpleTypeRef.replaceBy(clo); if (depth < 30) { clo.accept(this); } else { System.err.println("Infinite loop in type conversion ? " + tr); } } return; } TypeRef manualTypeRef = manualTypeDefs.get(name); if (manualTypeRef != null) { if (!convertToJavaRef) { return; } simpleTypeRef.replaceBy(manualTypeRef); return; } TypeRef structRef = typeRef(result.typeConverter.findStructRef(name, libraryClassName)); if (structRef != null) { if (!convertToJavaRef) { return; } simpleTypeRef.replaceBy(structRef); } TypeRef enumRef = result.typeConverter.findEnum(name, libraryClassName); if (enumRef != null) { if (!convertToJavaRef || !convertEnumToJavaRef) { return; } simpleTypeRef.replaceBy(enumRef); } Define define = result.defines.get(name); Expression expression = define == null ? null : define.getValue(); if (expression != null) { if (!convertToJavaRef) { return; } Identifier fieldName = null; if (expression instanceof Expression.VariableRef) { fieldName = ((Expression.VariableRef) expression).getName(); } else if (expression instanceof MemberRef) { fieldName = ((MemberRef) expression).getName(); } if (fieldName != null && !fieldName.equals(name)) { simpleTypeRef.replaceBy(resolveTypeDef(new TypeRef.SimpleTypeRef(fieldName), libraryClassName, true /*convertToJavaRef*/, convertEnumToJavaRef)); return; } } } finally { names.pop(); } } finally { depth--; } } }); TypeRef tr = holder.getValueType(); // tr.setParentElement(valueType.getParentElement()); return tr;// == null ? null : tr.clone(); } public boolean resolvesToPrimitive(String name) { return javaPrims.containsKey(name); } // TypeRef getPrimitiveRef(TypeRef valueType, String callerLibraryClass) { // JavaPrim prim = getPrimitive(valueType, callerLibraryClass); // if (prim == null) // return null; // // TypeRef tr = typeRef(prim); // if (valueType.isUnsigned()) // tr.addAnnotation(new Annotation(Unsigned.class)); // if (valueType.isUnsigned()) // tr.addAnnotation(new Annotation(Unsigned.class)); // // return tr; // } public static class JavaPrimitive extends Primitive { JavaPrim javaPrim; public JavaPrimitive() { } public JavaPrimitive(JavaPrim javaPrim) { super(); setName(ident(javaPrim == JavaPrim.Void ? Void.TYPE : javaPrim.type)); this.javaPrim = javaPrim; } public JavaPrim getJavaPrim() { return javaPrim; } public void setJavaPrim(JavaPrim javaPrim) { this.javaPrim = javaPrim; } } public JavaPrim getPrimitive(TypeRef valueType, Identifier libraryClassName) { valueType = resolveTypeDef(valueType, libraryClassName, true, true); if (valueType == null) { return null; } Identifier name = null; List<Modifier> mods = valueType.getModifiers(); int longCount = ModifierType.Long.countIn(mods); if (valueType instanceof JavaPrimitive) { return ((JavaPrimitive) valueType).getJavaPrim(); } if (valueType instanceof Primitive) { name = ((Primitive) valueType).getName(); if (name == null) { if (longCount == 1) { name = ident("long"); } else if (longCount > 1) { name = ident("long long"); } else if (valueType.hasModifier(ModifierType.Short)) { name = ident("short"); } else { name = ident("int"); } } } else if (valueType instanceof SimpleTypeRef) { name = ((SimpleTypeRef) valueType).getName(); } if (name == null) { return null; } JavaPrim p = JavaPrim.getJavaPrim(name.toString()); if (p != null && !p.isPrimitive) { return p; } boolean isLong = false; String str; if ((isLong = valueType.getModifiers().contains("long")) || valueType.getModifiers().contains("short")) { str = (isLong ? "long " : "short ") + name; } else { str = name.toString(); } JavaPrim type = javaPrims.get(str); if (type == JavaPrim.Int && longCount > 1) { return JavaPrim.Long; } return type; } public Identifier findStructRef(Identifier name, Identifier libraryClassName) { return findStructRef(result.structsByName.get(name), name, libraryClassName); } public Identifier findStructRef(Struct s, Identifier name, Identifier libraryClassName) { if (s == null || s.isForwardDeclaration()) { Pair<TypeDef, Declarator> pair = getTypeDef(name); if (pair == null) { return null; } if (pair.getFirst() == null || pair.getSecond() == null) { return null; } Object td = pair.getSecond().mutateType(pair.getFirst().getValueType()); if (!(td instanceof Struct)) { return null; } s = (Struct) td; } if (s == null && result.config.runtime == JNAeratorConfig.Runtime.BridJ) { String ns = name.toString(); Class<?> cl = null; if (ns.equals("IUnknown")) cl = org.bridj.cpp.com.IUnknown.class; else if (ns.equals("GUID")) cl = org.bridj.cpp.com.GUID.class; else if (ns.equals("RECT")) cl = org.bridj.cpp.com.RECT.class; if (cl != null) return ident(cl); } return result.getTaggedTypeIdentifierInJava(s); /* name = result.declarationsConverter.getActualTaggedTypeName((TaggedTypeRef) pair.getFirst().getValueType()); return findRef(name, s, libraryClassName, !result.config.putTopStructsInSeparateFiles); } else { return result.getTaggedTypeIdentifierInJava(s); //name = result.declarationsConverter.getActualTaggedTypeName(s); }*/ } public Identifier findStructRef(Struct s, Identifier libraryClassName) { switch (s.getType()) { case ObjCClass: case ObjCProtocol: return result.objectiveCGenerator.getFullClassName(s); default: return findStructRef(s, result.declarationsConverter.getActualTaggedTypeName(s), libraryClassName); } } // public String find(String name, Element e, String callerLibraryClass) { // if (e == null) // return null; // String library = result.getLibrary(e); // if (library == null) // return null; // SimpleIdentifier libClass = result.getLibraryClassFullName(library); // return SyntaxUtils.equal(libClass, callerLibraryClass) ? name : libClass + "." + name; // } public Identifier libMember(Identifier libClass, Identifier libraryClassName, Identifier member) { //return ident(SyntaxUtils.equal(libClass, libraryClassName) ? null : libClass, member); return ident(libClass, member); //return member; //TODODODODODODODODOoOOOOO } public Identifier findRef(Identifier name, Element e, Identifier libraryClassName, boolean inLibClass) { if (e == null || !name.isPlain()) { return null; } String library = result.getLibrary(e); if (library == null) { return null; } // e = e.getParentElement(); Struct parentStruct = e instanceof Struct ? (Struct) e : e.findParentOfType(Struct.class); if (!inLibClass && parentStruct != null) { if (parentStruct == e) { return ident(result.getLibraryPackage(library), name); } return ident(result.getTaggedTypeIdentifierInJava(parentStruct), name); } return libMember(result.getLibraryClassFullName(library), libraryClassName, name); } public SimpleTypeRef findEnum(Identifier name, Identifier libraryClassName) { Enum s = result.enumsByName.get(name); if (s == null) { return null; } return findEnumRef(s, libraryClassName); } public SimpleTypeRef findEnumRef(Enum s, Identifier libraryClassName) { if (result.config.runtime == JNAeratorConfig.Runtime.BridJ) return typeRef(result.getTaggedTypeIdentifierInJava(s)); Identifier name = result.declarationsConverter.getActualTaggedTypeName(s); String library = result.getLibrary(s); if (library == null) { return null; } Identifier libClass = result.getLibraryClassFullName(library); //return new SimpleTypeRef(SyntaxUtils.equal(libClass, callerLibraryClass) ? name : libClass + "." + name); /*if (result.config.runtime == JNAeratorConfig.Runtime.BridJ) { return typeRef(findRef(name, s, libraryClassName, result.config.putTopStructsInSeparateFiles)); }*/ SimpleTypeRef tr = new SimpleTypeRef("int"); if (result.config.features.contains(JNAeratorConfig.GenFeatures.EnumTypeLocationComments)) { tr.setCommentBefore("@see " + (SyntaxUtils.equal(libClass, libraryClassName) ? name : libClass + "#" + name)); } // if (s.getTag() != null) // tr.setCommentBefore("@see enums in " + s.getTag()); return tr; } public static Expression javaStaticFieldRef(Identifier javaClass, Identifier fieldName) { return memberRef( expr(typeRef(javaClass)), MemberRefStyle.Dot, fieldName); } public Expression findDefine(Identifier name) { Define s = result.defines.get(name); String library = s == null ? null : result.getLibrary(s); return library == null ? null : javaStaticFieldRef(result.getLibraryClassFullName(library), name); } public Identifier inferCallBackName(FunctionSignature functionSignature, boolean prependNamespaces, boolean qualify, Identifier libraryClassName) { List<String> nameElements = new ArrayList<String>(); Identifier name = functionSignature.getFunction().getName(); if (name != null) { name = name.clone(); } Identifier parentIdent = null; Element parent = functionSignature.getParentElement(); boolean firstParent = true; while (parent != null) { if (parent instanceof Struct) { parentIdent = findStructRef((Struct) parent, null); break; } else if (firstParent) { if (name == null && parent instanceof TypeDef) { Declarator simpleSto = null; for (Declarator sto : ((TypeDef) parent).getDeclarators()) { String stoName = sto.resolveName(); if (stoName == null) { continue; } if (!(sto instanceof ArrayDeclarator)) { boolean weirdName = stoName.startsWith("_") || stoName.endsWith("_"); if (simpleSto == null || (simpleSto.resolveName().startsWith("_") || simpleSto.resolveName().endsWith("_")) && !weirdName) { simpleSto = sto; } if (!weirdName) { break; } } if (stoName != null) { name = new SimpleIdentifier(stoName); } } } else if (name == null && parent instanceof Arg) { Arg arg = (Arg) parent; Function f = SyntaxUtils.as(arg.getParentElement(), Function.class); if (f != null) { name = new SimpleIdentifier(f.getName() + "_" + arg.getName()); break; } } else if (firstParent) { // if (//parent instanceof VariablesDeclaration || // parent instanceof FunctionPointerDeclaration // //|| parent instanceof TypeDef // ) { // nameElements.add("Callback"); // } } } parent = parent.getParentElement(); firstParent = false; } if (qualify && parentIdent == null) { //if (libraryClassName != null) // parentIdent = libraryClassName; //else { String library = result.getLibrary(functionSignature); if (library != null) { parentIdent = result.getLibraryClassFullName(library); } //} } if (prependNamespaces) { if (name == null) { name = new SimpleIdentifier("callback"); } nameElements.add(name.toString()); return ident(qualify ? parentIdent : null, StringUtils.implode(nameElements, "_")); } else { return ident(qualify ? parentIdent : null, name); } } public TypeRef findCallbackRef(Identifier name, Identifier libraryClassName) { FunctionSignature s = result.callbacksByName.get(name); if (s == null) { return null; } // Struct parentStruct = s.findParentOfType(Struct.class); // if (parentStruct != null && (parentStruct.getType() == Struct.Type.ObjCClass || parentStruct.getType() == Struct.Type.ObjCProtocol)) { // //Identifier structName = result.declarationsConverter.getActualTaggedTypeName(parentStruct); // return //result.result.getObjCClass(parentStruct.getName()). // typeRef(//libMember(structName, libraryClassName, // inferCallBackName(s, true, true)//) // ); // } return findCallbackRef(s, libraryClassName); } public TypeRef findCallbackRef(FunctionSignature s, Identifier callerLibraryClass) { String library = result.getLibrary(s); if (library == null) { return null; } // Struct parentStruct = s.findParentOfType(Struct.class); // if (parentStruct != null && (parentStruct.getType() == Struct.Type.ObjCClass || parentStruct.getType() == Struct.Type.ObjCProtocol)) { // Identifier structName = result.declarationsConverter.getActualTaggedTypeName(parentStruct); // return // typeRef(ident(structName, inferCallBackName(s, true, true))); // } return typeRef(inferCallBackName(s, true, true, callerLibraryClass)); // return typeRef(libMember(result.getLibraryClassFullName(library), callerLibraryClass, inferCallBackName(s, true, true))); //typeRef(ident(result.getLibraryClassFullName(library), inferCallBackName(s, true))); } static TypeRef primRef(JavaPrim p) { if (p == null) { return null; } return new JavaPrimitive(p); // return new SimpleTypeRef(toString(p)); } boolean isResolved(SimpleTypeRef tr) { return tr != null && (tr.isMarkedAsResolved() || isResolved(tr.getName())); } boolean isResolved(Identifier i) { if (i == null || i.isPlain()) { return false; } return (i instanceof Identifier.QualifiedIdentifier) && Identifier.QualificationSeparator.Dot.equals(((Identifier.QualifiedIdentifier) i).getSeparator()); } public enum ConvType { Enum, Pointer, Primitive, Struct, NativeLong, NativeSize, Void, Callback } public class NL4JConversion { public ConvType type; public TypeRef typeRef, indirectType; public List<Expression> arrayLengths; public Expression bits; public Expression getExpr, setExpr; public boolean wideString, readOnly, isPtr, byValue, nativeSize, cLong, isUndefined; public Charset charset; public final List<Annotation> annotations = new ArrayList<Annotation>(); //public String structIOFieldGetterNameRadix; public String pointerFieldGetterNameRadix; public Expression arrayLength() { Expression length = null; for (Expression m : arrayLengths) { m.setParenthesis(true); if (length == null) length = m.clone(); else length = expr(length, BinaryOperator.Multiply, m.clone()); } return length.setParenthesis(arrayLengths.size() > 1); } public TypeRef getIndirectTypeRef() { if (type == ConvType.Void) { return typeRef(ident("?")); } if (result.config.runtime == JNAeratorConfig.Runtime.BridJ) { if (type == ConvType.NativeSize) { return typeRef(SizeT.class); } if (type == ConvType.NativeLong) { return typeRef(org.bridj.CLong.class); } } TypeRef t = indirectType == null ? typeRef : indirectType; return t == null ? null : t.clone(); } public <M extends ModifiableElement> M annotateRawType(M element) throws UnsupportedConversionException { element.addAnnotations(annotations); if (type != null) { switch (type) { case Enum: case Primitive: case Void: break; case NativeLong: element.addAnnotation(new Annotation(CLong.class)); break; case NativeSize: element.addAnnotation(new Annotation(Ptr.class)); break; case Pointer: element.addAnnotation(new Annotation(Ptr.class)); break; case Struct: //throw new UnsupportedConversionException(typeRef, "Struct by value not supported yet"); break; default: throw new UnsupportedConversionException(typeRef, "Not supported"); } } return element; } public <M extends ModifiableElement> M annotateTypedType(M element) throws UnsupportedConversionException { element.addAnnotations(annotations); if (type != ConvType.Pointer) { annotateRawType(element); } return element; } } static Map<String, Pair<Integer, Class<?>>> buffersAndArityByType = new HashMap<String, Pair<Integer, Class<?>>>(); static Map<String, Pair<Integer, Class<?>>> arraysAndArityByType = new HashMap<String, Pair<Integer, Class<?>>>(); static Map<String, String> pointerFieldGetterNameRadixByType = new HashMap<String, String>(); static { Object[] data = new Object[]{ "char", Byte.TYPE, byte[].class, ByteBuffer.class, "Char", "long", Long.TYPE, long[].class, LongBuffer.class, "Long", "int", Integer.TYPE, int[].class, IntBuffer.class, "Int", "short", Short.TYPE, short[].class, ShortBuffer.class, "Short", "wchar_t", Character.TYPE, char[].class, CharBuffer.class, "WChar", "double", Double.TYPE, double[].class, DoubleBuffer.class, "Double", "float", Float.TYPE, float[].class, FloatBuffer.class, "Float", "bool", Boolean.TYPE, boolean[].class, null, "Bool" }; for (int arity : new int[]{1, 2, 4, 8, 16}) { String suffix = arity == 1 ? "" : arity + ""; for (int i = 0; i < data.length; i += 5) { String rawType = (String) data[i]; Class<?> scalClass = (Class<?>) data[i + 1]; Class<?> arrClass = (Class<?>) data[i + 2]; Class<?> buffClass = (Class<?>) data[i + 3]; String radix = (String) data[i + 4]; Pair<Integer, Class<?>> buffPair = new Pair<Integer, Class<?>>(arity, arity == 1 ? scalClass : buffClass), arrPair = new Pair<Integer, Class<?>>(arity, arity == 1 ? scalClass : arrClass); for (String type : new String[]{rawType + suffix, "u" + rawType + suffix}) { buffersAndArityByType.put(type, buffPair); arraysAndArityByType.put(type, arrPair); pointerFieldGetterNameRadixByType.put(type, radix); } } } } public NL4JConversion convertTypeToNL4J(TypeRef valueType, Identifier libraryClassName, Expression structIOExpr, Expression valueExpr, int fieldIndex, int bits) throws UnsupportedConversionException { TypeRef original = valueType; //if (valueType != null && valueType.toString().contains("MonoDomain")) // valueType = (TypeRef)valueType; valueType = resolveTypeDef(valueType, libraryClassName, true, true); //Expression offsetExpr = structIOExpr == null ? null : methodCall(structIOExpr, "getFieldOffset", expr(fieldIndex)); //Expression bitOffsetExpr = structIOExpr == null || bits <= 0 ? null : methodCall(structIOExpr, "getFieldBitOffset", expr(fieldIndex)); //Expression bitLengthExpr = structIOExpr == null || bits <= 0 ? null : methodCall(structIOExpr, "getFieldBitLength", expr(fieldIndex)); NL4JConversion conv = new NL4JConversion(); if (valueType == null) { conv.type = ConvType.Void; conv.typeRef = primRef(JavaPrim.Void); return conv; } //if (valueType instanceof Struct) // valueType = typeRef(findStructRef((Struct)valueType, libraryClassName)); if (valueType instanceof TargettedTypeRef) { TypeRef targetRef = ((TargettedTypeRef) valueType).getTarget(); if (valueType instanceof Pointer.ArrayRef) { Pointer.ArrayRef arrayRef = (Pointer.ArrayRef) valueType; List<Expression> sizes = new ArrayList<Expression>(); for (Expression dim : arrayRef.flattenDimensions()) { if (dim == null || dim instanceof EmptyArraySize) continue; Expression m = result.typeConverter.convertExpressionToJava(dim, libraryClassName, false).getFirst(); m.setParenthesis(false); sizes.add(m); } if (!sizes.isEmpty()) conv.arrayLengths = sizes; } try { NL4JConversion targetConv = convertTypeToNL4J(targetRef, libraryClassName, null, null, -1, -1); //if (result.isFakePointer(libraryClassName)) if (targetConv.isUndefined && allowFakePointers && original instanceof SimpleTypeRef) { conv.isPtr = true; conv.type = ConvType.Pointer; conv.typeRef = typeRef(result.getFakePointer(libraryClassName, ((SimpleTypeRef)original).getName().clone())); if (structIOExpr != null) { if (conv.arrayLengths == null) conv.setExpr = methodCall(structIOExpr.clone(), "setPointerField", thisRef(), expr(fieldIndex), valueExpr); conv.getExpr = methodCall(structIOExpr.clone(), "getTypedPointerField", thisRef(), expr(fieldIndex)); } return conv; } TypeRef pointedTypeRef = targetConv.getIndirectTypeRef(); if (targetConv.type != ConvType.Void) { if (targetConv.type == ConvType.NativeSize) pointedTypeRef = typeRef(SizeT.class); else if (targetConv.type == ConvType.NativeLong) pointedTypeRef = typeRef(CLong.class); } if (pointedTypeRef != null) { conv.isPtr = true; conv.type = ConvType.Pointer; conv.typeRef = typeRef(ident(result.config.runtime.pointerClass, expr(pointedTypeRef.clone()))); if (structIOExpr != null) { if (conv.arrayLengths == null) conv.setExpr = methodCall(structIOExpr.clone(), "setPointerField", thisRef(), expr(fieldIndex), valueExpr); conv.getExpr = methodCall(structIOExpr.clone(), "getPointerField", thisRef(), expr(fieldIndex)); } return conv; } } catch (UnsupportedConversionException ex) { conv.isPtr = true; conv.type = ConvType.Pointer; conv.typeRef = typeRef(result.config.runtime.pointerClass); return conv; /*if (valueType instanceof TypeRef.Pointer && targetRef instanceof SimpleTypeRef && allowFakePointers) { conv.typeRef = typeRef(result.getFakePointer(libraryClassName, ((SimpleTypeRef)targetRef).getName().clone())); if (structIOExpr != null) { if (conv.arrayLengths == null) conv.setExpr = methodCall(structIOExpr.clone(), "setPointerField", thisRef(), expr(fieldIndex), valueExpr); conv.getExpr = methodCall(structIOExpr.clone(), "getTypedPointerField", thisRef(), expr(fieldIndex)); } return conv; }//*/ /*if (valueType instanceof TypeRef.Pointer && targetRef instanceof SimpleTypeRef && allowFakePointers) { conv.typeRef = typeRef(ident(result.config.runtime.pointerClass, expr(typeRef(result.getUndefinedType(libraryClassName, ((SimpleTypeRef)targetRef).getName().clone()))))); if (structIOExpr != null) { if (conv.arrayLengths == null) conv.setExpr = methodCall(structIOExpr.clone(), "setPointerField", thisRef(), expr(fieldIndex), valueExpr); conv.getExpr = methodCall(structIOExpr.clone(), "getTypedPointerField", thisRef(), expr(fieldIndex)); } return conv; }*/ } } else {//if (valueType instanceof SimpleTypeRef || valueType instanceof TaggedTypeRef || valueType) { JavaPrim prim = getPrimitive(valueType, libraryClassName); if (prim != null) { String radix; switch (prim) { case NativeLong: conv.type = ConvType.NativeLong; conv.typeRef = typeRef(Long.TYPE); conv.indirectType = typeRef(org.bridj.CLong.class); radix = "CLong"; break; case NativeSize: conv.type = ConvType.NativeSize; conv.typeRef = typeRef(Long.TYPE); conv.indirectType = typeRef(org.bridj.SizeT.class); radix = "SizeT"; break; case Void: conv.type = ConvType.Void; conv.typeRef = primRef(prim); radix = null; break; default: conv.type = ConvType.Primitive; conv.typeRef = primRef(prim); conv.indirectType = typeRef(prim.wrapperType); radix = StringUtils.capitalize(prim.type.getName()); break; } if (structIOExpr != null && radix != null) { conv.setExpr = methodCall(structIOExpr.clone(), "set" + radix + "Field", thisRef(), expr(fieldIndex), valueExpr); conv.getExpr = methodCall(structIOExpr.clone(), "get" + radix + "Field", thisRef(), expr(fieldIndex)); } return conv; } else { Identifier valueName = valueType instanceof SimpleTypeRef ? ((SimpleTypeRef)valueType).getName() : null; // Structs if (valueType instanceof Struct) conv.typeRef = typeRef(findStructRef((Struct)valueType, libraryClassName)); else if (result.structsFullNames.contains(valueName)) conv.typeRef = valueType; else conv.typeRef = typeRef(findStructRef(valueName, libraryClassName)); if (conv.typeRef != null) { //conv.setExpr = methodCall(structPeerExpr.clone(), "set" + radix, offsetExpr.clone(), valueExpr); if (structIOExpr != null) { conv.getExpr = methodCall(structIOExpr, "getNativeObjectField", thisRef(), expr(fieldIndex)); //conv.getExpr = new Expression.New(conv.typeRef, (Expression)methodCall(structIOExpr.clone(), "offset", offsetExpr.clone())); } conv.type = ConvType.Struct; return conv; } // Enums if (valueType instanceof Enum) conv.typeRef = findEnumRef((Enum)valueType, libraryClassName); else if (result.enumsFullNames.contains(valueName)) conv.typeRef = valueType; else conv.typeRef = findEnum(valueName, libraryClassName); if (conv.typeRef != null) { if (structIOExpr != null) { conv.setExpr = methodCall(structIOExpr, "setEnumField", thisRef(), expr(fieldIndex), valueExpr); conv.getExpr = methodCall(structIOExpr, "getEnumField", thisRef(), expr(fieldIndex));//expr(typeRef(FlagSet.class)), "fromValue", methodCall(structPeerExpr.clone(), "getInt", expr(fieldIndex)), classLiteral(conv.typeRef.clone())); } conv.type = ConvType.Enum; conv.typeRef = typeRef(ident(ValuedEnum.class, expr(conv.typeRef))); return conv; } // Callbacks conv.typeRef = conv.typeRef = result.callbacksFullNames.contains(valueName) ? valueType : valueType instanceof FunctionSignature ? findCallbackRef((FunctionSignature)valueType, libraryClassName) : findCallbackRef(valueName, libraryClassName); if (conv.typeRef != null) { if (structIOExpr != null) { conv.setExpr = methodCall(structIOExpr.clone(), "setPointerField", thisRef(), expr(fieldIndex), valueExpr); conv.getExpr = methodCall(structIOExpr.clone(), "getPointerField", thisRef(), expr(fieldIndex)); } conv.type = ConvType.Pointer; conv.typeRef = typeRef(ident(result.config.runtime.pointerClass, expr(conv.typeRef))); return conv; } } } if (valueType instanceof SimpleTypeRef && allowFakePointers) { conv.typeRef = typeRef(result.getUndefinedType(libraryClassName, ((SimpleTypeRef)valueType).getName().clone())); conv.isUndefined = true; return conv; } throw new UnsupportedConversionException(original, "Unsupported type"); } @SuppressWarnings("unchecked") Pair<TypeRef, List<Annotation>> toRawNL4JType(TypeRef nl4jType) throws UnsupportedConversionException { if (!(nl4jType instanceof SimpleTypeRef)) { throw new UnsupportedConversionException(nl4jType, "Not a known type : " + nl4jType); } Pair<TypeRef, List<Annotation>> ret = new Pair<TypeRef, List<Annotation>>(nl4jType.clone(), Collections.EMPTY_LIST); if (nl4jType instanceof TypeRef.Primitive) { return ret; } SimpleTypeRef str = (SimpleTypeRef) nl4jType; Identifier strn = str.getName(); if (strn.equals(result.config.runtime.pointerClass.getName())) { ret.setSecond(Arrays.asList(new Annotation(Ptr.class))); ret.setFirst(typeRef(JavaPrim.Long.type)); } else if (strn.equals(ValuedEnum.class.getName())) { ret.setFirst(typeRef(JavaPrim.Int.type)); } else { throw new UnsupportedConversionException(nl4jType, "No raw conversion available yet for type " + nl4jType); } return ret; } /* public static class NL4JTypeConversion { public enum Type { Enum, Pointer, Primitive, Struct, NativeLong, NativeSize, Void, Callback } public NL4JTypeConversion(TypeRef directType, TypeRef indirectType, Type type) { this.directType = directType; this.indirectType = indirectType; this.type = type; } private final TypeRef directType, indirectType; public final Type type; public <M extends ModifiableElement> M annotateRawType(M element) throws UnsupportedConversionException { if (type != null) switch (type) { case Enum: case Primitive: case Void: break; case NativeLong: element.addAnnotation(new Annotation(CLong.class)); break; case NativeSize: element.addAnnotation(new Annotation(Ptr.class)); break; case Pointer: element.addAnnotation(new Annotation(Ptr.class)); break; case Struct: throw new UnsupportedConversionException(directType, "Struct by value not supported yet"); default: throw new UnsupportedConversionException(directType, "Not supported"); } return element; } public <M extends ModifiableElement> M annotateTypedType(M element) throws UnsupportedConversionException { if (type != Type.Pointer) annotateRawType(element); return element; } public TypeRef getTypedTypeRef() { return directType == null ? typeRef("void") : directType.clone(); } public TypeRef getIndirectTypeRef() { if (type == NL4JTypeConversion.Type.Void) return typeRef(ident("?")); TypeRef t = indirectType == null ? directType : indirectType; return t == null ? null : t.clone(); } public TypeRef getRawType() throws UnsupportedConversionException { if (type == null) { return directType.clone(); } switch (type) { case Enum: return typeRef(Integer.TYPE); case Pointer: return typeRef(Long.TYPE); case Void: return typeRef("void"); case Primitive: case NativeLong: case NativeSize: return getTypedTypeRef(); case Struct: throw new UnsupportedConversionException(getTypedTypeRef(), "Struct by value not supported yet"); default: throw new UnsupportedConversionException(getTypedTypeRef(), "Not supported"); } } } NL4JTypeConversion toNL4JType(TypeRef valueType, java.util.Stack<String> namesStack, Identifier library) throws UnsupportedConversionException { if (valueType instanceof TargettedTypeRef) { TargettedTypeRef ttr = (TargettedTypeRef)valueType; NL4JTypeConversion targetConv = toNL4JType(ttr.getTarget(), namesStack, library); TypeRef pointedTypeRef = targetConv.getIndirectTypeRef(); if (targetConv.type != NL4JTypeConversion.Type.Void) { try { if (targetConv.type == NL4JTypeConversion.Type.NativeSize) pointedTypeRef = typeRef(SizeT.class); else if (targetConv.type == NL4JTypeConversion.Type.NativeLong) pointedTypeRef = typeRef(CLong.class); else { String s = targetConv.getRawType().toString(); if (s.equals(Byte.TYPE.getName()) && (result.config.charPtrAsString || valueType.hasModifier(ModifierType.__const))) return new NL4JTypeConversion( typeRef(ident(result.config.runtime.pointerClass, expr(typeRef(String.class)))), null, NL4JTypeConversion.Type.Pointer ); } } catch (UnsupportedConversionException ex) { } } return new NL4JTypeConversion( typeRef( ident( result.config.runtime.pointerClass, expr(pointedTypeRef) ) ), null, NL4JTypeConversion.Type.Pointer ); } if (valueType instanceof SimpleTypeRef) { JavaPrim prim = getPrimitive(valueType, null); if (prim != null) { switch (prim) { case NativeLong: return new NL4JTypeConversion(typeRef(Long.TYPE), typeRef(Long.class), NL4JTypeConversion.Type.NativeLong); case NativeSize: return new NL4JTypeConversion(typeRef(Long.TYPE), typeRef(Long.class), NL4JTypeConversion.Type.NativeSize); case Void: return new NL4JTypeConversion(null, null, NL4JTypeConversion.Type.Void); default: return new NL4JTypeConversion(typeRef(prim.type), typeRef(prim.wrapperType), NL4JTypeConversion.Type.Primitive); } } Identifier name = ((SimpleTypeRef)valueType).getName(); if (name == null) return null; if (namesStack == null) namesStack = new Stack<String>(); String nameStr = name.toString(); if (nameStr == null || namesStack.contains(nameStr)) return null; namesStack.push(nameStr); try { Pair<TypeDef,Declarator> p = getTypeDef(name); if (p != null) { TypeRef tr = p.getFirst().getValueType();//as(p.getSecond().mutateType(p.getFirst().getValueType()), TypeRef.class); if (tr instanceof TaggedTypeRef) { TaggedTypeRef ttr = (TaggedTypeRef)tr; Identifier name2 = result.declarationsConverter.getActualTaggedTypeName(ttr); if (name2 != null) { name = name2; nameStr = name.toString(); } //if (ttr.isForwardDeclaration()) // return; TypeRef javaRef = typeRef(result.getTaggedTypeIdentifierInJava(ttr)); if (tr instanceof Enum) { return new NL4JTypeConversion(toNL4JEnum(javaRef), null, NL4JTypeConversion.Type.Enum); } else if (tr instanceof Struct) { return new NL4JTypeConversion(javaRef, null, NL4JTypeConversion.Type.Struct); } } else if (tr instanceof FunctionSignature) { return new NL4JTypeConversion(typeRef(ident(result.config.runtime.pointerClass, expr(findCallbackRef((FunctionSignature)tr, null)))), null, NL4JTypeConversion.Type.Pointer); } else { String strs = valueType.toString(); String trs = tr == null ? null : tr.toString(); if (trs != null && !strs.equals(trs)) { try { TypeRef clo = tr.clone(); return toNL4JType(clo, namesStack, library); } catch (UnsupportedConversionException ex) { if (tr instanceof TypeRef.Pointer && allowFakePointers) { return new NL4JTypeConversion( typeRef(result.getFakePointer(library, name.clone())), null, null ); } else throw ex; } } } } TypeRef manualTypeRef = manualTypeDefs.get(nameStr); if (manualTypeRef != null) return toNL4JType(manualTypeRef, namesStack, library); TypeRef structRef = typeRef(findStructRef(name, null)); if (structRef != null) { return new NL4JTypeConversion(structRef.clone(), null, NL4JTypeConversion.Type.Struct); } TypeRef enumRef = findEnum(name, null); if (enumRef != null) { return new NL4JTypeConversion(toNL4JEnum(enumRef), null, NL4JTypeConversion.Type.Enum); } Define define = result.defines.get(nameStr); Expression expression = define == null ? null : define.getValue(); if (expression != null) { Identifier fieldName = null; if (expression instanceof Expression.VariableRef) fieldName = ((Expression.VariableRef) expression).getName(); else if (expression instanceof MemberRef) fieldName = ((MemberRef) expression).getName(); if (fieldName != null && !fieldName.equals(name)) return toNL4JType(new TypeRef.SimpleTypeRef(fieldName), namesStack, library); } } finally { namesStack.pop(); } } throw new UnsupportedConversionException(valueType, "Unsupported type"); } TypeRef toNL4JEnum(TypeRef enumResolvedJavaRef) { return typeRef(ident(ValuedEnum.class, expr(enumResolvedJavaRef.clone()))); } */ public Expression getFlatArraySizeExpression(Pointer.ArrayRef arrayRef, Identifier callerLibraryName) throws UnsupportedConversionException { Expression mul = null; List<Expression> dims = arrayRef.flattenDimensions(); for (int i = dims.size(); i-- != 0;) { Expression x = dims.get(i); if (x == null || x instanceof EmptyArraySize) { return null; //javaType = jr = new ArrayRef(typeRef(Pointer.class)); //break; } else { Pair<Expression, TypeRef> c = result.typeConverter.convertExpressionToJava(x, callerLibraryName, false); c.getFirst().setParenthesis(dims.size() > 1); if (mul == null) { mul = c.getFirst(); } else { mul = expr(c.getFirst(), BinaryOperator.Multiply, mul); } } } return mul; } Pattern wstringPat = Pattern.compile("(__)?const wchar_t\\*"), stringPat = Pattern.compile("(__)?const char\\*"), wstringPtrPtrPat = Pattern.compile("(__)?const wchar_t\\*\\*"), stringPtrPtrPat = Pattern.compile("(__)?const char\\*\\*"); protected boolean isString(String typeRefAsString, boolean wide) { if (wide) { return wstringPat.matcher(typeRefAsString).matches() || result.config.charPtrAsString && typeRefAsString.equals("wchar_t*"); } else { return stringPat.matcher(typeRefAsString).matches() || result.config.charPtrAsString && typeRefAsString.equals("char*"); } } protected boolean isStringPtrPtr(String typeRefAsString, boolean wide) { if (wide) { return wstringPtrPtrPat.matcher(typeRefAsString).matches() || result.config.charPtrAsString && typeRefAsString.equals("wchar_t**"); } else { return stringPtrPtrPat.matcher(typeRefAsString).matches() || result.config.charPtrAsString && typeRefAsString.equals("char**"); } } public TypeRef convertTypeToJNA(TypeRef valueType, TypeConversionMode conversionMode, Identifier libraryClassName) throws UnsupportedConversionException { // if (String.valueOf(valueType).contains("MonoImageOpenStatus")) // valueType.toString(); TypeRef original = valueType; valueType = resolveTypeDef(valueType, libraryClassName, true, false); // if (String.valueOf(valueType).contains("MonoObject")) // valueType.toString(); String valueTypeString = String.valueOf(valueType); if (valueTypeString.matches("void\\s*\\*") || valueTypeString.matches("const\\s*void\\s*\\*")) { //valueType = (TypeRef)valueType; if (original instanceof Pointer && result.config.features.contains(GenFeatures.TypedPointersForForwardDeclarations) && allowFakePointers) { Pointer p = (Pointer) original; if (p.getTarget() instanceof SimpleTypeRef) { if (isResolved((SimpleTypeRef) p.getTarget())) { return p.getTarget(); } Identifier name = ((SimpleTypeRef) p.getTarget()).getName(); if (!"void".equals(name.toString()) && name.isPlain()) { // int i = name.lastIndexOf('.'); // if (i >= 0) // name = name.substring(i + 1); return typeRef(result.getFakePointer(libraryClassName, name)); } } } } else { if (conversionMode == TypeConversionMode.ReturnType && result.config.stringifyConstCStringReturnValues) { if (isString(valueTypeString, false)) { return typeRef(String.class); } else if (isString(valueTypeString, true)) { return typeRef(WString.class); } } else if (conversionMode == TypeConversionMode.PrimitiveOrBufferParameter) { if (isString(valueTypeString, false)) { return typeRef(String.class); } else if (isString(valueTypeString, true)) { return typeRef(WString.class); } else if (isStringPtrPtr(valueTypeString, false)) { return arrayRef(typeRef(String.class)); } else if (isStringPtrPtr(valueTypeString, true)) { return arrayRef(typeRef(WString.class)); } /*else if (conversionMode == TypeConversionMode.PrimitiveOrBufferParameter) { if (valueTypeString.matches("char\\*")) return typeRef(StringPointer.ByValue.class); else if (valueTypeString.matches("wchar_t\\*")) return typeRef(WStringPointer.ByValue.class); }*/ } } if (valueType instanceof Primitive) { JavaPrim prim = getPrimitive(valueType, libraryClassName); if (prim != null) { return primRef(prim); } // if (!valueType.getModifiers().contains("long")) // return valueType.toString(); } if (valueType instanceof TaggedTypeRef) { Identifier name = result.declarationsConverter.getActualTaggedTypeName((TaggedTypeRef) valueType); if (name != null) { if (valueType instanceof Enum) { TypeRef tr = findEnum(name, libraryClassName); if (tr != null) { TypeRef intRef = primRef(JavaPrim.Int); intRef.setCommentBefore(tr.getCommentBefore()); return intRef; } } else if (valueType instanceof Struct) { Identifier tr = findStructRef(name, libraryClassName); if (tr != null) { switch (conversionMode) { case PointedValue: case NativeParameterWithStructsPtrPtrs: case NativeParameter: case PrimitiveOrBufferParameter: case ReturnType: case PrimitiveReturnType: case FieldType: return typeRef(tr); case StaticallySizedArrayField: case ExpressionType: default: return typeRef(ident(tr, ident("ByValue"))); } } } } } if (valueType instanceof FunctionSignature) { TypeRef tr = findCallbackRef((FunctionSignature)valueType, libraryClassName); if (tr != null) return tr; else return typeRef(((FunctionSignature)valueType).getFunction().getName().clone()); } if (valueType instanceof TargettedTypeRef) { //TypeRef target = resolveTypeDef(((TargettedTypeRef) valueType).getTarget(), callerLibraryClass); TypeRef target = ((TargettedTypeRef) valueType).getTarget(); boolean staticallySized = valueType instanceof ArrayRef && ((ArrayRef)valueType).hasStaticStorageSize(); TypeRef convArgType = null; JavaPrim prim = getPrimitive(target, libraryClassName); if (prim != null) { if (prim == JavaPrim.Void) return typeRef(result.config.runtime.pointerClass); else convArgType = primRef(prim); } else { Identifier name = null; if (target instanceof SimpleTypeRef) name = ((SimpleTypeRef) target).getName(); else if (target instanceof Struct) { Struct struct = (Struct)target; if (struct == null) { valueType = resolveTypeDef(original, libraryClassName, true, false); struct = null; } else { name = result.declarationsConverter.getActualTaggedTypeName(struct); } } else if (target instanceof FunctionSignature) { TypeRef tr = findCallbackRef((FunctionSignature)target, libraryClassName); if (tr != null) { if (valueType instanceof TypeRef.ArrayRef) { return new TypeRef.ArrayRef(tr); } else { return tr; } } //else // return typeRef(((FunctionSignature)valueType).getFunction().getName()); } else if (target instanceof Pointer) { if (conversionMode == TypeConversionMode.NativeParameter) return typeRef(PointerByReference.class); Pointer pt = ((Pointer)target); TypeRef ptarget = pt.getTarget(); if (ptarget instanceof SimpleTypeRef) { SimpleTypeRef ptargett = (SimpleTypeRef) ptarget; Identifier tname = ptargett.getName(); if (result.structsFullNames.contains(tname)) { if (conversionMode == TypeConversionMode.FieldType) return typeRef(PointerByReference.class); else return new ArrayRef(typeRef(ident(ptargett.getName(), "ByReference"))); } else if ((tname = result.findFakePointer(tname)) != null) return new ArrayRef(typeRef(tname.clone())); } } if (name != null) { /// Pointer to Objective-C class ? convArgType = findObjCClass(name); boolean isQualStruct = result.structsFullNames.contains(name); if (convArgType == null || isQualStruct) { /// Pointer to C structure Identifier structRef = isQualStruct ? name : findStructRef(name, libraryClassName); if (structRef != null) {//result.cStructNames.contains(name)) { switch (conversionMode) { case ExpressionType: case FieldType: convArgType = valueType instanceof TypeRef.ArrayRef ? typeRef(structRef) : typeRef(ident(structRef, ident("ByReference"))); if (valueType instanceof Pointer) return convArgType; break; default: if (isQualStruct && (valueType instanceof ArrayRef) && ( conversionMode == TypeConversionMode.NativeParameterWithStructsPtrPtrs || conversionMode == TypeConversionMode.PrimitiveOrBufferParameter )) return arrayRef(typeRef(structRef)); convArgType = typeRef(structRef); if (valueType instanceof Pointer) return convArgType; break; } } else { try { convArgType = convertTypeToJNA(target, conversionMode, libraryClassName); if (result.isUndefinedType(convArgType)) { if (allowFakePointers && original instanceof SimpleTypeRef) return typeRef(result.getFakePointer(libraryClassName, ((SimpleTypeRef)original).getName().clone())); else convArgType = typeRef(result.config.runtime.pointerClass); } if (convArgType != null && result.callbacksFullNames.contains(ident(convArgType.toString())) && !(valueType instanceof ArrayRef)) { TypeRef tr = typeRef(result.config.runtime.pointerClass); if (!result.config.noComments) tr.setCommentBefore("@see " + convArgType); return tr; } prim = getPrimitive(convArgType, libraryClassName); } catch (UnsupportedConversionException ex) { //convArgType = null;//return typeRef(result.config.runtime.pointerClass); if (valueType instanceof TypeRef.Pointer && target instanceof TypeRef.SimpleTypeRef && result.config.features.contains(JNAeratorConfig.GenFeatures.TypedPointersForForwardDeclarations) && allowFakePointers ) { if (isResolved((SimpleTypeRef) target)) { return target; } // int i = name.lastIndexOf('.'); // if (i >= 0) { // name = name.substring(i + 1); // } return typeRef(result.getFakePointer(libraryClassName, name)); } else { return typeRef(result.config.runtime.pointerClass); } } } } } else { try { convArgType = convertTypeToJNA(target, conversionMode, libraryClassName); prim = getPrimitive(convArgType, libraryClassName); } catch (UnsupportedConversionException ex) { //convArgType = null;// return typeRef(result.config.runtime.pointerClass); } } } switch (conversionMode) { case StaticallySizedArrayField: return new ArrayRef(convArgType); case PrimitiveOrBufferParameter: if (!result.config.noPrimitiveArrays && (target.getModifiers().contains(ModifierType.Const) || valueType.getModifiers().contains(ModifierType.Const))) { return new ArrayRef(convArgType); } Class<? extends Buffer> bc = primToBuffer.get(prim); if (bc != null) { return typeRef(bc); } case ReturnType: case FieldType: if (staticallySized) { return arrayRef(convArgType); } default: if (prim != null) { if (prim == JavaPrim.Byte) { return typeRef(result.config.runtime.pointerClass).importDetails(convArgType, false); } Class<? extends ByReference> byRefClass = primToByReference.get(prim); if (byRefClass != null) { return typeRef(byRefClass).importDetails(convArgType, false); } } if (convArgType != null && !convArgType.toString().equals(result.config.runtime.pointerClass.getName()) && valueType instanceof TypeRef.Pointer && target instanceof TypeRef.SimpleTypeRef) { return convArgType; } } if (target instanceof Pointer) { return typeRef(PointerByReference.class); } if (allowUnknownPointers) { return typeRef(result.config.runtime.pointerClass); } } if (valueType instanceof SimpleTypeRef) { Identifier name = ((SimpleTypeRef) valueType).getName(); if (name == null) { throw new UnsupportedConversionException(valueType, null); } boolean isQualStruct = result.structsFullNames.contains(name); //isQualCallback = result.callbacksFullNames.contains(name); if (!isQualStruct && isResolved((SimpleTypeRef) valueType)) { return valueType; } if (name instanceof SimpleIdentifier) { TypeRef tr = findObjCClass(name); if (tr == null) { tr = findObjCClass(new SimpleIdentifier(((SimpleIdentifier) name).getName())); } if (tr != null) { return tr; } } Identifier structRef = isQualStruct ? name : findStructRef(name, libraryClassName); if (structRef != null) { switch (conversionMode) { case PointedValue: case FieldType: return typeRef(structRef); default: return typeRef(ident(structRef, "ByValue")); } } TypeRef callbackRef = findCallbackRef(name, libraryClassName); if (callbackRef != null) { return callbackRef; } SimpleTypeRef enumTypeRef = findEnum(name, libraryClassName); //FieldRef enumQualifiedName = findEnum(name); if (enumTypeRef != null) { return enumTypeRef; } TypeRef objCClassRef = findObjCClass(name); if (objCClassRef != null) { return objCClassRef; } } JavaPrim prim = getPrimitive(valueType, libraryClassName); if (prim != null) { return primRef(prim); } if (valueType instanceof SimpleTypeRef && allowFakePointers) { return typeRef(result.getUndefinedType(libraryClassName, ((SimpleTypeRef)valueType).getName().clone())); } unknownTypes.add(String.valueOf(valueType)); throw new UnsupportedConversionException(valueType, null); } static Map<String, Class<?>> predefObjCClasses = new HashMap<String, Class<?>>(); static { predefObjCClasses.put("id", ObjCObject.class);//org.rococoa.ID.class); predefObjCClasses.put("SEL", org.rococoa.Selector.class); predefObjCClasses.put("IMP", com.sun.jna.Pointer.class); predefObjCClasses.put("Class", ObjCClass.class); predefObjCClasses.put("Protocol", ObjCClass.class); predefObjCClasses.put("NSObject", NSObject.class); //predefObjCClasses.put("NSClass", NSClass.class); } public Identifier findObjCClassIdent(Identifier name) { if (name instanceof SimpleIdentifier) { SimpleIdentifier sname = (SimpleIdentifier) name; String n = sname.getName(); if (n.equals("id") && sname.getTemplateArguments().size() == 1/* && conversionMode != TypeConversionMode.NativeParameter && conversionMode != TypeConversionMode.NativeParameterWithStructsPtrPtrs*/) { Expression x = sname.getTemplateArguments().get(0); TypeRefExpression trx = x instanceof TypeRefExpression ? (TypeRefExpression) x : null; SimpleTypeRef str = trx.getType() instanceof SimpleTypeRef ? (SimpleTypeRef) trx.getType() : null; if (str != null) { name = str.getName(); } } } Class<?> class1 = predefObjCClasses.get(name.toString()); if (class1 != null) { return ident(class1); } Struct s = result.getObjcCClassOrProtocol(name); if (s != null) { return result.objectiveCGenerator.getFullClassName(s); } return null; } public TypeRef findObjCClass(Identifier name) { return typeRef(findObjCClassIdent(name)); } private TypeRef arrayRef(TypeRef tr) { ArrayRef arrayRef; if (tr instanceof ArrayRef) { arrayRef = (ArrayRef) tr; arrayRef.addDimension(new Expression.EmptyArraySize()); } else { arrayRef = new ArrayRef(tr); } return arrayRef; } Set<String> unknownTypes = new HashSet<String>(); public static <A, B> Pair<A, B> pair(A a, B b) { return new Pair<A, B>(a, b); } public static Pair<Expression, TypeRef> typed(Expression a, TypeRef b) { return new Pair<Expression, TypeRef>(a, b); } public Pair<Expression, TypeRef> convertExpressionToJava(Expression x, Identifier libraryClassName, boolean promoteNativeLongToLong) throws UnsupportedConversionException { Pair<Expression, TypeRef> res = null; if (x instanceof AssignmentOp) { Pair<Expression, TypeRef> convTarget = convertExpressionToJava(((AssignmentOp) x).getTarget(), libraryClassName, promoteNativeLongToLong), convValue = convertExpressionToJava(((AssignmentOp) x).getValue(), libraryClassName, promoteNativeLongToLong); res = typed(expr(convTarget.getFirst(), AssignmentOperator.Equal, convValue.getFirst()), convTarget.getSecond()); } else if (x instanceof BinaryOp) { BinaryOp bop = (BinaryOp) x; Pair<Expression, TypeRef> conv1 = convertExpressionToJava(bop.getFirstOperand(), libraryClassName, promoteNativeLongToLong), conv2 = convertExpressionToJava(bop.getSecondOperand(), libraryClassName, promoteNativeLongToLong); if (conv1 != null && conv2 != null) { TypeRef t1 = conv1.getSecond(), t2 = conv2.getSecond(); Expression x1 = conv1.getFirst(), x2 = conv2.getFirst(); String s1 = String.valueOf(t1), s2 = String.valueOf(t2); TypeRef tr = null; if (bop.getOperator().givesBool) tr = typeRef(boolean.class); else { if (s1.equals(s2)) { tr = t1; } else { JavaPrim p1 = getPrimitive(t1, null), p2 = getPrimitive(t2, null); if (p1 != null && p2 != null) { switch (bop.getOperator()) { case LeftShift: case RightShift: case SignedRightShift: tr = t1; break; default: for (JavaPrim p : new JavaPrim[]{ JavaPrim.Double, JavaPrim.Float, JavaPrim.Long, JavaPrim.NativeSize, JavaPrim.NativeLong, JavaPrim.Int, JavaPrim.Short, JavaPrim.Byte }) { if (p1 == p || p2 == p) { if (promoteNativeLongToLong && (p == JavaPrim.NativeLong || p == JavaPrim.NativeSize)) { p = JavaPrim.Long; } tr = primRef(p); break; } } } } } } res = typed(expr(x1, ((BinaryOp) x).getOperator(), x2), tr); } } else if (x instanceof UnaryOp) { UnaryOperator op = ((UnaryOp) x).getOperator(); if (op == UnaryOperator.Not) { throw new UnsupportedConversionException(x, null); // TODO handle this properly ? } Pair<Expression, TypeRef> conv = convertExpressionToJava(((UnaryOp) x).getOperand(), libraryClassName, promoteNativeLongToLong); res = typed(expr(op, conv.getFirst()), conv.getSecond()); } else if (x instanceof Cast) { TypeRef tpe = ((Cast) x).getType(); Pair<Expression, TypeRef> casted = convertExpressionToJava(((Cast) x).getTarget(), libraryClassName, promoteNativeLongToLong); if (result.config.runtime.hasJNA) { TypeRef tr = convertTypeToJNA(tpe, TypeConversionMode.ExpressionType, libraryClassName); JavaPrim prim = getPrimitive(tr, libraryClassName); if (promoteNativeLongToLong && (prim == JavaPrim.NativeLong || prim == JavaPrim.NativeSize)) { prim = JavaPrim.Long; tr = typeRef(Long.TYPE); } res = typed(casted.getFirst(), tr); if (prim == JavaPrim.NativeLong) { res.setFirst((Expression) new New(typeRef(com.sun.jna.NativeLong.class), casted.getFirst())); } else if (prim == JavaPrim.NativeSize) { res.setFirst((Expression) new New(typeRef(NativeSize.class), casted.getFirst())); } } else { NL4JConversion conv = convertTypeToNL4J(tpe, libraryClassName, null, null, -1, -1); TypeRef tr = conv.typeRef; res = typed(casted.getFirst(), tr); if (conv.isPtr) { res.setFirst(methodCall(expr(typeRef(result.config.runtime.pointerClass)), "pointerToAddress", casted.getFirst())); } } } else if (x instanceof Constant) { Class<?> c = null; Constant jc = ((Constant) x).asJava(); switch (jc.getType()) { case Byte: c = Byte.TYPE; break; case Char: c = Character.TYPE; break; case Double: c = Double.TYPE; break; case Float: c = Float.TYPE; break; case Int: case UInt: case IntegerString: c = Integer.TYPE; break; case ULong: case Long: case LongString: c = Long.TYPE; break; case Short: c = Short.TYPE; break; case String: c = String.class; break; } if (c != null) { res = typed(((Constant) x).asJava(), typeRef(c)); } } else if (x instanceof VariableRef) { VariableRef fr = (VariableRef) x; Identifier name = fr.getName(); if (name != null) { Define define = result.defines.get(name); if (define != null && define.getValue() != null) { if (x.toString().equals(define.getValue().toString())) { res = null; // avoid some nasty loops } else { Expression defineValue = define.getValue(); if (defineValue instanceof Constant) { Constant constant = (Constant) defineValue; res = typed(findDefine(name), convertToJavaType(constant.getType())); } if (res == null) { res = convertExpressionToJava(defineValue, libraryClassName, promoteNativeLongToLong); } } } else { String sname = name.toString(); if (sname.equals("True") || sname.equals("true")) { res = typed(expr(Constant.Type.Bool, true), primRef(JavaPrim.Boolean)); } else if (sname.equals("False") || sname.equals("false")) { res = typed(expr(Constant.Type.Bool, false), primRef(JavaPrim.Boolean)); } else { EnumItem enumItem = result.enumItems.get(name); if (enumItem != null) { res = typed(findEnumItem(enumItem), typeRef(Integer.TYPE)); } else { VariablesDeclaration constant = result.globalVariablesByName.get(name); if (constant != null) { res = typed(varRef(findRef(name, constant, libraryClassName, true)), null); } else { res = typed(new VariableRef(name), null); } } } } } } else if (x instanceof FunctionCall) { FunctionCall fc = (FunctionCall) x; if ("sizeof".equals(String.valueOf(fc.getFunction())) && fc.getArguments().size() == 1) { TypeRefExpression typeEx = SyntaxUtils.as(fc.getArguments().get(0).getValue(), TypeRefExpression.class); if (typeEx != null) { res = typed(sizeofToJava(typeEx.getType(), libraryClassName), typeRef(Integer.TYPE)); } } } if (x instanceof TypeRefExpression) { TypeRefExpression tre = (TypeRefExpression) x; TypeRef tr = tre.getType(); if (tr instanceof SimpleTypeRef) { SimpleTypeRef str = (SimpleTypeRef) tr; Identifier ident = str.getName(); if (ident != null) { if (result.enumItemsFullName.contains(ident)) { res = typed(tre, typeRef(Integer.TYPE)); } } } if (res == null) { if (tr.isMarkedAsResolved()) { res = typed(tre, tr); } else { TypeRef conv = convertTypeToJNA(tr, TypeConversionMode.ExpressionType, libraryClassName); res = typed(new TypeRefExpression(conv), conv); } } } if (res == null) { // return convertExpressionToJava(x); throw new UnsupportedConversionException(x, null); } if (res.getFirst() == null) { return null; } res.getFirst().setParenthesis(x.getParenthesis()); return (Pair<Expression, TypeRef>) res; } public TypeRef convertToJavaType(Constant.Type type) { switch (type) { case Bool: return typeRef(Boolean.TYPE); case IntegerString: case UInt: case Int: return typeRef(Integer.TYPE); case LongString: case ULong: case Long: return typeRef(Long.TYPE); case Short: return typeRef(Short.TYPE); case Byte: return typeRef(Byte.TYPE); case Float: return typeRef(Float.TYPE); case Double: return typeRef(Double.TYPE); case String: return typeRef(String.class); default: return null; } } private Expression sizeofToJava(TypeRef type, Identifier libraryClassName) throws UnsupportedConversionException { type = resolveTypeDef(type, libraryClassName, true, false); // type = type; Expression res = null; if (type instanceof Pointer) { res = memberRef(expr(typeRef(result.config.runtime.pointerClass)), MemberRefStyle.Dot, "SIZE"); } else if (type instanceof ArrayRef) { res = sizeofToJava(((ArrayRef) type).getTarget(), libraryClassName); if (res == null) { return null; } ArrayRef ar = (ArrayRef) type; for (Expression x : ar.getDimensions()) { Expression c = convertExpressionToJava(x, libraryClassName, false).getFirst(); res = expr(res, Expression.BinaryOperator.Multiply, c); } } else if (type instanceof SimpleTypeRef || type instanceof Primitive) { JavaPrim prim = getPrimitive(type, libraryClassName); if (prim != null) { res = sizeof(prim); } else { Identifier structRef = findStructRef(((SimpleTypeRef) type).getName(), libraryClassName); if (structRef == null) { structRef = findStructRef(((SimpleTypeRef) type).getName().resolveLastSimpleIdentifier(), libraryClassName); } if (structRef != null) { return methodCall(new New(typeRef(structRef)), MemberRefStyle.Dot, "size"); } } } else if (type instanceof Struct) { Struct s = (Struct) type; if (s != null) { Identifier structName = result.declarationsConverter.getActualTaggedTypeName(s); Identifier structRef = findStructRef(structName, libraryClassName); if (structRef != null) { return methodCall(new New(typeRef(structRef)), MemberRefStyle.Dot, "size"); } else { for (Declaration d : s.getDeclarations()) { if (d instanceof VariablesDeclaration) { TypeRef varsType = d.getValueType(); for (Declarator sto : ((VariablesDeclaration) d).getDeclarators()) { Expression so = sizeofToJava(as(sto.mutateType(varsType), TypeRef.class), libraryClassName); if (so == null) { return null; } if (res == null) { res = so; } else { res = expr(res, Expression.BinaryOperator.Plus, so); } } } } } } } return res; } private Expression sizeof(JavaPrim prim) { return prim.size.sizeof(prim); } private Expression findEnumItem(EnumItem enumItem) { String library = result.getLibrary(enumItem); if (library == null) { return null; } Element parent = enumItem.getParentElement(); if (parent == null || !(parent instanceof Enum)) { return null; } Enum e = (Enum) parent; Identifier ident = ident(result.getLibraryClassFullName(library), result.declarationsConverter.getActualTaggedTypeName(e), ident(enumItem.getName())); return expr(typeRef(ident).setMarkedAsResolved(true)); } /// @see http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html public static Set<String> JAVA_KEYWORDS = new HashSet<String>(Arrays.asList( "null", "true", "false", "abstract", "continue", "for", "new", "switch", "assert", "default", "goto", "package", "synchronized", "boolean", "do", "if", "private", "this", "break", "double", "implements", "protected", "throw", "byte", "else", "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", "native", "super", "while", "wait" // not allowed for function names )); //static String keywords = " true false double float wait new null boolean return class public protected private "; public Identifier getValidJavaArgumentName(Identifier name) { return getValidJavaIdentifier(name); } public Identifier getValidJavaMethodName(Identifier name) { String nameStr = name.toString(); String newName = null; if (nameStr.matches("operator[^\\w]+")) { String op = nameStr.substring("operator".length()); //int nArgs = method.getArgs().size(); String suffix = null; java.lang.Enum<?> e = Expression.getAnyOperator(op); if (e == null) { if (op.equals("()")) { suffix = "parenthesis"; } else if (op.equals("[]")) { suffix = "brackets"; } else if (op.equals("->")) { suffix = "arrow"; } } else { suffix = e.name(); } if (suffix != null) { newName = "operator" + StringUtils.capitalize(suffix); } }/* else if (nameStr.startsWith("~")) { newName = getValidJavaIdentifierString(ident(nameStr.substring(1))) + "Destructor"; }*/ if (newName == null) { newName = getValidJavaIdentifierString(name); } else if (result.config.beautifyNames) { newName = beautify(newName); } return ident(newName); } String beautify(String name) { String newName = StringUtils.uncapitalize(StringUtils.underscoredToCamel(name)); if (name.endsWith("_")) { newName += "$"; } return newName; } public boolean isJavaKeyword(String name) { return JAVA_KEYWORDS.contains(name); } public Identifier getValidJavaIdentifier(Identifier name) { return ident(getValidJavaIdentifierString(name)); } public String getValidJavaIdentifierString(Identifier name) { if (name == null) { return null; } if (isJavaKeyword(name.toString())) { return name + "$"; } else { String newName = name.toString().replace('-', '_').replaceAll("[^\\w]", "\\$"); if (result.config.beautifyNames) { newName = beautify(newName); } return newName; } } public static String toPrimString(JavaPrim prim) { return prim.name; } public Expression getJavaClassLitteralExpression(TypeRef tr) { JavaPrim prim = result.typeConverter.getPrimitive(tr, null); return prim != null ? classLiteral(prim.type) : typeLiteral(tr.clone()); } public Expression getJavaClassLitteralExpression() { throw new UnsupportedOperationException(getClass().getName() + "." + toString() + " not handled !"); } }
JNAerator: typeLiteral for ? should be null
libraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/TypeConversion.java
JNAerator: typeLiteral for ? should be null
<ide><path>ibraries/jnaerator/jnaerator/src/main/java/com/ochafik/lang/jnaerator/TypeConversion.java <ide> } <ide> <ide> public Expression typeLiteral(TypeRef c) { <add> if (c != null && c.toString().equals("?")) <add> return new Constant(Constant.Type.Null, null); <add> <ide> if (c instanceof SimpleTypeRef && result.config.runtime == JNAeratorConfig.Runtime.BridJ) { <ide> Identifier id = ((SimpleTypeRef) c).getName(); <ide> SimpleIdentifier sid = id.resolveLastSimpleIdentifier();
Java
bsd-2-clause
58dbcfbc4661b6df3f9681c63ffcdd5b22efc683
0
KorAP/Kustvakt,KorAP/Kustvakt,KorAP/Kustvakt,KorAP/Kustvakt
package de.ids_mannheim.korap.authentication; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import de.ids_mannheim.korap.authentication.framework.HttpAuthorizationHandler; import de.ids_mannheim.korap.authentication.framework.TransferEncoding; import de.ids_mannheim.korap.config.Attributes; import de.ids_mannheim.korap.config.AuthenticationType; import de.ids_mannheim.korap.config.KustvaktConfiguration; import de.ids_mannheim.korap.config.Scopes; import de.ids_mannheim.korap.dao.UserDao; import de.ids_mannheim.korap.exceptions.KustvaktException; import de.ids_mannheim.korap.exceptions.StatusCodes; import de.ids_mannheim.korap.interfaces.AuthenticationIface; import de.ids_mannheim.korap.interfaces.EncryptionIface; import de.ids_mannheim.korap.user.KorAPUser; import de.ids_mannheim.korap.user.TokenContext; import de.ids_mannheim.korap.user.User; import de.ids_mannheim.korap.utils.StringUtils; import de.ids_mannheim.korap.utils.TimeUtils; /** * Implementation of encoding and decoding access token is moved to * {@link TransferEncoding}. Moreover, implementation of HTTP * Authentication framework, i.e. creation of authorization header, * is defined in {@link HttpAuthorizationHandler}. * * Basic authentication is intended to be used with a database. It is * currently only used for testing using a dummy DAO (@see {@link UserDao}). * * * @author margaretha * @date 15/11/2017 * * @author hanl * @date 28/04/2015 */ public class BasicAuthentication implements AuthenticationIface { @Autowired private TransferEncoding transferEncoding; @Autowired private KustvaktConfiguration config; @Autowired private EncryptionIface crypto; @Autowired private UserDao dao; public BasicAuthentication (KustvaktConfiguration config) { this.config = config; } @Override public TokenContext getTokenContext (String authToken) throws KustvaktException { // Hanl: fixme: handle via constructor // EM: ? String[] values = transferEncoding.decodeBase64(authToken); if (values != null) { TokenContext c = new TokenContext(); User user = dao.getAccount(values[0]); if (user instanceof KorAPUser && ((KorAPUser) user).getPassword() != null) { boolean check = crypto.checkHash(values[1], ((KorAPUser) user).getPassword()); if (!check) return null; } c.setUsername(values[0]); c.setExpirationTime(TimeUtils.plusSeconds(this.config.getTokenTTL()) .getMillis()); c.setAuthenticationType(AuthenticationType.BASIC); // todo: for production mode, set true c.setSecureRequired(false); // EM: is this secure? c.setToken(StringUtils.stripTokenType(authToken)); // fixme: you can make queries, but user sensitive data is off limits?! c.addContextParameter(Attributes.SCOPES, Scopes.Scope.search.toString()); return c; } return null; } // not supported! @Override public TokenContext createTokenContext (User user, Map<String, Object> attr) throws KustvaktException { return null; } @Override public void removeUserSession (String token) throws KustvaktException { throw new KustvaktException(StatusCodes.NOT_SUPPORTED); } @Override public TokenContext refresh (TokenContext context) throws KustvaktException { return null; } @Override public AuthenticationType getIdentifier () { return AuthenticationType.BASIC; } }
full/src/main/java/de/ids_mannheim/korap/authentication/BasicAuthentication.java
package de.ids_mannheim.korap.authentication; import java.util.Map; import org.apache.commons.codec.binary.Base64; import org.springframework.beans.factory.annotation.Autowired; import de.ids_mannheim.korap.config.Attributes; import de.ids_mannheim.korap.config.AuthenticationType; import de.ids_mannheim.korap.config.KustvaktConfiguration; import de.ids_mannheim.korap.config.Scopes; import de.ids_mannheim.korap.exceptions.KustvaktException; import de.ids_mannheim.korap.exceptions.StatusCodes; import de.ids_mannheim.korap.interfaces.AuthenticationIface; import de.ids_mannheim.korap.interfaces.EncryptionIface; import de.ids_mannheim.korap.interfaces.db.EntityHandlerIface; import de.ids_mannheim.korap.user.KorAPUser; import de.ids_mannheim.korap.user.TokenContext; import de.ids_mannheim.korap.user.User; import de.ids_mannheim.korap.utils.StringUtils; import de.ids_mannheim.korap.utils.TimeUtils; /** EM: do not use at the moment, there is no authentication * checking, formerly used a database. Should separate between * authentication procedure and the real authentication checking * method. * * * @author hanl * @date 28/04/2015 */ // todo: bean injection! public class BasicHttpAuth implements AuthenticationIface { @Autowired private KustvaktConfiguration config; @Autowired private EncryptionIface crypto; @Autowired private EntityHandlerIface dao; public BasicHttpAuth() { } public BasicHttpAuth(KustvaktConfiguration config) { this.config = config; } public static String[] decode (String token) { //return OAuthUtils.decodeClientAuthenticationHeader(token); String[] tokens = token.split(" "); String encodedCred = null; if (!token.equals(tokens[0])) { if (tokens[0] != null && !tokens[0].isEmpty()) { if (!tokens[0].toLowerCase().equalsIgnoreCase("basic")) { return null; } encodedCred = tokens[1]; } } else { encodedCred = tokens[0]; } if(encodedCred != null && !"".equals(encodedCred)) { String decodedCreds = new String(Base64.decodeBase64(encodedCred)); if(decodedCreds.contains(":") && decodedCreds.split(":").length == 2) { String[] creds = decodedCreds.split(":"); if ((creds[0] != null && !creds[0].isEmpty()) && (creds[1] != null && !creds[1].isEmpty())) return decodedCreds.split(":"); } } return null; } public static String encode (String user, String pass) { String s = user + ":" + pass; return Attributes.BASIC_AUTHENTICATION + " " + new String(Base64.encodeBase64(s.getBytes())); } @Override public TokenContext getTokenContext(String authToken) throws KustvaktException { //fixme: handle via constructor String[] values = decode(authToken); if (values != null) { TokenContext c = new TokenContext(); User user = dao.getAccount(values[0]); if (user instanceof KorAPUser && ((KorAPUser) user).getPassword() != null) { boolean check = crypto.checkHash(values[1], ((KorAPUser) user).getPassword()); if (!check) return null; } c.setUsername(values[0]); c.setExpirationTime(TimeUtils.plusSeconds(this.config.getTokenTTL()).getMillis()); c.setAuthenticationType(AuthenticationType.DATABASE); // todo: for production mode, set true c.setSecureRequired(false); c.setToken(StringUtils.stripTokenType(authToken)); // fixme: you can make queries, but user sensitive data is off limits?! c.addContextParameter(Attributes.SCOPES, Scopes.Scope.search.toString()); return c; } return null; } // not supported! @Override public TokenContext createTokenContext(User user, Map<String, Object> attr) throws KustvaktException { return null; } @Override public void removeUserSession (String token) throws KustvaktException { throw new KustvaktException(StatusCodes.NOT_SUPPORTED); } @Override public TokenContext refresh (TokenContext context) throws KustvaktException { return null; } @Override public AuthenticationType getIdentifier () { return AuthenticationType.DATABASE; } }
Cleaned up basic authentication. Change-Id: I023a8554f1c1c2f2cfaadaab234eb792fa1a5a7c
full/src/main/java/de/ids_mannheim/korap/authentication/BasicAuthentication.java
Cleaned up basic authentication.
<ide><path>ull/src/main/java/de/ids_mannheim/korap/authentication/BasicAuthentication.java <ide> <ide> import java.util.Map; <ide> <del>import org.apache.commons.codec.binary.Base64; <ide> import org.springframework.beans.factory.annotation.Autowired; <ide> <add>import de.ids_mannheim.korap.authentication.framework.HttpAuthorizationHandler; <add>import de.ids_mannheim.korap.authentication.framework.TransferEncoding; <ide> import de.ids_mannheim.korap.config.Attributes; <ide> import de.ids_mannheim.korap.config.AuthenticationType; <ide> import de.ids_mannheim.korap.config.KustvaktConfiguration; <ide> import de.ids_mannheim.korap.config.Scopes; <add>import de.ids_mannheim.korap.dao.UserDao; <ide> import de.ids_mannheim.korap.exceptions.KustvaktException; <ide> import de.ids_mannheim.korap.exceptions.StatusCodes; <ide> import de.ids_mannheim.korap.interfaces.AuthenticationIface; <ide> import de.ids_mannheim.korap.interfaces.EncryptionIface; <del>import de.ids_mannheim.korap.interfaces.db.EntityHandlerIface; <ide> import de.ids_mannheim.korap.user.KorAPUser; <ide> import de.ids_mannheim.korap.user.TokenContext; <ide> import de.ids_mannheim.korap.user.User; <ide> import de.ids_mannheim.korap.utils.StringUtils; <ide> import de.ids_mannheim.korap.utils.TimeUtils; <ide> <del>/** EM: do not use at the moment, there is no authentication <del> * checking, formerly used a database. Should separate between <del> * authentication procedure and the real authentication checking <del> * method. <add>/** <add> * Implementation of encoding and decoding access token is moved to <add> * {@link TransferEncoding}. Moreover, implementation of HTTP <add> * Authentication framework, i.e. creation of authorization header, <add> * is defined in {@link HttpAuthorizationHandler}. <ide> * <add> * Basic authentication is intended to be used with a database. It is <add> * currently only used for testing using a dummy DAO (@see {@link UserDao}). <add> * <add> * <add> * @author margaretha <add> * @date 15/11/2017 <ide> * <ide> * @author hanl <ide> * @date 28/04/2015 <ide> */ <del>// todo: bean injection! <del>public class BasicHttpAuth implements AuthenticationIface { <add>public class BasicAuthentication implements AuthenticationIface { <ide> <add> @Autowired <add> private TransferEncoding transferEncoding; <ide> @Autowired <ide> private KustvaktConfiguration config; <ide> @Autowired <ide> private EncryptionIface crypto; <ide> @Autowired <del> private EntityHandlerIface dao; <del> <del> public BasicHttpAuth() { <add> private UserDao dao; <ide> <del> } <del> <del> public BasicHttpAuth(KustvaktConfiguration config) { <add> public BasicAuthentication (KustvaktConfiguration config) { <ide> this.config = config; <ide> } <ide> <del> <del> public static String[] decode (String token) { <del> //return OAuthUtils.decodeClientAuthenticationHeader(token); <del> String[] tokens = token.split(" "); <del> String encodedCred = null; <del> if (!token.equals(tokens[0])) { <del> if (tokens[0] != null && !tokens[0].isEmpty()) { <del> if (!tokens[0].toLowerCase().equalsIgnoreCase("basic")) { <del> return null; <del> } <del> encodedCred = tokens[1]; <del> } <del> } else { <del> encodedCred = tokens[0]; <del> } <del> if(encodedCred != null && !"".equals(encodedCred)) { <del> String decodedCreds = new String(Base64.decodeBase64(encodedCred)); <del> if(decodedCreds.contains(":") && decodedCreds.split(":").length == 2) { <del> String[] creds = decodedCreds.split(":"); <del> if ((creds[0] != null && !creds[0].isEmpty()) && (creds[1] != null && !creds[1].isEmpty())) <del> return decodedCreds.split(":"); <del> } <del> } <del> return null; <del> } <del> <del> <del> public static String encode (String user, String pass) { <del> String s = user + ":" + pass; <del> return Attributes.BASIC_AUTHENTICATION + " " <del> + new String(Base64.encodeBase64(s.getBytes())); <del> } <del> <del> <ide> @Override <del> public TokenContext getTokenContext(String authToken) <add> public TokenContext getTokenContext (String authToken) <ide> throws KustvaktException { <del> //fixme: handle via constructor <del> String[] values = decode(authToken); <add> // Hanl: fixme: handle via constructor <add> // EM: ? <add> String[] values = transferEncoding.decodeBase64(authToken); <ide> if (values != null) { <ide> TokenContext c = new TokenContext(); <ide> User user = dao.getAccount(values[0]); <del> if (user instanceof KorAPUser && ((KorAPUser) user).getPassword() != null) { <add> if (user instanceof KorAPUser <add> && ((KorAPUser) user).getPassword() != null) { <ide> boolean check = crypto.checkHash(values[1], <ide> ((KorAPUser) user).getPassword()); <ide> <del> if (!check) <del> return null; <add> if (!check) return null; <ide> } <ide> c.setUsername(values[0]); <del> c.setExpirationTime(TimeUtils.plusSeconds(this.config.getTokenTTL()).getMillis()); <del> c.setAuthenticationType(AuthenticationType.DATABASE); <add> c.setExpirationTime(TimeUtils.plusSeconds(this.config.getTokenTTL()) <add> .getMillis()); <add> c.setAuthenticationType(AuthenticationType.BASIC); <ide> // todo: for production mode, set true <ide> c.setSecureRequired(false); <add> // EM: is this secure? <ide> c.setToken(StringUtils.stripTokenType(authToken)); <ide> // fixme: you can make queries, but user sensitive data is off limits?! <ide> c.addContextParameter(Attributes.SCOPES, <ide> <ide> // not supported! <ide> @Override <del> public TokenContext createTokenContext(User user, Map<String, Object> attr) <add> public TokenContext createTokenContext (User user, Map<String, Object> attr) <ide> throws KustvaktException { <ide> return null; <ide> } <ide> <ide> <ide> @Override <del> public TokenContext refresh (TokenContext context) throws KustvaktException { <add> public TokenContext refresh (TokenContext context) <add> throws KustvaktException { <ide> return null; <ide> } <ide> <ide> <ide> @Override <ide> public AuthenticationType getIdentifier () { <del> return AuthenticationType.DATABASE; <add> return AuthenticationType.BASIC; <ide> } <ide> }
Java
mit
fbab2ee408599e79a4547f2b9266b3003f91e041
0
malotian/moltin.java.adventure.works
package com.moltin.adventure.works; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonObject; public class AdventureWorksData { private static final Logger LOGGER = LoggerFactory.getLogger(AdventureWorksData.class); private JsonArray categories = new JsonArray(); private JsonArray products = new JsonArray(); private JsonArray descriptions = new JsonArray(); private JsonArray images = new JsonArray(); private JsonArray imagesLink = new JsonArray(); private JsonArray variants = new JsonArray(); private JsonArray orderHeader = new JsonArray(); private JsonArray orderDetail = new JsonArray(); private JsonArray descriptionsLink = new JsonArray(); private Path directory = Paths.get("."); public AdventureWorksData(final Path directory) { setDirectory(directory); } public List<CSVRecord> _read(final String fileName, final CSVFormat format, final Charset encoding) throws IOException { final String fileNameOnly = FilenameUtils.getBaseName(fileName); final String fileExtensionOnly = FilenameUtils.getExtension(fileName); if (Files.exists(Paths.get(directory.toString(), fileNameOnly + ".clean." + fileExtensionOnly))) { LOGGER.info("reading: {}", Paths.get(directory.toString(), fileNameOnly + ".clean." + fileExtensionOnly)); return CSVParser.parse(new File(directory.toString(), fileNameOnly + ".clean." + fileExtensionOnly), encoding, format).getRecords(); } return CSVParser.parse(new File(directory.toString(), fileName), encoding, format).getRecords(); } void clean(final String fileName, final String[] patternsToRemove, final Charset encoding) throws IOException { final String fileNameOnly = FilenameUtils.getBaseName(fileName); final String fileExtensionOnly = FilenameUtils.getExtension(fileName); String textFromFile = FileUtils.readFileToString(new File(directory.toString(), fileName), encoding); for (final String pattern : patternsToRemove) { textFromFile = textFromFile.replaceAll(pattern, ""); } FileUtils.write(new File(directory.toString(), fileNameOnly + ".clean." + fileExtensionOnly), textFromFile, encoding); } void dump() throws JsonProcessingException, IOException { final File dumpDirectory = new File(directory.toString(), "processed"); FileUtils.deleteDirectory(dumpDirectory); FileUtils.forceMkdir(dumpDirectory); final Gson gson = new GsonBuilder().setPrettyPrinting().create(); FileUtils.write(new File(dumpDirectory, "categories.json"), gson.toJson(categories), StandardCharsets.US_ASCII); FileUtils.write(new File(dumpDirectory, "products.json"), gson.toJson(products), StandardCharsets.US_ASCII); FileUtils.write(new File(dumpDirectory, "descriptions.json"), gson.toJson(descriptions), StandardCharsets.US_ASCII); FileUtils.write(new File(dumpDirectory, "images.json"), gson.toJson(images), StandardCharsets.US_ASCII); FileUtils.write(new File(dumpDirectory, "imagesLink.json"), gson.toJson(imagesLink), StandardCharsets.US_ASCII); FileUtils.write(new File(dumpDirectory, "variants.json"), gson.toJson(variants), StandardCharsets.US_ASCII); FileUtils.write(new File(dumpDirectory, "orderHeader.json"), gson.toJson(orderHeader), StandardCharsets.US_ASCII); FileUtils.write(new File(dumpDirectory, "orderDetail.json"), gson.toJson(orderDetail), StandardCharsets.US_ASCII); FileUtils.write(new File(dumpDirectory, "descriptionsLink.json"), gson.toJson(descriptionsLink), StandardCharsets.US_ASCII); } public JsonArray getCategories() { return categories; } public JsonArray getDescriptions() { return descriptions; } public JsonArray getDescriptionsLink() { return descriptionsLink; } public JsonArray getImages() { return images; } public JsonArray getImagesLink() { return imagesLink; } public JsonArray getInventory() { return getProducts(); } public JsonArray getOrderDetail() { return orderDetail; } public JsonArray getOrderHeader() { return orderHeader; } public JsonArray getProducts() { return products; } public JsonArray getTransactions() { return getOrderHeader(); } public JsonArray getVariants() { return variants; } void initialize() throws IOException { clean("ProductModel.csv", new String[] { "<root.+?>[\\s\\S]+?</root>", "<p1:ProductDescription.+?>[\\s\\S]+?</p1:ProductDescription>", "<\\?.+?\\?>" }, StandardCharsets.UTF_16LE); clean("ProductDescription.csv", new String[] { "\"" }, StandardCharsets.UTF_16LE); setCategories(read("ProductSubcategory.csv", CSVFormat.TDF.withHeader("id", "parent", "name", "guid", "date"), StandardCharsets.US_ASCII)); setProducts(read("ProductModel.csv", CSVFormat.TDF.withDelimiter('|').withHeader("id", "name", "description", "instructions", "guid", "modified"), StandardCharsets.UTF_16LE, true)); setDescriptions(read("ProductDescription.csv", CSVFormat.TDF.withRecordSeparator("\n").withHeader("id", "description", "guid", "modified"), StandardCharsets.UTF_16LE)); setDescriptionsLink(read("ProductModelProductDescriptionCulture.csv", CSVFormat.TDF.withHeader("model", "description", "culture", "modified"), StandardCharsets.US_ASCII)); setImages(read("ProductPhoto.csv", CSVFormat.TDF.withDelimiter('|').withHeader("id", "thumbnail", "thumbnail_filename", "large", "large_filename", "date"), StandardCharsets.UTF_16LE, true)); setImagesLink(read("ProductProductPhoto.csv", CSVFormat.TDF.withHeader("product", "image", "primary", "modified"), StandardCharsets.US_ASCII)); setVariants(read("Product.csv", CSVFormat.TDF.withHeader("id", "name", "sku", "make", "finished", "color", "safetyStockLevel", "reorderPoint", "cost", "price", "size", "sizeUnit", "weightUnit", "weight", "daysToManufacture", "productLine", "class", "style", "subcategory", "model", "sellStartDate", "sellEndDate", "discontinuedDate", "guid", "modified"), StandardCharsets.US_ASCII)); setOrderHeader(read("SalesOrderHeader.csv", CSVFormat.TDF.withHeader("orderId", "revisionNumber", "orderDate", "dueDate", "shipDate", "status", "isOnline", "onlineNumber", "poNumber", "accountNumber", "customer", "salesPerson", "territory", "billTo", "shipTo", "shipMethod", "cc", "ccCode", "currency", "subTotal", "tax", "freight", "total", "comment", "guid", "date"), StandardCharsets.US_ASCII)); setOrderDetail(read("SalesOrderDetail.csv", CSVFormat.TDF.withHeader("orderId", "recordId", "tracking", "quantity", "productId", "offerId", "price", "discount", "total", "guid", "date"), StandardCharsets.US_ASCII)); variants.forEach(_v -> { final JsonObject v = _v.getAsJsonObject(); imagesLink.forEach(_l -> { final JsonObject l = _l.getAsJsonObject(); if (l.get("product").equals(v.get("id"))) { images.forEach(_i -> { final JsonObject i = _i.getAsJsonObject(); if (i.get("id").equals(l.get("image"))) { v.add("image", i); } }); } }); categories.forEach(_c -> { final JsonObject c = _c.getAsJsonObject(); if (c.get("id").equals(v.get("subcategory"))) { v.add("category", c); // LOGGER.debug("variant: {}, category: {}", v, c); } }); }); products.forEach(_p -> { final JsonObject p = _p.getAsJsonObject(); p.addProperty("description", "Description not available"); descriptionsLink.forEach(_l -> { final JsonObject l = _l.getAsJsonObject(); if (l.get("model").equals(p.get("id")) && "en".equals(l.get("culture"))) { descriptions.forEach(_d -> { final JsonObject d = _d.getAsJsonObject(); if (d.get("id").equals(l.get("description"))) { p.add("description", d.get("description")); } }); } }); final JsonArray colors = new JsonArray(); final JsonArray sizes = new JsonArray(); final JsonArray varities = new JsonArray(); variants.forEach(_v -> { final JsonObject v = _v.getAsJsonObject(); if (v.get("model").equals(p.get("id")) && v.has("category")) { varities.add(v); if (v.has("color") && !colors.contains(v.get("color"))) { colors.add(v.get("color")); } if (v.has("size") && !colors.contains(v.get("size"))) { sizes.add(v.get("size")); } } }); final JsonObject mod1 = new JsonObject(); mod1.addProperty("title", "color"); mod1.add("values", colors); final JsonObject mod2 = new JsonObject(); mod2.addProperty("title", "size"); mod2.add("values", sizes); final JsonArray modifiers = new JsonArray(); modifiers.add(mod1); modifiers.add(mod2); //@formatter:off p.add("variants", varities); p.add("modifiers", modifiers); //@formatter:on }); orderDetail.forEach(_line -> { final JsonObject line = _line.getAsJsonObject(); variants.forEach(_v1 -> { final JsonObject v1 = _v1.getAsJsonObject(); if (v1.get("id").equals(line.get("productId"))) { line.add("sku", v1.get("sku")); } }); }); final JsonObject groupedDetails = new JsonObject(); orderDetail.forEach(_od -> { final JsonObject od = _od.getAsJsonObject(); final String orderId = od.get("orderId").getAsString(); if (!groupedDetails.has(orderId)) { groupedDetails.add(orderId, new JsonArray()); } groupedDetails.get(orderId).getAsJsonArray().add(od); }); orderHeader.forEach(_oh -> { final JsonObject oh = _oh.getAsJsonObject(); oh.add("details", groupedDetails.get("orderId")); }); } public JsonArray read(final String fileName, final CSVFormat format, final Charset encoding) throws IOException { return read(fileName, format, encoding, false); } public JsonArray read(final String fileName, final CSVFormat format, final Charset encoding, boolean strip) throws IOException { final JsonArray ja = new JsonArray(); final List<CSVRecord> records = _read(fileName, format, encoding); records.forEach(r -> { final JsonObject jo = new JsonObject(); r.toMap().forEach((k, v) -> { if (strip) { v = StringUtils.substring(v, 0, -1); } jo.addProperty(k, v); }); ja.add(jo); }); return ja; } public void setCategories(final JsonArray categories) { this.categories = categories; } public void setDescriptions(final JsonArray descriptions) { this.descriptions = descriptions; } private void setDescriptionsLink(final JsonArray descriptionsLink) { this.descriptionsLink = descriptionsLink; } private void setDirectory(final Path directory) { this.directory = directory; } public void setImages(final JsonArray images) { this.images = images; } public void setImagesLink(final JsonArray imagesLink) { this.imagesLink = imagesLink; } public void setOrderDetail(final JsonArray orderDetail) { this.orderDetail = orderDetail; } public void setOrderHeader(final JsonArray orderHeader) { this.orderHeader = orderHeader; } public void setProducts(final JsonArray products) { this.products = products; } public void setVariants(final JsonArray variants) { this.variants = variants; } }
src/main/java/com/moltin/adventure/works/AdventureWorksData.java
package com.moltin.adventure.works; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVParser; import org.apache.commons.csv.CSVRecord; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonArray; import com.google.gson.JsonObject; public class AdventureWorksData { private static final Logger LOGGER = LoggerFactory.getLogger(AdventureWorksData.class); private JsonArray categories = new JsonArray(); private JsonArray products = new JsonArray(); private JsonArray descriptions = new JsonArray(); private JsonArray images = new JsonArray(); private JsonArray imagesLink = new JsonArray(); private JsonArray variants = new JsonArray(); private JsonArray orderHeader = new JsonArray(); private JsonArray orderDetail = new JsonArray(); private JsonArray descriptionsLink = new JsonArray(); private Path directory = Paths.get("."); public AdventureWorksData(final Path directory) { setDirectory(directory); } public List<CSVRecord> _read(final String fileName, final CSVFormat format, final Charset encoding) throws IOException { final String fileNameOnly = FilenameUtils.getBaseName(fileName); final String fileExtensionOnly = FilenameUtils.getExtension(fileName); if (Files.exists(Paths.get(directory.toString(), fileNameOnly + ".clean." + fileExtensionOnly))) { LOGGER.info("reading: {}", Paths.get(directory.toString(), fileNameOnly + ".clean." + fileExtensionOnly)); return CSVParser.parse(new File(directory.toString(), fileNameOnly + ".clean." + fileExtensionOnly), encoding, format).getRecords(); } return CSVParser.parse(new File(directory.toString(), fileName), encoding, format).getRecords(); } void clean(final String fileName, final String[] patternsToRemove, final Charset encoding) throws IOException { final String fileNameOnly = FilenameUtils.getBaseName(fileName); final String fileExtensionOnly = FilenameUtils.getExtension(fileName); String textFromFile = FileUtils.readFileToString(new File(directory.toString(), fileName), encoding); for (final String pattern : patternsToRemove) { textFromFile = textFromFile.replaceAll(pattern, ""); } FileUtils.write(new File(directory.toString(), fileNameOnly + ".clean." + fileExtensionOnly), textFromFile, encoding); } void dump() throws JsonProcessingException, IOException { final File dumpDirectory = new File(directory.toString(), "processed"); FileUtils.deleteDirectory(dumpDirectory); FileUtils.forceMkdir(dumpDirectory); final Gson gson = new GsonBuilder().setPrettyPrinting().create(); FileUtils.write(new File(dumpDirectory, "categories.json"), gson.toJson(categories), StandardCharsets.US_ASCII); FileUtils.write(new File(dumpDirectory, "products.json"), gson.toJson(products), StandardCharsets.US_ASCII); FileUtils.write(new File(dumpDirectory, "descriptions.json"), gson.toJson(descriptions), StandardCharsets.US_ASCII); FileUtils.write(new File(dumpDirectory, "images.json"), gson.toJson(images), StandardCharsets.US_ASCII); FileUtils.write(new File(dumpDirectory, "imagesLink.json"), gson.toJson(imagesLink), StandardCharsets.US_ASCII); FileUtils.write(new File(dumpDirectory, "variants.json"), gson.toJson(variants), StandardCharsets.US_ASCII); FileUtils.write(new File(dumpDirectory, "orderHeader.json"), gson.toJson(orderHeader), StandardCharsets.US_ASCII); FileUtils.write(new File(dumpDirectory, "orderDetail.json"), gson.toJson(orderDetail), StandardCharsets.US_ASCII); FileUtils.write(new File(dumpDirectory, "descriptionsLink.json"), gson.toJson(descriptionsLink), StandardCharsets.US_ASCII); } public JsonArray getCategories() { return categories; } public JsonArray getDescriptions() { return descriptions; } public JsonArray getDescriptionsLink() { return descriptionsLink; } public JsonArray getImages() { return images; } public JsonArray getImagesLink() { return imagesLink; } public JsonArray getInventory() { return getProducts(); } public JsonArray getOrderDetail() { return orderDetail; } public JsonArray getOrderHeader() { return orderHeader; } public JsonArray getProducts() { return products; } public JsonArray getTransactions() { return getOrderHeader(); } public JsonArray getVariants() { return variants; } void initialize() throws IOException { clean("ProductModel.csv", new String[] { "<root.+?>[\\s\\S]+?</root>", "<p1:ProductDescription.+?>[\\s\\S]+?</p1:ProductDescription>", "<\\?.+?\\?>" }, StandardCharsets.UTF_16LE); clean("ProductDescription.csv", new String[] { "\"" }, StandardCharsets.UTF_16LE); setCategories(read("ProductSubcategory.csv", CSVFormat.TDF.withHeader("id", "parent", "name", "guid", "date"), StandardCharsets.US_ASCII)); setProducts(read("ProductModel.csv", CSVFormat.TDF.withDelimiter('|').withHeader("id", "name", "description", "instructions", "guid", "modified"), StandardCharsets.UTF_16LE, true)); setDescriptions(read("ProductDescription.csv", CSVFormat.TDF.withRecordSeparator("\n").withHeader("id", "description", "guid", "modified"), StandardCharsets.UTF_16LE)); setDescriptionsLink(read("ProductModelProductDescriptionCulture.csv", CSVFormat.TDF.withHeader("model", "description", "culture", "modified"), StandardCharsets.US_ASCII)); setImages(read("ProductPhoto.csv", CSVFormat.TDF.withDelimiter('|').withHeader("id", "thumbnail", "thumbnail_filename", "large", "large_filename", "date"), StandardCharsets.UTF_16LE, true)); setImagesLink(read("ProductProductPhoto.csv", CSVFormat.TDF.withHeader("product", "image", "primary", "modified"), StandardCharsets.US_ASCII)); setVariants(read("Product.csv", CSVFormat.TDF.withHeader("id", "name", "sku", "make", "finished", "color", "safetyStockLevel", "reorderPoint", "cost", "price", "size", "sizeUnit", "weightUnit", "weight", "daysToManufacture", "productLine", "class", "style", "subcategory", "model", "sellStartDate", "sellEndDate", "discontinuedDate", "guid", "modified"), StandardCharsets.US_ASCII)); setOrderHeader(read("SalesOrderHeader.csv", CSVFormat.TDF.withHeader("orderId", "revisionNumber", "orderDate", "dueDate", "shipDate", "status", "isOnline", "onlineNumber", "poNumber", "accountNumber", "customer", "salesPerson", "territory", "billTo", "shipTo", "shipMethod", "cc", "ccCode", "currency", "subTotal", "tax", "freight", "total", "comment", "guid", "date"), StandardCharsets.US_ASCII)); setOrderDetail(read("SalesOrderDetail.csv", CSVFormat.TDF.withHeader("orderId", "recordId", "tracking", "quantity", "productId", "offerId", "price", "discount", "total", "guid", "date"), StandardCharsets.US_ASCII)); variants.forEach(_v -> { final JsonObject v = _v.getAsJsonObject(); imagesLink.forEach(_l -> { final JsonObject l = _l.getAsJsonObject(); if (l.get("product").equals(v.get("id"))) { images.forEach(_i -> { final JsonObject i = _i.getAsJsonObject(); if (i.get("id").equals(l.get("image"))) { v.add("image", i); } }); } }); categories.forEach(_c -> { final JsonObject c = _c.getAsJsonObject(); if (c.get("id").equals(v.get("subcategory"))) { v.add("category", c); // LOGGER.debug("variant: {}, category: {}", v, c); } }); }); products.forEach(_p -> { final JsonObject p = _p.getAsJsonObject(); p.addProperty("description", "Description not available"); descriptionsLink.forEach(_l -> { final JsonObject l = _l.getAsJsonObject(); if (l.get("model").equals(p.get("id")) && "en".equals(l.get("culture"))) { descriptions.forEach(_d -> { final JsonObject d = _d.getAsJsonObject(); if (d.get("id").equals(l.get("description"))) { p.add("description", d.get("description")); } }); } }); final JsonArray colors = new JsonArray(); final JsonArray sizes = new JsonArray(); final JsonArray varities = new JsonArray(); variants.forEach(_v -> { final JsonObject v = _v.getAsJsonObject(); if (v.get("model").equals(p.get("id")) && v.has("category")) { varities.add(v); if (v.has("color")) { colors.add(v.get("color")); } if (v.has("size")) { sizes.add(v.get("size")); } } }); final JsonObject mod1 = new JsonObject(); mod1.addProperty("title", "color"); mod1.add("values", colors); final JsonObject mod2 = new JsonObject(); mod2.addProperty("title", "size"); mod2.add("values", sizes); final JsonArray modifiers = new JsonArray(); modifiers.add(mod1); modifiers.add(mod2); //@formatter:off p.add("variants", varities); p.add("modifiers", modifiers); //@formatter:on }); orderDetail.forEach(_line -> { final JsonObject line = _line.getAsJsonObject(); variants.forEach(_v1 -> { final JsonObject v1 = _v1.getAsJsonObject(); if (v1.get("id").equals(line.get("productId"))) { line.add("sku", v1.get("sku")); } }); }); final JsonObject groupedDetails = new JsonObject(); orderDetail.forEach(_od -> { final JsonObject od = _od.getAsJsonObject(); final String orderId = od.get("orderId").getAsString(); if (!groupedDetails.has(orderId)) { groupedDetails.add(orderId, new JsonArray()); } groupedDetails.get(orderId).getAsJsonArray().add(od); }); orderHeader.forEach(_oh -> { final JsonObject oh = _oh.getAsJsonObject(); oh.add("details", groupedDetails.get("orderId")); }); } public JsonArray read(final String fileName, final CSVFormat format, final Charset encoding) throws IOException { return read(fileName, format, encoding, false); } public JsonArray read(final String fileName, final CSVFormat format, final Charset encoding, boolean strip) throws IOException { final JsonArray ja = new JsonArray(); final List<CSVRecord> records = _read(fileName, format, encoding); records.forEach(r -> { final JsonObject jo = new JsonObject(); r.toMap().forEach((k, v) -> { if (strip) { v = StringUtils.substring(v, 0, -1); } jo.addProperty(k, v); }); ja.add(jo); }); return ja; } public void setCategories(final JsonArray categories) { this.categories = categories; } public void setDescriptions(final JsonArray descriptions) { this.descriptions = descriptions; } private void setDescriptionsLink(final JsonArray descriptionsLink) { this.descriptionsLink = descriptionsLink; } private void setDirectory(final Path directory) { this.directory = directory; } public void setImages(final JsonArray images) { this.images = images; } public void setImagesLink(final JsonArray imagesLink) { this.imagesLink = imagesLink; } public void setOrderDetail(final JsonArray orderDetail) { this.orderDetail = orderDetail; } public void setOrderHeader(final JsonArray orderHeader) { this.orderHeader = orderHeader; } public void setProducts(final JsonArray products) { this.products = products; } public void setVariants(final JsonArray variants) { this.variants = variants; } }
unique modifiers
src/main/java/com/moltin/adventure/works/AdventureWorksData.java
unique modifiers
<ide><path>rc/main/java/com/moltin/adventure/works/AdventureWorksData.java <ide> final JsonObject v = _v.getAsJsonObject(); <ide> if (v.get("model").equals(p.get("id")) && v.has("category")) { <ide> varities.add(v); <del> if (v.has("color")) { <add> if (v.has("color") && !colors.contains(v.get("color"))) { <ide> colors.add(v.get("color")); <ide> } <del> if (v.has("size")) { <add> if (v.has("size") && !colors.contains(v.get("size"))) { <ide> sizes.add(v.get("size")); <ide> } <ide> }
Java
mit
ad2323b7cb457c74482495330dae42ad347632f3
0
jjwedemyer/studies
import java.lang.Math; import java.util.*; /** * Test class */ public class Sortthings{ public static void main(String[] args) { //Liste mit 1-20000 erzeugen List<Integer> list = new ArrayList<Integer>(); for (int i = 1; i < 200; i++) { list.add(i); } Collections.shuffle(list); //Array aus Liste erstellen Integer[] a = list.toArray(new Integer[list.size()]); //Kopie erstellen Integer[] b = new Integer[list.size()]; System.arraycopy(a, 0, b, 0, list.size()); int r = Sorter.quickSort(a,a.length/2,0,a.length-1); System.arraycopy(b, 0, a, 0, list.size()); int r2 = Sorter.quickSort(a,Sorter.randomWithRange(0,a.length-1),0,a.length-1); System.arraycopy(b, 0, a, 0, list.size()); int r3 = Sorter.insertionSort(a); System.out.println("Vergleiche quickSort1: " + r); System.out.println("Vergleiche quickSort2: " + r2); System.out.println("Vergleiche insertionSort: " + r3); } } /** * This class implements the sorting algorithms */ class Sorter{ public static <E extends Comparable<E>> int insertionSort(E[] array){ int n = array.length; int counter = 0; for(int j=2; j<=n; j++){ E key = array[j]; int i = j; while(i>1 && array[i-1].compareTo(key) > 0) { counter++; array[i] = array[i-1]; i--; } array[i] = key; } return counter; } public static <E extends Comparable<E>> int quickSort(E[] array, int partitionScheme, int low, int high){ int lowcount=0,highcount=0; Pair<Integer,Integer> p = null; if (low < high) { p = partition(array,partitionScheme,low,high); System.out.println(p); try{ lowcount = quickSort(array, partitionScheme, low, p.first-1);} catch (Exception e){ e.printStackTrace(); } highcount = quickSort(array,partitionScheme, p.first+1, high); } return (lowcount+highcount+p.second); } protected static <E extends Comparable<E>> Pair<Integer,Integer> partition(E[] array, int partitionScheme, int low, int high){ //TODO: implement counting behavior int count,i,j; i = low-1; j = high+1; count = j; E t,pivot = array[partitionScheme]; while(true){ do{ ++i; }while(array[i].compareTo(pivot) <= 0 && i <= high); do{ --j; }while(array[j].compareTo(pivot) > 0); if (i >= j) break; t = array[i]; array[i] = array[j]; array[j] = t; } t = array[low]; array[low] = array[j]; array[j] = t; return new Pair<Integer,Integer>(j,count); } //random helper functions public static int randomWithRange(int min, int max) { int range = Math.abs(max - min) + 1; return (int)(Math.random() * range) + (min <= max ? min : max); } } /** * Helping class */ class Pair<F, S> { public F first; public S second; public Pair(F f,S s){ this.first = f; this.second = s; } public String toString(){ return "First: "+first+" Second: "+second; } }
Info3/Sortthings.java
import java.lang.Math; import java.util.*; /** * Test class */ public class Sortthings{ public static void main(String[] args) { //Liste mit 1-20000 erzeugen List<Integer> list = new ArrayList<Integer>(); for (int i = 1; i < 20000; i++) { list.add(i); } Collections.shuffle(list); //Array aus Liste erstellen Integer[] a = list.toArray(new Integer[list.size()]); //Kopie erstellen Integer[] b = new Integer[list.size()]; System.arraycopy(a, 0, b, 0, list.size()); int r = Sorter.quickSort(a,a.length/2,0,a.length-1); System.arraycopy(b, 0, a, 0, list.size()); int r2 = Sorter.quickSort(a,Sorter.randomWithRange(0,a.length-1),0,a.length-1); System.arraycopy(b, 0, a, 0, list.size()); int r3 = Sorter.insertionSort(a); System.out.println("Vergleiche quickSort1: " + r); System.out.println("Vergleiche quickSort2: " + r2); System.out.println("Vergleiche insertionSort: " + r3); } } /** * This class implements the sorting algorithms */ class Sorter{ public static <E extends Comparable<E>> int insertionSort(E[] array){ int n = array.length; int counter = 0; for(int j=2; j<=n; j++){ E key = array[j]; int i = j; while(i>1 && array[i-1].compareTo(key) > 0) { counter++; array[i] = array[i-1]; i--; } array[i] = key; } return counter; } public static <E extends Comparable<E>> int quickSort(E[] array, int partitionScheme, int low, int high){ int lowcount=0,highcount=0; Pair<Integer,Integer> p = null; if (low < high) { p = partition(array,partitionScheme,low,high); lowcount = quickSort(array,partitionScheme, low, p.first-1); highcount = quickSort(array,partitionScheme, p.first+1, high); } return (lowcount+highcount+p.second); } protected static <E extends Comparable<E>> Pair<Integer,Integer> partition(E[] array, int partitionScheme, int low, int high){ //TODO: implement counting behavior int count,i,j; i = low-1; j = high+1; count = j; E t,pivot = array[partitionScheme]; while(true){ do{ ++i; }while(array[i].compareTo(pivot) <= 0 && i <= high); do{ --j; }while(array[j].compareTo(pivot) > 0); if (i >= j) break; t = array[i]; array[i] = array[j]; array[j] = t; } t = array[low]; array[low] = array [j]; return new Pair<Integer,Integer>(j,count); } //random helper functions public static int randomWithRange(int min, int max) { int range = Math.abs(max - min) + 1; return (int)(Math.random() * range) + (min <= max ? min : max); } } /** * Helping class */ class Pair<F, S> { public F first; public S second; public Pair(F f,S s){ this.first = f; this.second = s; } }
FUCK :poop: NullPointers
Info3/Sortthings.java
FUCK :poop: NullPointers
<ide><path>nfo3/Sortthings.java <ide> public static void main(String[] args) { <ide> //Liste mit 1-20000 erzeugen <ide> List<Integer> list = new ArrayList<Integer>(); <del> for (int i = 1; i < 20000; i++) { <add> for (int i = 1; i < 200; i++) { <ide> list.add(i); <ide> } <ide> Collections.shuffle(list); <ide> Pair<Integer,Integer> p = null; <ide> if (low < high) { <ide> p = partition(array,partitionScheme,low,high); <del> lowcount = quickSort(array,partitionScheme, low, p.first-1); <add> System.out.println(p); <add> try{ <add> lowcount = quickSort(array, partitionScheme, low, p.first-1);} catch (Exception e){ <add> e.printStackTrace(); <add> } <ide> highcount = quickSort(array,partitionScheme, p.first+1, high); <ide> } <ide> return (lowcount+highcount+p.second); <ide> if (i >= j) break; <ide> t = array[i]; array[i] = array[j]; array[j] = t; <ide> } <del> t = array[low]; array[low] = array [j]; <add> t = array[low]; array[low] = array[j]; array[j] = t; <ide> return new Pair<Integer,Integer>(j,count); <ide> <ide> } <ide> this.first = f; <ide> this.second = s; <ide> } <add> public String toString(){ <add> return "First: "+first+" Second: "+second; <add> } <ide> }
Java
apache-2.0
85ad560580d3a3e5fd64561addaba307d5f15059
0
mario-areias/zaproxy,robocoder/zaproxy,kingthorin/zaproxy,gmaran23/zaproxy,robocoder/zaproxy,tjackiw/zaproxy,gsavastano/zaproxy,meitar/zaproxy,thamizarasu/zaproxy,thc202/zaproxy,JordanGS/zaproxy,rajiv65/zaproxy,DJMIN/zaproxy,ozzyjohnson/zaproxy,pdehaan/zaproxy,kingthorin/zaproxy,gsavastano/zaproxy,Ali-Razmjoo/zaproxy,JordanGS/zaproxy,gmaran23/zaproxy,Ye-Yong-Chi/zaproxy,cassiodeveloper/zaproxy,JordanGS/zaproxy,thamizarasu/zaproxy,zapbot/zaproxy,psiinon/zaproxy,Ye-Yong-Chi/zaproxy,mabdi/zaproxy,mabdi/zaproxy,psiinon/zaproxy,veggiespam/zaproxy,zapbot/zaproxy,mario-areias/zaproxy,kingthorin/zaproxy,efdutra/zaproxy,rajiv65/zaproxy,kingthorin/zaproxy,meitar/zaproxy,Harinus/zaproxy,Harinus/zaproxy,mabdi/zaproxy,mabdi/zaproxy,zaproxy/zaproxy,UjuE/zaproxy,mustafa421/zaproxy,profjrr/zaproxy,Ali-Razmjoo/zaproxy,0xkasun/zaproxy,cassiodeveloper/zaproxy,NVolcz/zaproxy,NVolcz/zaproxy,gsavastano/zaproxy,veggiespam/zaproxy,profjrr/zaproxy,urgupluoglu/zaproxy,Harinus/zaproxy,UjuE/zaproxy,pdehaan/zaproxy,zapbot/zaproxy,zapbot/zaproxy,tjackiw/zaproxy,mabdi/zaproxy,UjuE/zaproxy,profjrr/zaproxy,Ali-Razmjoo/zaproxy,0xkasun/zaproxy,tjackiw/zaproxy,lightsey/zaproxy,mustafa421/zaproxy,profjrr/zaproxy,JordanGS/zaproxy,zapbot/zaproxy,DJMIN/zaproxy,robocoder/zaproxy,meitar/zaproxy,robocoder/zaproxy,Ye-Yong-Chi/zaproxy,psiinon/zaproxy,jorik041/zaproxy,pdehaan/zaproxy,zaproxy/zaproxy,veggiespam/zaproxy,profjrr/zaproxy,JordanGS/zaproxy,UjuE/zaproxy,NVolcz/zaproxy,meitar/zaproxy,cassiodeveloper/zaproxy,tjackiw/zaproxy,kingthorin/zaproxy,0xkasun/zaproxy,thc202/zaproxy,zaproxy/zaproxy,MD14/zaproxy,tjackiw/zaproxy,gsavastano/zaproxy,0xkasun/zaproxy,zaproxy/zaproxy,pdehaan/zaproxy,lightsey/zaproxy,DJMIN/zaproxy,Ali-Razmjoo/zaproxy,gmaran23/zaproxy,urgupluoglu/zaproxy,efdutra/zaproxy,MD14/zaproxy,rajiv65/zaproxy,JordanGS/zaproxy,lightsey/zaproxy,robocoder/zaproxy,Ali-Razmjoo/zaproxy,thamizarasu/zaproxy,NVolcz/zaproxy,efdutra/zaproxy,urgupluoglu/zaproxy,mario-areias/zaproxy,gmaran23/zaproxy,0xkasun/zaproxy,profjrr/zaproxy,thamizarasu/zaproxy,urgupluoglu/zaproxy,pdehaan/zaproxy,NVolcz/zaproxy,UjuE/zaproxy,UjuE/zaproxy,UjuE/zaproxy,thc202/zaproxy,thc202/zaproxy,pdehaan/zaproxy,ozzyjohnson/zaproxy,ozzyjohnson/zaproxy,rajiv65/zaproxy,MD14/zaproxy,gsavastano/zaproxy,DJMIN/zaproxy,jorik041/zaproxy,efdutra/zaproxy,Harinus/zaproxy,Ye-Yong-Chi/zaproxy,thamizarasu/zaproxy,veggiespam/zaproxy,meitar/zaproxy,gsavastano/zaproxy,Ye-Yong-Chi/zaproxy,thc202/zaproxy,urgupluoglu/zaproxy,jorik041/zaproxy,DJMIN/zaproxy,zaproxy/zaproxy,meitar/zaproxy,robocoder/zaproxy,rajiv65/zaproxy,lightsey/zaproxy,psiinon/zaproxy,mabdi/zaproxy,efdutra/zaproxy,psiinon/zaproxy,MD14/zaproxy,meitar/zaproxy,gmaran23/zaproxy,mustafa421/zaproxy,ozzyjohnson/zaproxy,lightsey/zaproxy,kingthorin/zaproxy,Harinus/zaproxy,efdutra/zaproxy,robocoder/zaproxy,cassiodeveloper/zaproxy,0xkasun/zaproxy,urgupluoglu/zaproxy,psiinon/zaproxy,thamizarasu/zaproxy,Ali-Razmjoo/zaproxy,gmaran23/zaproxy,veggiespam/zaproxy,mabdi/zaproxy,surikato/zaproxy,gmaran23/zaproxy,psiinon/zaproxy,cassiodeveloper/zaproxy,MD14/zaproxy,thamizarasu/zaproxy,Ye-Yong-Chi/zaproxy,DJMIN/zaproxy,profjrr/zaproxy,JordanGS/zaproxy,jorik041/zaproxy,jorik041/zaproxy,surikato/zaproxy,cassiodeveloper/zaproxy,ozzyjohnson/zaproxy,tjackiw/zaproxy,Ye-Yong-Chi/zaproxy,mario-areias/zaproxy,tjackiw/zaproxy,ozzyjohnson/zaproxy,mario-areias/zaproxy,MD14/zaproxy,mustafa421/zaproxy,mustafa421/zaproxy,Ali-Razmjoo/zaproxy,mustafa421/zaproxy,efdutra/zaproxy,thc202/zaproxy,kingthorin/zaproxy,veggiespam/zaproxy,jorik041/zaproxy,zapbot/zaproxy,surikato/zaproxy,surikato/zaproxy,lightsey/zaproxy,NVolcz/zaproxy,cassiodeveloper/zaproxy,Harinus/zaproxy,zaproxy/zaproxy,mustafa421/zaproxy,lightsey/zaproxy,gsavastano/zaproxy,urgupluoglu/zaproxy,zaproxy/zaproxy,mario-areias/zaproxy,0xkasun/zaproxy,rajiv65/zaproxy,Harinus/zaproxy,pdehaan/zaproxy,NVolcz/zaproxy,zapbot/zaproxy,mario-areias/zaproxy,jorik041/zaproxy,MD14/zaproxy,DJMIN/zaproxy,surikato/zaproxy,surikato/zaproxy,surikato/zaproxy,rajiv65/zaproxy,ozzyjohnson/zaproxy,veggiespam/zaproxy,meitar/zaproxy,thc202/zaproxy
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2010 [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zaproxy.zap.model; import java.util.Collections; import java.util.List; import org.parosproxy.paros.Constant; public final class Vulnerabilities { private static VulnerabilitiesI18NMap vulnerabilitiesI18NMap = null; private Vulnerabilities() { } private static synchronized void init() { if (vulnerabilitiesI18NMap == null) { VulnerabilitiesLoader loader = new VulnerabilitiesLoader(Constant.getZapInstall() + Constant.LANG_DIR, Constant.VULNS_BASE); vulnerabilitiesI18NMap = loader.load(); } } /** * Gets an unmodifiable {@code List} containing all the * {@code Vulnerability} for the current active Locale. * They are loaded from the xml files as specified by the {@code Constant}. * <p> * An empty {@code List} is returned if any error occurred while opening the * file. The returned {@code List} is guaranteed to be <i>non</i> * {@code null}. * </p> * <p> * <b>Note:</b> Trying to modify the list will result in an * {@code UnsupportedOperationException}. * </p> * * @return An unmodifiable {@code List} containing all the * {@code Vulnerability} loaded, never {@code null}. * * @see Constant#VULNS_CONFIG */ public static List<Vulnerability> getAllVulnerabilities() { initializeIfEmpty(); return Collections.unmodifiableList(vulnerabilitiesI18NMap.getVulnerabilityList(Constant.getLocale().toString())); } public static Vulnerability getVulnerability (String name) { initializeIfEmpty(); return vulnerabilitiesI18NMap.getVulnerabilityByName(name, Constant.getLocale().toString()); } private static void initializeIfEmpty() { if (vulnerabilitiesI18NMap == null) { init(); } } public static String getDescription(Vulnerability vuln) { if (vuln != null) { return vuln.getDescription(); } return "Failed to load vulnerability description from file"; } public static String getSolution(Vulnerability vuln) { if (vuln != null) { return vuln.getSolution(); } return "Failed to load vulnerability solution from file"; } public static String getReference(Vulnerability vuln) { if (vuln != null) { StringBuilder sb = new StringBuilder(); for (String ref : vuln.getReferences()) { if (sb.length() > 0) { sb.append('\n'); } sb.append(ref); } return sb.toString(); } return "Failed to load vulnerability reference from file"; } }
src/org/zaproxy/zap/model/Vulnerabilities.java
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * Copyright 2010 [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.zaproxy.zap.model; import java.util.Collections; import java.util.List; import org.parosproxy.paros.Constant; public class Vulnerabilities { private static VulnerabilitiesI18NMap vulnerabilitiesI18NMap = null; private Vulnerabilities() { } private static synchronized void init() { if (vulnerabilitiesI18NMap == null) { VulnerabilitiesLoader loader = new VulnerabilitiesLoader(Constant.getZapInstall() + Constant.LANG_DIR, Constant.VULNS_BASE); vulnerabilitiesI18NMap = loader.load(); } } /** * Gets an unmodifiable {@code List} containing all the * {@code Vulnerability} for the current active Locale. * They are loaded from the xml files as specified by the {@code Constant}. * <p> * An empty {@code List} is returned if any error occurred while opening the * file. The returned {@code List} is guaranteed to be <i>non</i> * {@code null}. * </p> * <p> * <b>Note:</b> Trying to modify the list will result in an * {@code UnsupportedOperationException}. * </p> * * @return An unmodifiable {@code List} containing all the * {@code Vulnerability} loaded, never {@code null}. * * @see Constant#VULNS_CONFIG */ public static List<Vulnerability> getAllVulnerabilities() { initializeIfEmpty(); return Collections.unmodifiableList(vulnerabilitiesI18NMap.getVulnerabilityList(Constant.getLocale().toString())); } public static Vulnerability getVulnerability (String name) { initializeIfEmpty(); return vulnerabilitiesI18NMap.getVulnerabilityByName(name, Constant.getLocale().toString()); } private static void initializeIfEmpty() { if (vulnerabilitiesI18NMap == null) { init(); } } }
Added utility methods for getting default value if a Vulnerability was not properly loaded.
src/org/zaproxy/zap/model/Vulnerabilities.java
Added utility methods for getting default value if a Vulnerability was not properly loaded.
<ide><path>rc/org/zaproxy/zap/model/Vulnerabilities.java <ide> <ide> import org.parosproxy.paros.Constant; <ide> <del>public class Vulnerabilities { <add>public final class Vulnerabilities { <ide> <ide> private static VulnerabilitiesI18NMap vulnerabilitiesI18NMap = null; <ide> <ide> init(); <ide> } <ide> } <add> <add> public static String getDescription(Vulnerability vuln) { <add> if (vuln != null) { <add> return vuln.getDescription(); <add> } <add> return "Failed to load vulnerability description from file"; <add> } <add> <add> public static String getSolution(Vulnerability vuln) { <add> if (vuln != null) { <add> return vuln.getSolution(); <add> } <add> return "Failed to load vulnerability solution from file"; <add> } <add> <add> public static String getReference(Vulnerability vuln) { <add> if (vuln != null) { <add> StringBuilder sb = new StringBuilder(); <add> for (String ref : vuln.getReferences()) { <add> if (sb.length() > 0) { <add> sb.append('\n'); <add> } <add> sb.append(ref); <add> } <add> return sb.toString(); <add> } <add> return "Failed to load vulnerability reference from file"; <add> } <ide> }
Java
apache-2.0
ea1b5bdb0c4f6eab549591d9d94d7924b41662f2
0
nezda/yawni,nezda/yawni,nezda/yawni,nezda/yawni,nezda/yawni
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.yawni.wn.browser; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.*; /** * The {@code TextPrompt} class will display a prompt over top of a text component when * the {@link Document} of the text component is empty. The Show property is used to * determine the visibility of the prompt. * * <p> The {@link Font} and foreground {@link Color} of the prompt will default to those properties * of the parent text component. You are free to change the properties after * class construction. * * <p> Courtesy <a href="http://tips4java.wordpress.com/2009/11/29/text-prompt/"> * http://tips4java.wordpress.com/2009/11/29/text-prompt/</a> */ public class TextPrompt extends JLabel implements FocusListener, DocumentListener, PropertyChangeListener { public enum Show { // show prompt independent of focus (disappears on typing into textComponent though) ALWAYS, FOCUS_GAINED, FOCUS_LOST; } private final JTextComponent sourceTextComponent; private final JTextComponent targetTextComponent; private Show show; private boolean showPromptOnce; private int focusLost; // default configuration: // Listen for content/Document AND focus changes on textComponent (typically a JTextField) // and render self as child component of textComponent based on this // desired configuration: // Listen for content/Document changes on textComponent and change label content. // Position self (label) horizontally centered and about 20% of the from the top // // sourceTextComponent: listened to for content/focus changes // targetTextComponent: where TextPrompt is installed // // bugs: // - BOTH source and target text components need to be empty to trigger prompt // - consider property change listener enable/disable and disabling resultEditorPane when searchField changes // - tests are dead locking!? // - label should have larger font // - maybe label should be in italics or a serif font // - use this to replace Status.INTRO functinoality ("Enter search word...") // and maybe No search results // - fade in/out public TextPrompt(final String promptText, final JTextComponent sourceTextComponent, final JTextComponent targetTextComponent) { this.sourceTextComponent = sourceTextComponent; this.targetTextComponent = targetTextComponent; setShow(Show.ALWAYS); setText(promptText); setHorizontalTextPosition(CENTER); setAlignmentX(CENTER_ALIGNMENT); setAlignmentY(0.2f); // setFont(targetTextComponent.getFont().deriveFont(Font.ITALIC, 24.0f)); // setFont(new Font("Serif", Font.ITALIC, 24)); setFont(new Font("Serif", Font.PLAIN, 24)); setForeground(targetTextComponent.getForeground()); sourceTextComponent.addFocusListener(this); sourceTextComponent.getDocument().addDocumentListener(this); // sourceTextComponent.addPropertyChangeListener("document", this); // targetTextComponent.getDocument().addDocumentListener(this); targetTextComponent.addPropertyChangeListener("document", this); targetTextComponent.setLayout(new BoxLayout(targetTextComponent, BoxLayout.Y_AXIS)); // put space above equal to 1 blank line of text targetTextComponent.add(Box.createVerticalStrut(getFontMetrics(getFont()).getHeight())); targetTextComponent.add(this); checkForPrompt(); } /** * Convenience method to change the alpha value of the current foreground * Color to the specifice value. * * @param alpha value in the range of 0 - 1.0. */ public void changeAlpha(float alpha) { changeAlpha((int) (alpha * 255)); } /** * Convenience method to change the alpha value of the current foreground * Color to the specifice value. * * @param alpha value in the range of 0 - 255. */ public void changeAlpha(int alpha) { alpha = alpha > 255 ? 255 : alpha < 0 ? 0 : alpha; final Color foreground = getForeground(); final int red = foreground.getRed(); final int green = foreground.getGreen(); final int blue = foreground.getBlue(); final Color withAlpha = new Color(red, green, blue, alpha); super.setForeground(withAlpha); } // /** // * Convenience method to change the style of the current Font. The style // * values are found in the Font class. Common values might be: // * Font.BOLD, Font.ITALIC and Font.BOLD + Font.ITALIC. // * // * @param style value representing the the new style of the Font. // */ // public void changeStyle(int style, float size) { // setFont(getFont().deriveFont(style, size)); // } // /** // * Get the Show property // * // * @return the Show property. // */ // public Show getShow() { // return show; // } /** * Set the prompt Show property to control when the promt is shown; * valid values are: * * {@link Show#ALWAYS} (default) - always show the prompt * {@link Show#FOCUS_GAINED} - show the prompt when the component gains focus * (and hide the prompt when focus is lost) * {@link Show#FOCUS_LOST}- show the prompt when the component loses focus * (and hide the prompt when focus is gained) * * @param show a valid Show enum */ public void setShow(Show show) { this.show = show; } /** * Get the showPromptOnce property * * @return the showPromptOnce property. */ public boolean getShowPromptOnce() { return showPromptOnce; } /** * Show the prompt once. Once the component has gained/lost focus * once, the prompt will not be shown again. * * @param showPromptOnce when true the prompt will only be shown once, * otherwise it will be shown repeatedly. */ public void setShowPromptOnce(boolean showPromptOnce) { this.showPromptOnce = showPromptOnce; } /** * Check whether the prompt should be visible or not. The visibility * will change on updates to the Document and on focus changes. */ private void checkForPrompt() { // Text has been entered, remove the prompt if (sourceTextComponent.getDocument().getLength() > 0 || targetTextComponent.getDocument().getLength() > 0) { setVisible(false); return; } // Prompt has already been shown once, remove it if (showPromptOnce && focusLost > 0) { setVisible(false); return; } // Check the Show property and component focus to determine if the // prompt should be displayed. if (sourceTextComponent.hasFocus()) { if (show == Show.ALWAYS || show == Show.FOCUS_GAINED) { setVisible(true); } else { setVisible(false); } } else { if (show == Show.ALWAYS || show == Show.FOCUS_LOST) { setVisible(true); } else { setVisible(false); } } } /** {@inheritDoc} {@link FocusListener} */ public void focusGained(FocusEvent evt) { checkForPrompt(); } /** {@inheritDoc} {@link FocusListener} */ public void focusLost(FocusEvent evt) { focusLost++; checkForPrompt(); } /** {@inheritDoc} {@link DocumentListener} */ public void insertUpdate(DocumentEvent evt) { checkForPrompt(); // NOTE: if document is replaced via setDocument(), // no insert, remove, or change updates events are fired! // However, the "document" property is changed and this can // be listened for } /** {@inheritDoc} {@link DocumentListener} */ public void removeUpdate(final DocumentEvent evt) { checkForPrompt(); } /** {@inheritDoc} {@link DocumentListener} */ public void changedUpdate(final DocumentEvent evt) { } public void propertyChange(final PropertyChangeEvent evt) { // triggered by targetTextComponent.setDocument() calls if ("document".equals(evt.getPropertyName())) { checkForPrompt(); } } }
browser/src/main/java/org/yawni/wn/browser/TextPrompt.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.yawni.wn.browser; import java.awt.*; import java.awt.event.*; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.*; import javax.swing.event.*; import javax.swing.text.*; /** * The {@code TextPrompt} class will display a prompt over top of a text component when * the {@link Document} of the text component is empty. The Show property is used to * determine the visibility of the prompt. * * <p> The {@link Font} and foreground {@link Color} of the prompt will default to those properties * of the parent text component. You are free to change the properties after * class construction. * * <p> Courtesy <a href="http://tips4java.wordpress.com/2009/11/29/text-prompt/"> * http://tips4java.wordpress.com/2009/11/29/text-prompt/</a> */ public class TextPrompt extends JLabel implements FocusListener, DocumentListener, PropertyChangeListener { public enum Show { // show prompt independent of focus (disappears on typing into textComponent though) ALWAYS, FOCUS_GAINED, FOCUS_LOST; } private final JTextComponent sourceTextComponent; private final JTextComponent targetTextComponent; private Show show; private boolean showPromptOnce; private int focusLost; // default configuration: // Listen for content/Document AND focus changes on textComponent (typically a JTextField) // and render self as child component of textComponent based on this // desired configuration: // Listen for content/Document changes on textComponent and change label content. // Position self (label) horizontally centered and about 20% of the from the top // // sourceTextComponent: listened to for content/focus changes // targetTextComponent: where TextPrompt is installed // // bugs: // - BOTH source and target text components need to be empty to trigger prompt // - consider property change listener enable/disable and disabling resultEditorPane when searchField changes // - tests are dead locking!? // - label should have larger font // - maybe label should be in italics or a serif font // - use this to replace Status.INTRO functinoality ("Enter search word...") // and maybe No search results // - fade in/out public TextPrompt(final String promptText, final JTextComponent sourceTextComponent, final JTextComponent targetTextComponent) { this.sourceTextComponent = sourceTextComponent; this.targetTextComponent = targetTextComponent; setShow(Show.ALWAYS); setText(promptText); setHorizontalTextPosition(CENTER); setAlignmentX(CENTER_ALIGNMENT); setAlignmentY(0.2f); // setFont(targetTextComponent.getFont().deriveFont("Serif", Font.ITALIC, 24.0f)); setFont(new Font("Serif", Font.ITALIC, 24)); setForeground(targetTextComponent.getForeground()); sourceTextComponent.addFocusListener(this); sourceTextComponent.getDocument().addDocumentListener(this); // sourceTextComponent.addPropertyChangeListener("document", this); // targetTextComponent.getDocument().addDocumentListener(this); targetTextComponent.addPropertyChangeListener("document", this); targetTextComponent.setLayout(new BoxLayout(targetTextComponent, BoxLayout.Y_AXIS)); // put gap targetTextComponent.add(Box.createVerticalStrut(getFontMetrics(getFont()).getHeight())); targetTextComponent.add(this); checkForPrompt(); } /** * Convenience method to change the alpha value of the current foreground * Color to the specifice value. * * @param alpha value in the range of 0 - 1.0. */ public void changeAlpha(float alpha) { changeAlpha((int) (alpha * 255)); } /** * Convenience method to change the alpha value of the current foreground * Color to the specifice value. * * @param alpha value in the range of 0 - 255. */ public void changeAlpha(int alpha) { alpha = alpha > 255 ? 255 : alpha < 0 ? 0 : alpha; final Color foreground = getForeground(); final int red = foreground.getRed(); final int green = foreground.getGreen(); final int blue = foreground.getBlue(); final Color withAlpha = new Color(red, green, blue, alpha); super.setForeground(withAlpha); } // /** // * Convenience method to change the style of the current Font. The style // * values are found in the Font class. Common values might be: // * Font.BOLD, Font.ITALIC and Font.BOLD + Font.ITALIC. // * // * @param style value representing the the new style of the Font. // */ // public void changeStyle(int style, float size) { // setFont(getFont().deriveFont(style, size)); // } // /** // * Get the Show property // * // * @return the Show property. // */ // public Show getShow() { // return show; // } /** * Set the prompt Show property to control when the promt is shown; * valid values are: * * {@link Show#ALWAYS} (default) - always show the prompt * {@link Show#FOCUS_GAINED} - show the prompt when the component gains focus * (and hide the prompt when focus is lost) * {@link Show#FOCUS_LOST}- show the prompt when the component loses focus * (and hide the prompt when focus is gained) * * @param show a valid Show enum */ public void setShow(Show show) { this.show = show; } /** * Get the showPromptOnce property * * @return the showPromptOnce property. */ public boolean getShowPromptOnce() { return showPromptOnce; } /** * Show the prompt once. Once the component has gained/lost focus * once, the prompt will not be shown again. * * @param showPromptOnce when true the prompt will only be shown once, * otherwise it will be shown repeatedly. */ public void setShowPromptOnce(boolean showPromptOnce) { this.showPromptOnce = showPromptOnce; } /** * Check whether the prompt should be visible or not. The visibility * will change on updates to the Document and on focus changes. */ private void checkForPrompt() { // Text has been entered, remove the prompt if (sourceTextComponent.getDocument().getLength() > 0 || targetTextComponent.getDocument().getLength() > 0) { setVisible(false); return; } // Prompt has already been shown once, remove it if (showPromptOnce && focusLost > 0) { setVisible(false); return; } // Check the Show property and component focus to determine if the // prompt should be displayed. if (sourceTextComponent.hasFocus()) { if (show == Show.ALWAYS || show == Show.FOCUS_GAINED) { setVisible(true); } else { setVisible(false); } } else { if (show == Show.ALWAYS || show == Show.FOCUS_LOST) { setVisible(true); } else { setVisible(false); } } } /** {@inheritDoc} {@link FocusListener} */ public void focusGained(FocusEvent evt) { checkForPrompt(); } /** {@inheritDoc} {@link FocusListener} */ public void focusLost(FocusEvent evt) { focusLost++; checkForPrompt(); } /** {@inheritDoc} {@link DocumentListener} */ public void insertUpdate(DocumentEvent evt) { checkForPrompt(); // NOTE: if document is replaced via setDocument(), // no insert, remove, or change updates events are fired! // However, the "document" property is changed and this can // be listened for } /** {@inheritDoc} {@link DocumentListener} */ public void removeUpdate(final DocumentEvent evt) { checkForPrompt(); } /** {@inheritDoc} {@link DocumentListener} */ public void changedUpdate(final DocumentEvent evt) { } public void propertyChange(final PropertyChangeEvent evt) { // triggered by targetTextComponent.setDocument() calls if ("document".equals(evt.getPropertyName())) { checkForPrompt(); } } }
use Font.PLAIN instead of Font.ITALICS
browser/src/main/java/org/yawni/wn/browser/TextPrompt.java
use Font.PLAIN instead of Font.ITALICS
<ide><path>rowser/src/main/java/org/yawni/wn/browser/TextPrompt.java <ide> setHorizontalTextPosition(CENTER); <ide> setAlignmentX(CENTER_ALIGNMENT); <ide> setAlignmentY(0.2f); <del>// setFont(targetTextComponent.getFont().deriveFont("Serif", Font.ITALIC, 24.0f)); <del> setFont(new Font("Serif", Font.ITALIC, 24)); <add>// setFont(targetTextComponent.getFont().deriveFont(Font.ITALIC, 24.0f)); <add>// setFont(new Font("Serif", Font.ITALIC, 24)); <add> setFont(new Font("Serif", Font.PLAIN, 24)); <ide> setForeground(targetTextComponent.getForeground()); <ide> <ide> sourceTextComponent.addFocusListener(this); <ide> targetTextComponent.addPropertyChangeListener("document", this); <ide> <ide> targetTextComponent.setLayout(new BoxLayout(targetTextComponent, BoxLayout.Y_AXIS)); <del> // put gap <add> // put space above equal to 1 blank line of text <ide> targetTextComponent.add(Box.createVerticalStrut(getFontMetrics(getFont()).getHeight())); <ide> targetTextComponent.add(this); <ide> checkForPrompt();
Java
mit
840f845e9fc5c1e5aaf74414add10102b1213c41
0
sonork/spongycastle,bcgit/bc-java,FAU-Inf2/spongycastle,FAU-Inf2/spongycastle,sonork/spongycastle,bcgit/bc-java,isghe/bc-java,iseki-masaya/spongycastle,sergeypayu/bc-java,lesstif/spongycastle,sonork/spongycastle,sergeypayu/bc-java,FAU-Inf2/spongycastle,onessimofalconi/bc-java,Skywalker-11/spongycastle,savichris/spongycastle,onessimofalconi/bc-java,savichris/spongycastle,Skywalker-11/spongycastle,partheinstein/bc-java,iseki-masaya/spongycastle,isghe/bc-java,open-keychain/spongycastle,partheinstein/bc-java,lesstif/spongycastle,Skywalker-11/spongycastle,onessimofalconi/bc-java,lesstif/spongycastle,isghe/bc-java,open-keychain/spongycastle,partheinstein/bc-java,sergeypayu/bc-java,savichris/spongycastle,open-keychain/spongycastle,iseki-masaya/spongycastle,bcgit/bc-java
package org.bouncycastle.crypto.macs; import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.Mac; import org.bouncycastle.crypto.generators.Poly1305KeyGenerator; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.crypto.util.Pack; /** * Poly1305 message authentication code, designed by D. J. Bernstein. * <p> * Poly1305 computes a 128-bit (16 bytes) authenticator, using a 128 bit nonce and a 256 bit key * consisting of a 128 bit key applied to an underlying cipher, and a 128 bit key (with 106 * effective key bits) used in the authenticator. * <p> * The polynomial calculation in this implementation is adapted from the public domain <a * href="https://github.com/floodyberry/poly1305-donna">poly1305-donna-unrolled</a> C implementation * by Andrew M (@floodyberry). * @see Poly1305KeyGenerator */ public class Poly1305 implements Mac { private static final int BLOCK_SIZE = 16; private final BlockCipher cipher; private final byte[] singleByte = new byte[1]; // Initialised state /** Polynomial key */ private int r0, r1, r2, r3, r4; /** Precomputed 5 * r[1..4] */ private int s1, s2, s3, s4; /** Encrypted nonce */ private int k0, k1, k2, k3; // Accumulating state /** Current block of buffered input */ private final byte[] currentBlock = new byte[BLOCK_SIZE]; /** Current offset in input buffer */ private int currentBlockOffset = 0; /** Polynomial accumulator */ private int h0, h1, h2, h3, h4; /** * Constructs a Poly1305 MAC, where the key passed to init() will be used directly. */ public Poly1305() { this.cipher = null; } /** * Constructs a Poly1305 MAC, using a 128 bit block cipher. */ public Poly1305(final BlockCipher cipher) { if (cipher.getBlockSize() != BLOCK_SIZE) { throw new IllegalArgumentException("Poly1305 requires a 128 bit block cipher."); } this.cipher = cipher; } /** * Initialises the Poly1305 MAC. * * @param if used with a block cipher, then a {@link ParametersWithIV} containing a 128 bit * nonce and a {@link KeyParameter} with a 256 bit key complying to the * {@link Poly1305KeyGenerator Poly1305 key format}, otherwise just the * {@link KeyParameter}. */ public void init(CipherParameters params) throws IllegalArgumentException { byte[] nonce = null; if (cipher != null) { if (!(params instanceof ParametersWithIV)) { throw new IllegalArgumentException("Poly1305 requires an IV when used with a block cipher."); } ParametersWithIV ivParams = (ParametersWithIV)params; nonce = ivParams.getIV(); params = ivParams.getParameters(); } if (!(params instanceof KeyParameter)) { throw new IllegalArgumentException("Poly1305 requires a key."); } KeyParameter keyParams = (KeyParameter)params; setKey(keyParams.getKey(), nonce); reset(); } private void setKey(final byte[] key, final byte[] nonce) { if (cipher != null && (nonce == null || nonce.length != BLOCK_SIZE)) { throw new IllegalArgumentException("Poly1305 requires a 128 bit IV."); } Poly1305KeyGenerator.checkKey(key); // Extract r portion of key int t0 = Pack.littleEndianToInt(key, BLOCK_SIZE + 0); int t1 = Pack.littleEndianToInt(key, BLOCK_SIZE + 4); int t2 = Pack.littleEndianToInt(key, BLOCK_SIZE + 8); int t3 = Pack.littleEndianToInt(key, BLOCK_SIZE + 12); r0 = t0 & 0x3ffffff; t0 >>>= 26; t0 |= t1 << 6; r1 = t0 & 0x3ffff03; t1 >>>= 20; t1 |= t2 << 12; r2 = t1 & 0x3ffc0ff; t2 >>>= 14; t2 |= t3 << 18; r3 = t2 & 0x3f03fff; t3 >>>= 8; r4 = t3 & 0x00fffff; // Precompute multipliers s1 = r1 * 5; s2 = r2 * 5; s3 = r3 * 5; s4 = r4 * 5; final byte[] kBytes; if (cipher == null) { kBytes = key; } else { // Compute encrypted nonce kBytes = new byte[BLOCK_SIZE]; cipher.init(true, new KeyParameter(key, 0, BLOCK_SIZE)); cipher.processBlock(nonce, 0, kBytes, 0); } k0 = Pack.littleEndianToInt(kBytes, 0); k1 = Pack.littleEndianToInt(kBytes, 4); k2 = Pack.littleEndianToInt(kBytes, 8); k3 = Pack.littleEndianToInt(kBytes, 12); } public String getAlgorithmName() { return cipher == null ? "Poly1305" : "Poly1305-" + cipher.getAlgorithmName(); } public int getMacSize() { return BLOCK_SIZE; } public void update(final byte in) throws IllegalStateException { singleByte[0] = in; update(singleByte, 0, 1); } public void update(final byte[] in, final int inOff, final int len) throws DataLengthException, IllegalStateException { int copied = 0; while (len > copied) { if (currentBlockOffset == BLOCK_SIZE) { processBlock(); currentBlockOffset = 0; } int toCopy = Math.min((len - copied), BLOCK_SIZE - currentBlockOffset); System.arraycopy(in, copied + inOff, currentBlock, currentBlockOffset, toCopy); copied += toCopy; currentBlockOffset += toCopy; } } private void processBlock() { if (currentBlockOffset < BLOCK_SIZE) { currentBlock[currentBlockOffset] = 1; for (int i = currentBlockOffset + 1; i < BLOCK_SIZE; i++) { currentBlock[i] = 0; } } final long t0 = 0xffffffffL & Pack.littleEndianToInt(currentBlock, 0); final long t1 = 0xffffffffL & Pack.littleEndianToInt(currentBlock, 4); final long t2 = 0xffffffffL & Pack.littleEndianToInt(currentBlock, 8); final long t3 = 0xffffffffL & Pack.littleEndianToInt(currentBlock, 12); h0 += t0 & 0x3ffffff; h1 += (((t1 << 32) | t0) >>> 26) & 0x3ffffff; h2 += (((t2 << 32) | t1) >>> 20) & 0x3ffffff; h3 += (((t3 << 32) | t2) >>> 14) & 0x3ffffff; h4 += (t3 >>> 8); if (currentBlockOffset == BLOCK_SIZE) { h4 += (1 << 24); } long tp0 = mul32x32_64(h0,r0) + mul32x32_64(h1,s4) + mul32x32_64(h2,s3) + mul32x32_64(h3,s2) + mul32x32_64(h4,s1); long tp1 = mul32x32_64(h0,r1) + mul32x32_64(h1,r0) + mul32x32_64(h2,s4) + mul32x32_64(h3,s3) + mul32x32_64(h4,s2); long tp2 = mul32x32_64(h0,r2) + mul32x32_64(h1,r1) + mul32x32_64(h2,r0) + mul32x32_64(h3,s4) + mul32x32_64(h4,s3); long tp3 = mul32x32_64(h0,r3) + mul32x32_64(h1,r2) + mul32x32_64(h2,r1) + mul32x32_64(h3,r0) + mul32x32_64(h4,s4); long tp4 = mul32x32_64(h0,r4) + mul32x32_64(h1,r3) + mul32x32_64(h2,r2) + mul32x32_64(h3,r1) + mul32x32_64(h4,r0); long b; h0 = (int)tp0 & 0x3ffffff; b = (tp0 >>> 26); tp1 += b; h1 = (int)tp1 & 0x3ffffff; b = ((tp1 >>> 26) & 0xffffffff); tp2 += b; h2 = (int)tp2 & 0x3ffffff; b = ((tp2 >>> 26) & 0xffffffff); tp3 += b; h3 = (int)tp3 & 0x3ffffff; b = (tp3 >>> 26); tp4 += b; h4 = (int)tp4 & 0x3ffffff; b = (tp4 >>> 26); h0 += b * 5; } public int doFinal(final byte[] out, final int outOff) throws DataLengthException, IllegalStateException { if (outOff + BLOCK_SIZE > out.length) { throw new DataLengthException("Output buffer is too short."); } if (currentBlockOffset > 0) { // Process padded final block processBlock(); } long f0, f1, f2, f3; int b = h0 >>> 26; h0 = h0 & 0x3ffffff; h1 += b; b = h1 >>> 26; h1 = h1 & 0x3ffffff; h2 += b; b = h2 >>> 26; h2 = h2 & 0x3ffffff; h3 += b; b = h3 >>> 26; h3 = h3 & 0x3ffffff; h4 += b; b = h4 >>> 26; h4 = h4 & 0x3ffffff; h0 += b * 5; int g0, g1, g2, g3, g4; g0 = h0 + 5; b = g0 >>> 26; g0 &= 0x3ffffff; g1 = h1 + b; b = g1 >>> 26; g1 &= 0x3ffffff; g2 = h2 + b; b = g2 >>> 26; g2 &= 0x3ffffff; g3 = h3 + b; b = g3 >>> 26; g3 &= 0x3ffffff; g4 = h4 + b - (1 << 26); b = (g4 >>> 31) - 1; int nb = ~b; h0 = (h0 & nb) | (g0 & b); h1 = (h1 & nb) | (g1 & b); h2 = (h2 & nb) | (g2 & b); h3 = (h3 & nb) | (g3 & b); h4 = (h4 & nb) | (g4 & b); f0 = (((h0 ) | (h1 << 26)) & 0xffffffffl) + (0xffffffffL & k0); f1 = (((h1 >>> 6 ) | (h2 << 20)) & 0xffffffffl) + (0xffffffffL & k1); f2 = (((h2 >>> 12) | (h3 << 14)) & 0xffffffffl) + (0xffffffffL & k2); f3 = (((h3 >>> 18) | (h4 << 8 )) & 0xffffffffl) + (0xffffffffL & k3); Pack.intToLittleEndian((int)f0, out, outOff); f1 += (f0 >>> 32); Pack.intToLittleEndian((int)f1, out, outOff + 4); f2 += (f1 >>> 32); Pack.intToLittleEndian((int)f2, out, outOff + 8); f3 += (f2 >>> 32); Pack.intToLittleEndian((int)f3, out, outOff + 12); reset(); return BLOCK_SIZE; } public void reset() { currentBlockOffset = 0; h0 = h1 = h2 = h3 = h4 = 0; } private static final long mul32x32_64(int i1, int i2) { return ((long)i1) * i2; } }
core/src/main/java/org/bouncycastle/crypto/macs/Poly1305.java
package org.bouncycastle.crypto.macs; import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.DataLengthException; import org.bouncycastle.crypto.Mac; import org.bouncycastle.crypto.generators.Poly1305KeyGenerator; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.crypto.util.Pack; /** * Poly1305 message authentication code, designed by D. J. Bernstein. * <p> * Poly1305 computes a 128-bit (16 bytes) authenticator, using a 128 bit nonce and a 256 bit key * consisting of a 128 bit key applied to an underlying cipher, and a 128 bit key (with 106 * effective key bits) used in the authenticator. * <p> * The polynomial calculation in this implementation is adapted from the public domain <a * href="https://github.com/floodyberry/poly1305-donna">poly1305-donna-unrolled</a> C implementation * by Andrew M (@floodyberry). * @see Poly1305KeyGenerator */ public class Poly1305 implements Mac { private static final int BLOCK_SIZE = 16; private final BlockCipher cipher; private final byte[] singleByte = new byte[1]; // Initialised state /** Polynomial key */ private int r0, r1, r2, r3, r4; /** Precomputed 5 * r[1..4] */ private int s1, s2, s3, s4; /** Encrypted nonce */ private int k0, k1, k2, k3; // Accumulating state /** Current block of buffered input */ private final byte[] currentBlock = new byte[BLOCK_SIZE]; /** Current offset in input buffer */ private int currentBlockOffset = 0; /** Polynomial accumulator */ private int h0, h1, h2, h3, h4; /** * Constructs a Poly1305 MAC, using a 128 bit block cipher. */ public Poly1305(final BlockCipher cipher) { if (cipher.getBlockSize() != BLOCK_SIZE) { throw new IllegalArgumentException("Poly1305 requires a 128 bit block cipher."); } this.cipher = cipher; } /** * Initialises the Poly1305 MAC. * * @param a {@link ParametersWithIV} containing a 128 bit nonce and a {@link KeyParameter} with * a 256 bit key complying to the {@link Poly1305KeyGenerator Poly1305 key format}. */ public void init(final CipherParameters params) throws IllegalArgumentException { final byte[] nonce; final byte[] key; if ((params instanceof ParametersWithIV) && ((ParametersWithIV)params).getParameters() instanceof KeyParameter) { nonce = ((ParametersWithIV)params).getIV(); key = ((KeyParameter)((ParametersWithIV)params).getParameters()).getKey(); } else { throw new IllegalArgumentException("Poly1305 requires a key and and IV."); } setKey(key, nonce); reset(); } private void setKey(final byte[] key, final byte[] nonce) { if (nonce.length != BLOCK_SIZE) { throw new IllegalArgumentException("Poly1305 requires a 128 bit IV."); } Poly1305KeyGenerator.checkKey(key); // Extract r portion of key int t0 = Pack.littleEndianToInt(key, BLOCK_SIZE + 0); int t1 = Pack.littleEndianToInt(key, BLOCK_SIZE + 4); int t2 = Pack.littleEndianToInt(key, BLOCK_SIZE + 8); int t3 = Pack.littleEndianToInt(key, BLOCK_SIZE + 12); r0 = t0 & 0x3ffffff; t0 >>>= 26; t0 |= t1 << 6; r1 = t0 & 0x3ffff03; t1 >>>= 20; t1 |= t2 << 12; r2 = t1 & 0x3ffc0ff; t2 >>>= 14; t2 |= t3 << 18; r3 = t2 & 0x3f03fff; t3 >>>= 8; r4 = t3 & 0x00fffff; // Precompute multipliers s1 = r1 * 5; s2 = r2 * 5; s3 = r3 * 5; s4 = r4 * 5; // Compute encrypted nonce final byte[] cipherKey = new byte[BLOCK_SIZE]; System.arraycopy(key, 0, cipherKey, 0, cipherKey.length); cipher.init(true, new KeyParameter(cipherKey)); cipher.processBlock(nonce, 0, cipherKey, 0); k0 = Pack.littleEndianToInt(cipherKey, 0); k1 = Pack.littleEndianToInt(cipherKey, 4); k2 = Pack.littleEndianToInt(cipherKey, 8); k3 = Pack.littleEndianToInt(cipherKey, 12); } public String getAlgorithmName() { return "Poly1305-" + cipher.getAlgorithmName(); } public int getMacSize() { return BLOCK_SIZE; } public void update(final byte in) throws IllegalStateException { singleByte[0] = in; update(singleByte, 0, 1); } public void update(final byte[] in, final int inOff, final int len) throws DataLengthException, IllegalStateException { int copied = 0; while (len > copied) { if (currentBlockOffset == BLOCK_SIZE) { processBlock(); currentBlockOffset = 0; } int toCopy = Math.min((len - copied), BLOCK_SIZE - currentBlockOffset); System.arraycopy(in, copied + inOff, currentBlock, currentBlockOffset, toCopy); copied += toCopy; currentBlockOffset += toCopy; } } private void processBlock() { if (currentBlockOffset < BLOCK_SIZE) { currentBlock[currentBlockOffset] = 1; for (int i = currentBlockOffset + 1; i < BLOCK_SIZE; i++) { currentBlock[i] = 0; } } final long t0 = 0xffffffffL & Pack.littleEndianToInt(currentBlock, 0); final long t1 = 0xffffffffL & Pack.littleEndianToInt(currentBlock, 4); final long t2 = 0xffffffffL & Pack.littleEndianToInt(currentBlock, 8); final long t3 = 0xffffffffL & Pack.littleEndianToInt(currentBlock, 12); h0 += t0 & 0x3ffffff; h1 += (((t1 << 32) | t0) >>> 26) & 0x3ffffff; h2 += (((t2 << 32) | t1) >>> 20) & 0x3ffffff; h3 += (((t3 << 32) | t2) >>> 14) & 0x3ffffff; h4 += (t3 >>> 8); if (currentBlockOffset == BLOCK_SIZE) { h4 += (1 << 24); } long tp0 = mul32x32_64(h0,r0) + mul32x32_64(h1,s4) + mul32x32_64(h2,s3) + mul32x32_64(h3,s2) + mul32x32_64(h4,s1); long tp1 = mul32x32_64(h0,r1) + mul32x32_64(h1,r0) + mul32x32_64(h2,s4) + mul32x32_64(h3,s3) + mul32x32_64(h4,s2); long tp2 = mul32x32_64(h0,r2) + mul32x32_64(h1,r1) + mul32x32_64(h2,r0) + mul32x32_64(h3,s4) + mul32x32_64(h4,s3); long tp3 = mul32x32_64(h0,r3) + mul32x32_64(h1,r2) + mul32x32_64(h2,r1) + mul32x32_64(h3,r0) + mul32x32_64(h4,s4); long tp4 = mul32x32_64(h0,r4) + mul32x32_64(h1,r3) + mul32x32_64(h2,r2) + mul32x32_64(h3,r1) + mul32x32_64(h4,r0); long b; h0 = (int)tp0 & 0x3ffffff; b = (tp0 >>> 26); tp1 += b; h1 = (int)tp1 & 0x3ffffff; b = ((tp1 >>> 26) & 0xffffffff); tp2 += b; h2 = (int)tp2 & 0x3ffffff; b = ((tp2 >>> 26) & 0xffffffff); tp3 += b; h3 = (int)tp3 & 0x3ffffff; b = (tp3 >>> 26); tp4 += b; h4 = (int)tp4 & 0x3ffffff; b = (tp4 >>> 26); h0 += b * 5; } public int doFinal(final byte[] out, final int outOff) throws DataLengthException, IllegalStateException { if (outOff + BLOCK_SIZE > out.length) { throw new DataLengthException("Output buffer is too short."); } if (currentBlockOffset > 0) { // Process padded final block processBlock(); } long f0, f1, f2, f3; int b = h0 >>> 26; h0 = h0 & 0x3ffffff; h1 += b; b = h1 >>> 26; h1 = h1 & 0x3ffffff; h2 += b; b = h2 >>> 26; h2 = h2 & 0x3ffffff; h3 += b; b = h3 >>> 26; h3 = h3 & 0x3ffffff; h4 += b; b = h4 >>> 26; h4 = h4 & 0x3ffffff; h0 += b * 5; int g0, g1, g2, g3, g4; g0 = h0 + 5; b = g0 >>> 26; g0 &= 0x3ffffff; g1 = h1 + b; b = g1 >>> 26; g1 &= 0x3ffffff; g2 = h2 + b; b = g2 >>> 26; g2 &= 0x3ffffff; g3 = h3 + b; b = g3 >>> 26; g3 &= 0x3ffffff; g4 = h4 + b - (1 << 26); b = (g4 >>> 31) - 1; int nb = ~b; h0 = (h0 & nb) | (g0 & b); h1 = (h1 & nb) | (g1 & b); h2 = (h2 & nb) | (g2 & b); h3 = (h3 & nb) | (g3 & b); h4 = (h4 & nb) | (g4 & b); f0 = (((h0 ) | (h1 << 26)) & 0xffffffffl) + (0xffffffffL & k0); f1 = (((h1 >>> 6 ) | (h2 << 20)) & 0xffffffffl) + (0xffffffffL & k1); f2 = (((h2 >>> 12) | (h3 << 14)) & 0xffffffffl) + (0xffffffffL & k2); f3 = (((h3 >>> 18) | (h4 << 8 )) & 0xffffffffl) + (0xffffffffL & k3); Pack.intToLittleEndian((int)f0, out, outOff); f1 += (f0 >>> 32); Pack.intToLittleEndian((int)f1, out, outOff + 4); f2 += (f1 >>> 32); Pack.intToLittleEndian((int)f2, out, outOff + 8); f3 += (f2 >>> 32); Pack.intToLittleEndian((int)f3, out, outOff + 12); reset(); return BLOCK_SIZE; } public void reset() { currentBlockOffset = 0; h0 = h1 = h2 = h3 = h4 = 0; } private static final long mul32x32_64(int i1, int i2) { return ((long)i1) * i2; } }
Support using Poly1305 without a BlockCipher
core/src/main/java/org/bouncycastle/crypto/macs/Poly1305.java
Support using Poly1305 without a BlockCipher
<ide><path>ore/src/main/java/org/bouncycastle/crypto/macs/Poly1305.java <ide> private int h0, h1, h2, h3, h4; <ide> <ide> /** <add> * Constructs a Poly1305 MAC, where the key passed to init() will be used directly. <add> */ <add> public Poly1305() <add> { <add> this.cipher = null; <add> } <add> <add> /** <ide> * Constructs a Poly1305 MAC, using a 128 bit block cipher. <ide> */ <ide> public Poly1305(final BlockCipher cipher) <ide> <ide> /** <ide> * Initialises the Poly1305 MAC. <del> * <del> * @param a {@link ParametersWithIV} containing a 128 bit nonce and a {@link KeyParameter} with <del> * a 256 bit key complying to the {@link Poly1305KeyGenerator Poly1305 key format}. <add> * <add> * @param if used with a block cipher, then a {@link ParametersWithIV} containing a 128 bit <add> * nonce and a {@link KeyParameter} with a 256 bit key complying to the <add> * {@link Poly1305KeyGenerator Poly1305 key format}, otherwise just the <add> * {@link KeyParameter}. <ide> */ <del> public void init(final CipherParameters params) <add> public void init(CipherParameters params) <ide> throws IllegalArgumentException <ide> { <del> final byte[] nonce; <del> final byte[] key; <del> if ((params instanceof ParametersWithIV) && ((ParametersWithIV)params).getParameters() instanceof KeyParameter) <del> { <del> nonce = ((ParametersWithIV)params).getIV(); <del> key = ((KeyParameter)((ParametersWithIV)params).getParameters()).getKey(); <del> } <del> else <del> { <del> throw new IllegalArgumentException("Poly1305 requires a key and and IV."); <del> } <del> <del> setKey(key, nonce); <add> byte[] nonce = null; <add> <add> if (cipher != null) <add> { <add> if (!(params instanceof ParametersWithIV)) <add> { <add> throw new IllegalArgumentException("Poly1305 requires an IV when used with a block cipher."); <add> } <add> <add> ParametersWithIV ivParams = (ParametersWithIV)params; <add> nonce = ivParams.getIV(); <add> params = ivParams.getParameters(); <add> } <add> <add> if (!(params instanceof KeyParameter)) <add> { <add> throw new IllegalArgumentException("Poly1305 requires a key."); <add> } <add> <add> KeyParameter keyParams = (KeyParameter)params; <add> <add> setKey(keyParams.getKey(), nonce); <add> <ide> reset(); <ide> } <ide> <ide> private void setKey(final byte[] key, final byte[] nonce) <ide> { <del> if (nonce.length != BLOCK_SIZE) <add> if (cipher != null && (nonce == null || nonce.length != BLOCK_SIZE)) <ide> { <ide> throw new IllegalArgumentException("Poly1305 requires a 128 bit IV."); <ide> } <add> <ide> Poly1305KeyGenerator.checkKey(key); <ide> <ide> // Extract r portion of key <ide> s3 = r3 * 5; <ide> s4 = r4 * 5; <ide> <del> // Compute encrypted nonce <del> final byte[] cipherKey = new byte[BLOCK_SIZE]; <del> System.arraycopy(key, 0, cipherKey, 0, cipherKey.length); <del> <del> cipher.init(true, new KeyParameter(cipherKey)); <del> cipher.processBlock(nonce, 0, cipherKey, 0); <del> <del> k0 = Pack.littleEndianToInt(cipherKey, 0); <del> k1 = Pack.littleEndianToInt(cipherKey, 4); <del> k2 = Pack.littleEndianToInt(cipherKey, 8); <del> k3 = Pack.littleEndianToInt(cipherKey, 12); <add> final byte[] kBytes; <add> if (cipher == null) <add> { <add> kBytes = key; <add> } <add> else <add> { <add> // Compute encrypted nonce <add> kBytes = new byte[BLOCK_SIZE]; <add> cipher.init(true, new KeyParameter(key, 0, BLOCK_SIZE)); <add> cipher.processBlock(nonce, 0, kBytes, 0); <add> } <add> <add> k0 = Pack.littleEndianToInt(kBytes, 0); <add> k1 = Pack.littleEndianToInt(kBytes, 4); <add> k2 = Pack.littleEndianToInt(kBytes, 8); <add> k3 = Pack.littleEndianToInt(kBytes, 12); <ide> } <ide> <ide> public String getAlgorithmName() <ide> { <del> return "Poly1305-" + cipher.getAlgorithmName(); <add> return cipher == null ? "Poly1305" : "Poly1305-" + cipher.getAlgorithmName(); <ide> } <ide> <ide> public int getMacSize()
Java
apache-2.0
0f15807a71d2b0a10dcdb0f8ff1a69d66db9f226
0
qtproject/qtqa-gerrit,WANdisco/gerrit,qtproject/qtqa-gerrit,WANdisco/gerrit,WANdisco/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,WANdisco/gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,qtproject/qtqa-gerrit,qtproject/qtqa-gerrit
// Copyright (C) 2016 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.account.externalids; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.auto.value.AutoValue; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.hash.Hashing; import com.google.gerrit.common.Nullable; import com.google.gerrit.extensions.client.AuthType; import com.google.gerrit.reviewdb.client.Account; import com.google.gerrit.server.account.HashedPassword; import java.io.Serializable; import java.util.Collection; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Stream; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; @AutoValue public abstract class ExternalId implements Serializable { // If these regular expressions are modified the same modifications should be done to the // corresponding regular expressions in the // com.google.gerrit.client.account.UsernameField class. private static final String USER_NAME_PATTERN_FIRST_REGEX = "[a-zA-Z0-9]"; private static final String USER_NAME_PATTERN_REST_REGEX = "[a-zA-Z0-9._@-]"; private static final String USER_NAME_PATTERN_LAST_REGEX = "[a-zA-Z0-9]"; /** Regular expression that a username must match. */ private static final String USER_NAME_PATTERN_REGEX = "^" + // "(" + // USER_NAME_PATTERN_FIRST_REGEX + // USER_NAME_PATTERN_REST_REGEX + "*" + // USER_NAME_PATTERN_LAST_REGEX + // "|" + // USER_NAME_PATTERN_FIRST_REGEX + // ")" + // "$"; private static final Pattern USER_NAME_PATTERN = Pattern.compile(USER_NAME_PATTERN_REGEX); public static boolean isValidUsername(String username) { return USER_NAME_PATTERN.matcher(username).matches(); } /** * Returns the ID of the first external ID from the provided external IDs that has the {@link * ExternalId#SCHEME_USERNAME} scheme. * * @param extIds external IDs * @return the ID of the first external ID from the provided external IDs that has the {@link * ExternalId#SCHEME_USERNAME} scheme */ public static Optional<String> getUserName(Collection<ExternalId> extIds) { return extIds .stream() .filter(e -> e.isScheme(SCHEME_USERNAME)) .map(e -> e.key().id()) .filter(u -> !Strings.isNullOrEmpty(u)) .findFirst(); } /** * Returns all IDs of the provided external IDs that have the {@link ExternalId#SCHEME_MAILTO} * scheme as a distinct stream. * * @param extIds external IDs * @return distinct stream of all IDs of the provided external IDs that have the {@link * ExternalId#SCHEME_MAILTO} scheme */ public static Stream<String> getEmails(Collection<ExternalId> extIds) { return extIds.stream().filter(e -> e.isScheme(SCHEME_MAILTO)).map(e -> e.key().id()).distinct(); } private static final long serialVersionUID = 1L; private static final String EXTERNAL_ID_SECTION = "externalId"; private static final String ACCOUNT_ID_KEY = "accountId"; private static final String EMAIL_KEY = "email"; private static final String PASSWORD_KEY = "password"; /** * Scheme used for {@link AuthType#LDAP}, {@link AuthType#CLIENT_SSL_CERT_LDAP}, {@link * AuthType#HTTP_LDAP}, and {@link AuthType#LDAP_BIND} usernames. * * <p>The name {@code gerrit:} was a very poor choice. */ public static final String SCHEME_GERRIT = "gerrit"; /** Scheme used for randomly created identities constructed by a UUID. */ public static final String SCHEME_UUID = "uuid"; /** Scheme used to represent only an email address. */ public static final String SCHEME_MAILTO = "mailto"; /** Scheme for the username used to authenticate an account, e.g. over SSH. */ public static final String SCHEME_USERNAME = "username"; /** Scheme used for GPG public keys. */ public static final String SCHEME_GPGKEY = "gpgkey"; /** Scheme for external auth used during authentication, e.g. OAuth Token */ public static final String SCHEME_EXTERNAL = "external"; @AutoValue public abstract static class Key implements Serializable { private static final long serialVersionUID = 1L; public static Key create(@Nullable String scheme, String id) { return new AutoValue_ExternalId_Key(Strings.emptyToNull(scheme), id); } /** * Parses an external ID key from a string in the format "scheme:id" or "id". * * @return the parsed external ID key */ public static Key parse(String externalId) { int c = externalId.indexOf(':'); if (c < 1 || c >= externalId.length() - 1) { return create(null, externalId); } return create(externalId.substring(0, c), externalId.substring(c + 1)); } public abstract @Nullable String scheme(); public abstract String id(); public boolean isScheme(String scheme) { return scheme.equals(scheme()); } /** * Returns the SHA1 of the external ID that is used as note ID in the refs/meta/external-ids * notes branch. */ @SuppressWarnings("deprecation") // Use Hashing.sha1 for compatibility. public ObjectId sha1() { return ObjectId.fromRaw(Hashing.sha1().hashString(get(), UTF_8).asBytes()); } /** * Exports this external ID key as string with the format "scheme:id", or "id" if scheme is * null. * * <p>This string representation is used as subsection name in the Git config file that stores * the external ID. */ public String get() { if (scheme() != null) { return scheme() + ":" + id(); } return id(); } @Override public String toString() { return get(); } public static ImmutableSet<ExternalId.Key> from(Collection<ExternalId> extIds) { return extIds.stream().map(ExternalId::key).collect(toImmutableSet()); } } public static ExternalId create(String scheme, String id, Account.Id accountId) { return create(Key.create(scheme, id), accountId, null, null); } public static ExternalId create( String scheme, String id, Account.Id accountId, @Nullable String email, @Nullable String hashedPassword) { return create(Key.create(scheme, id), accountId, email, hashedPassword); } public static ExternalId create(Key key, Account.Id accountId) { return create(key, accountId, null, null); } public static ExternalId create( Key key, Account.Id accountId, @Nullable String email, @Nullable String hashedPassword) { return create( key, accountId, Strings.emptyToNull(email), Strings.emptyToNull(hashedPassword), null); } public static ExternalId createWithPassword( Key key, Account.Id accountId, @Nullable String email, @Nullable String plainPassword) { plainPassword = Strings.emptyToNull(plainPassword); String hashedPassword = plainPassword != null ? HashedPassword.fromPassword(plainPassword).encode() : null; return create(key, accountId, email, hashedPassword); } public static ExternalId createUsername( String id, Account.Id accountId, @Nullable String plainPassword) { return createWithPassword(Key.create(SCHEME_USERNAME, id), accountId, null, plainPassword); } public static ExternalId createWithEmail( String scheme, String id, Account.Id accountId, @Nullable String email) { return createWithEmail(Key.create(scheme, id), accountId, email); } public static ExternalId createWithEmail(Key key, Account.Id accountId, @Nullable String email) { return create(key, accountId, Strings.emptyToNull(email), null); } public static ExternalId createEmail(Account.Id accountId, String email) { return createWithEmail(SCHEME_MAILTO, email, accountId, checkNotNull(email)); } static ExternalId create(ExternalId extId, @Nullable ObjectId blobId) { return new AutoValue_ExternalId( extId.key(), extId.accountId(), extId.email(), extId.password(), blobId); } @VisibleForTesting public static ExternalId create( Key key, Account.Id accountId, @Nullable String email, @Nullable String hashedPassword, @Nullable ObjectId blobId) { return new AutoValue_ExternalId( key, accountId, Strings.emptyToNull(email), Strings.emptyToNull(hashedPassword), blobId); } /** * Parses an external ID from a byte array that contain the external ID as an Git config file * text. * * <p>The Git config must have exactly one externalId subsection with an accountId and optionally * email and password: * * <pre> * [externalId "username:jdoe"] * accountId = 1003407 * email = [email protected] * password = bcrypt:4:LCbmSBDivK/hhGVQMfkDpA==:XcWn0pKYSVU/UJgOvhidkEtmqCp6oKB7 * </pre> */ public static ExternalId parse(String noteId, byte[] raw, ObjectId blobId) throws ConfigInvalidException { Config externalIdConfig = new Config(); try { externalIdConfig.fromText(new String(raw, UTF_8)); } catch (ConfigInvalidException e) { throw invalidConfig(noteId, e.getMessage()); } return parse(noteId, externalIdConfig, blobId); } public static ExternalId parse(String noteId, Config externalIdConfig, ObjectId blobId) throws ConfigInvalidException { checkNotNull(blobId); Set<String> externalIdKeys = externalIdConfig.getSubsections(EXTERNAL_ID_SECTION); if (externalIdKeys.size() != 1) { throw invalidConfig( noteId, String.format( "Expected exactly 1 '%s' section, found %d", EXTERNAL_ID_SECTION, externalIdKeys.size())); } String externalIdKeyStr = Iterables.getOnlyElement(externalIdKeys); Key externalIdKey = Key.parse(externalIdKeyStr); if (externalIdKey == null) { throw invalidConfig(noteId, String.format("External ID %s is invalid", externalIdKeyStr)); } if (!externalIdKey.sha1().getName().equals(noteId)) { throw invalidConfig( noteId, String.format( "SHA1 of external ID '%s' does not match note ID '%s'", externalIdKeyStr, noteId)); } String email = externalIdConfig.getString(EXTERNAL_ID_SECTION, externalIdKeyStr, EMAIL_KEY); String password = externalIdConfig.getString(EXTERNAL_ID_SECTION, externalIdKeyStr, PASSWORD_KEY); int accountId = readAccountId(noteId, externalIdConfig, externalIdKeyStr); return create( externalIdKey, new Account.Id(accountId), Strings.emptyToNull(email), Strings.emptyToNull(password), blobId); } private static int readAccountId(String noteId, Config externalIdConfig, String externalIdKeyStr) throws ConfigInvalidException { String accountIdStr = externalIdConfig.getString(EXTERNAL_ID_SECTION, externalIdKeyStr, ACCOUNT_ID_KEY); if (accountIdStr == null) { throw invalidConfig( noteId, String.format( "Value for '%s.%s.%s' is missing, expected account ID", EXTERNAL_ID_SECTION, externalIdKeyStr, ACCOUNT_ID_KEY)); } try { int accountId = externalIdConfig.getInt(EXTERNAL_ID_SECTION, externalIdKeyStr, ACCOUNT_ID_KEY, -1); if (accountId < 0) { throw invalidConfig( noteId, String.format( "Value %s for '%s.%s.%s' is invalid, expected account ID", accountIdStr, EXTERNAL_ID_SECTION, externalIdKeyStr, ACCOUNT_ID_KEY)); } return accountId; } catch (IllegalArgumentException e) { throw invalidConfig( noteId, String.format( "Value %s for '%s.%s.%s' is invalid, expected account ID", accountIdStr, EXTERNAL_ID_SECTION, externalIdKeyStr, ACCOUNT_ID_KEY)); } } private static ConfigInvalidException invalidConfig(String noteId, String message) { return new ConfigInvalidException( String.format("Invalid external ID config for note '%s': %s", noteId, message)); } public abstract Key key(); public abstract Account.Id accountId(); public abstract @Nullable String email(); public abstract @Nullable String password(); /** * ID of the note blob in the external IDs branch that stores this external ID. {@code null} if * the external ID was created in code and is not yet stored in Git. */ public abstract @Nullable ObjectId blobId(); public void checkThatBlobIdIsSet() { checkState(blobId() != null, "No blob ID set for external ID %s", key().get()); } public boolean isScheme(String scheme) { return key().isScheme(scheme); } public byte[] toByteArray() { checkState(blobId() != null, "Missing blobId in external ID %s", key().get()); byte[] b = new byte[2 * Constants.OBJECT_ID_STRING_LENGTH + 1]; key().sha1().copyTo(b, 0); b[Constants.OBJECT_ID_STRING_LENGTH] = ':'; blobId().copyTo(b, Constants.OBJECT_ID_STRING_LENGTH + 1); return b; } /** * For checking if two external IDs are equals the blobId is excluded and external IDs that have * different blob IDs but identical other fields are considered equal. This way an external ID * that was loaded from Git can be equal with an external ID that was created from code. */ @Override public boolean equals(Object obj) { if (!(obj instanceof ExternalId)) { return false; } ExternalId o = (ExternalId) obj; return Objects.equals(key(), o.key()) && Objects.equals(accountId(), o.accountId()) && Objects.equals(email(), o.email()) && Objects.equals(password(), o.password()); } @Override public int hashCode() { return Objects.hash(key(), accountId(), email(), password()); } /** * Exports this external ID as Git config file text. * * <p>The Git config has exactly one externalId subsection with an accountId and optionally email * and password: * * <pre> * [externalId "username:jdoe"] * accountId = 1003407 * email = [email protected] * password = bcrypt:4:LCbmSBDivK/hhGVQMfkDpA==:XcWn0pKYSVU/UJgOvhidkEtmqCp6oKB7 * </pre> */ @Override public String toString() { Config c = new Config(); writeToConfig(c); return c.toText(); } public void writeToConfig(Config c) { String externalIdKey = key().get(); // Do not use c.setInt(...) to write the account ID because c.setInt(...) persists integers // that can be expressed in KiB as a unit strings, e.g. "1024000" is stored as "100k". Using // c.setString(...) ensures that account IDs are human readable. c.setString( EXTERNAL_ID_SECTION, externalIdKey, ACCOUNT_ID_KEY, Integer.toString(accountId().get())); if (email() != null) { c.setString(EXTERNAL_ID_SECTION, externalIdKey, EMAIL_KEY, email()); } else { c.unset(EXTERNAL_ID_SECTION, externalIdKey, EMAIL_KEY); } if (password() != null) { c.setString(EXTERNAL_ID_SECTION, externalIdKey, PASSWORD_KEY, password()); } else { c.unset(EXTERNAL_ID_SECTION, externalIdKey, PASSWORD_KEY); } } }
java/com/google/gerrit/server/account/externalids/ExternalId.java
// Copyright (C) 2016 The Android Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.gerrit.server.account.externalids; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.auto.value.AutoValue; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.hash.Hashing; import com.google.gerrit.common.Nullable; import com.google.gerrit.extensions.client.AuthType; import com.google.gerrit.reviewdb.client.Account; import com.google.gerrit.server.account.HashedPassword; import java.io.Serializable; import java.util.Collection; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.regex.Pattern; import java.util.stream.Stream; import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.lib.Config; import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.ObjectId; @AutoValue public abstract class ExternalId implements Serializable { // If these regular expressions are modified the same modifications should be done to the // corresponding regular expressions in the // com.google.gerrit.client.account.UsernameField class. private static final String USER_NAME_PATTERN_FIRST_REGEX = "[a-zA-Z0-9]"; private static final String USER_NAME_PATTERN_REST_REGEX = "[a-zA-Z0-9._@-]"; private static final String USER_NAME_PATTERN_LAST_REGEX = "[a-zA-Z0-9]"; /** Regular expression that a username must match. */ private static final String USER_NAME_PATTERN_REGEX = "^" + // "(" + // USER_NAME_PATTERN_FIRST_REGEX + // USER_NAME_PATTERN_REST_REGEX + "*" + // USER_NAME_PATTERN_LAST_REGEX + // "|" + // USER_NAME_PATTERN_FIRST_REGEX + // ")" + // "$"; private static final Pattern USER_NAME_PATTERN = Pattern.compile(USER_NAME_PATTERN_REGEX); public static boolean isValidUsername(String username) { return USER_NAME_PATTERN.matcher(username).matches(); } /** * Returns the ID of the first external ID from the provided external IDs that has the {@link * ExternalId#SCHEME_USERNAME} scheme. * * @param extIds external IDs * @return the ID of the first external ID from the provided external IDs that has the {@link * ExternalId#SCHEME_USERNAME} scheme */ public static Optional<String> getUserName(Collection<ExternalId> extIds) { return extIds .stream() .filter(e -> e.isScheme(SCHEME_USERNAME)) .map(e -> e.key().id()) .filter(u -> !Strings.isNullOrEmpty(u)) .findFirst(); } /** * Returns all IDs of the provided external IDs that have the {@link ExternalId#SCHEME_MAILTO} * scheme as a distinct stream. * * @param extIds external IDs * @return distinct stream of all IDs of the provided external IDs that have the {@link * ExternalId#SCHEME_MAILTO} scheme */ public static Stream<String> getEmails(Collection<ExternalId> extIds) { return extIds.stream().filter(e -> e.isScheme(SCHEME_MAILTO)).map(e -> e.key().id()).distinct(); } private static final long serialVersionUID = 1L; private static final String EXTERNAL_ID_SECTION = "externalId"; private static final String ACCOUNT_ID_KEY = "accountId"; private static final String EMAIL_KEY = "email"; private static final String PASSWORD_KEY = "password"; /** * Scheme used for {@link AuthType#LDAP}, {@link AuthType#CLIENT_SSL_CERT_LDAP}, {@link * AuthType#HTTP_LDAP}, and {@link AuthType#LDAP_BIND} usernames. * * <p>The name {@code gerrit:} was a very poor choice. */ public static final String SCHEME_GERRIT = "gerrit"; /** Scheme used for randomly created identities constructed by a UUID. */ public static final String SCHEME_UUID = "uuid"; /** Scheme used to represent only an email address. */ public static final String SCHEME_MAILTO = "mailto"; /** Scheme for the username used to authenticate an account, e.g. over SSH. */ public static final String SCHEME_USERNAME = "username"; /** Scheme used for GPG public keys. */ public static final String SCHEME_GPGKEY = "gpgkey"; /** Scheme for external auth used during authentication, e.g. OAuth Token */ public static final String SCHEME_EXTERNAL = "external"; @AutoValue public abstract static class Key implements Serializable { private static final long serialVersionUID = 1L; public static Key create(@Nullable String scheme, String id) { return new AutoValue_ExternalId_Key(Strings.emptyToNull(scheme), id); } /** * Parses an external ID key from a string in the format "scheme:id" or "id". * * @return the parsed external ID key */ public static Key parse(String externalId) { int c = externalId.indexOf(':'); if (c < 1 || c >= externalId.length() - 1) { return create(null, externalId); } return create(externalId.substring(0, c), externalId.substring(c + 1)); } public abstract @Nullable String scheme(); public abstract String id(); public boolean isScheme(String scheme) { return scheme.equals(scheme()); } /** * Returns the SHA1 of the external ID that is used as note ID in the refs/meta/external-ids * notes branch. */ @SuppressWarnings("deprecation") // Use Hashing.sha1 for compatibility. public ObjectId sha1() { return ObjectId.fromRaw(Hashing.sha1().hashString(get(), UTF_8).asBytes()); } /** * Exports this external ID key as string with the format "scheme:id", or "id" if scheme is * null. * * <p>This string representation is used as subsection name in the Git config file that stores * the external ID. */ public String get() { if (scheme() != null) { return scheme() + ":" + id(); } return id(); } @Override public String toString() { return get(); } public static ImmutableSet<ExternalId.Key> from(Collection<ExternalId> extIds) { return extIds.stream().map(ExternalId::key).collect(toImmutableSet()); } } public static ExternalId create(String scheme, String id, Account.Id accountId) { return create(Key.create(scheme, id), accountId, null, null); } public static ExternalId create( String scheme, String id, Account.Id accountId, @Nullable String email, @Nullable String hashedPassword) { return create(Key.create(scheme, id), accountId, email, hashedPassword); } public static ExternalId create(Key key, Account.Id accountId) { return create(key, accountId, null, null); } public static ExternalId create( Key key, Account.Id accountId, @Nullable String email, @Nullable String hashedPassword) { return create( key, accountId, Strings.emptyToNull(email), Strings.emptyToNull(hashedPassword), null); } public static ExternalId createWithPassword( Key key, Account.Id accountId, @Nullable String email, String plainPassword) { plainPassword = Strings.emptyToNull(plainPassword); String hashedPassword = plainPassword != null ? HashedPassword.fromPassword(plainPassword).encode() : null; return create(key, accountId, email, hashedPassword); } public static ExternalId createUsername(String id, Account.Id accountId, String plainPassword) { return createWithPassword(Key.create(SCHEME_USERNAME, id), accountId, null, plainPassword); } public static ExternalId createWithEmail( String scheme, String id, Account.Id accountId, @Nullable String email) { return createWithEmail(Key.create(scheme, id), accountId, email); } public static ExternalId createWithEmail(Key key, Account.Id accountId, @Nullable String email) { return create(key, accountId, Strings.emptyToNull(email), null); } public static ExternalId createEmail(Account.Id accountId, String email) { return createWithEmail(SCHEME_MAILTO, email, accountId, checkNotNull(email)); } static ExternalId create(ExternalId extId, @Nullable ObjectId blobId) { return new AutoValue_ExternalId( extId.key(), extId.accountId(), extId.email(), extId.password(), blobId); } @VisibleForTesting public static ExternalId create( Key key, Account.Id accountId, @Nullable String email, @Nullable String hashedPassword, @Nullable ObjectId blobId) { return new AutoValue_ExternalId( key, accountId, Strings.emptyToNull(email), Strings.emptyToNull(hashedPassword), blobId); } /** * Parses an external ID from a byte array that contain the external ID as an Git config file * text. * * <p>The Git config must have exactly one externalId subsection with an accountId and optionally * email and password: * * <pre> * [externalId "username:jdoe"] * accountId = 1003407 * email = [email protected] * password = bcrypt:4:LCbmSBDivK/hhGVQMfkDpA==:XcWn0pKYSVU/UJgOvhidkEtmqCp6oKB7 * </pre> */ public static ExternalId parse(String noteId, byte[] raw, ObjectId blobId) throws ConfigInvalidException { Config externalIdConfig = new Config(); try { externalIdConfig.fromText(new String(raw, UTF_8)); } catch (ConfigInvalidException e) { throw invalidConfig(noteId, e.getMessage()); } return parse(noteId, externalIdConfig, blobId); } public static ExternalId parse(String noteId, Config externalIdConfig, ObjectId blobId) throws ConfigInvalidException { checkNotNull(blobId); Set<String> externalIdKeys = externalIdConfig.getSubsections(EXTERNAL_ID_SECTION); if (externalIdKeys.size() != 1) { throw invalidConfig( noteId, String.format( "Expected exactly 1 '%s' section, found %d", EXTERNAL_ID_SECTION, externalIdKeys.size())); } String externalIdKeyStr = Iterables.getOnlyElement(externalIdKeys); Key externalIdKey = Key.parse(externalIdKeyStr); if (externalIdKey == null) { throw invalidConfig(noteId, String.format("External ID %s is invalid", externalIdKeyStr)); } if (!externalIdKey.sha1().getName().equals(noteId)) { throw invalidConfig( noteId, String.format( "SHA1 of external ID '%s' does not match note ID '%s'", externalIdKeyStr, noteId)); } String email = externalIdConfig.getString(EXTERNAL_ID_SECTION, externalIdKeyStr, EMAIL_KEY); String password = externalIdConfig.getString(EXTERNAL_ID_SECTION, externalIdKeyStr, PASSWORD_KEY); int accountId = readAccountId(noteId, externalIdConfig, externalIdKeyStr); return create( externalIdKey, new Account.Id(accountId), Strings.emptyToNull(email), Strings.emptyToNull(password), blobId); } private static int readAccountId(String noteId, Config externalIdConfig, String externalIdKeyStr) throws ConfigInvalidException { String accountIdStr = externalIdConfig.getString(EXTERNAL_ID_SECTION, externalIdKeyStr, ACCOUNT_ID_KEY); if (accountIdStr == null) { throw invalidConfig( noteId, String.format( "Value for '%s.%s.%s' is missing, expected account ID", EXTERNAL_ID_SECTION, externalIdKeyStr, ACCOUNT_ID_KEY)); } try { int accountId = externalIdConfig.getInt(EXTERNAL_ID_SECTION, externalIdKeyStr, ACCOUNT_ID_KEY, -1); if (accountId < 0) { throw invalidConfig( noteId, String.format( "Value %s for '%s.%s.%s' is invalid, expected account ID", accountIdStr, EXTERNAL_ID_SECTION, externalIdKeyStr, ACCOUNT_ID_KEY)); } return accountId; } catch (IllegalArgumentException e) { throw invalidConfig( noteId, String.format( "Value %s for '%s.%s.%s' is invalid, expected account ID", accountIdStr, EXTERNAL_ID_SECTION, externalIdKeyStr, ACCOUNT_ID_KEY)); } } private static ConfigInvalidException invalidConfig(String noteId, String message) { return new ConfigInvalidException( String.format("Invalid external ID config for note '%s': %s", noteId, message)); } public abstract Key key(); public abstract Account.Id accountId(); public abstract @Nullable String email(); public abstract @Nullable String password(); /** * ID of the note blob in the external IDs branch that stores this external ID. {@code null} if * the external ID was created in code and is not yet stored in Git. */ public abstract @Nullable ObjectId blobId(); public void checkThatBlobIdIsSet() { checkState(blobId() != null, "No blob ID set for external ID %s", key().get()); } public boolean isScheme(String scheme) { return key().isScheme(scheme); } public byte[] toByteArray() { checkState(blobId() != null, "Missing blobId in external ID %s", key().get()); byte[] b = new byte[2 * Constants.OBJECT_ID_STRING_LENGTH + 1]; key().sha1().copyTo(b, 0); b[Constants.OBJECT_ID_STRING_LENGTH] = ':'; blobId().copyTo(b, Constants.OBJECT_ID_STRING_LENGTH + 1); return b; } /** * For checking if two external IDs are equals the blobId is excluded and external IDs that have * different blob IDs but identical other fields are considered equal. This way an external ID * that was loaded from Git can be equal with an external ID that was created from code. */ @Override public boolean equals(Object obj) { if (!(obj instanceof ExternalId)) { return false; } ExternalId o = (ExternalId) obj; return Objects.equals(key(), o.key()) && Objects.equals(accountId(), o.accountId()) && Objects.equals(email(), o.email()) && Objects.equals(password(), o.password()); } @Override public int hashCode() { return Objects.hash(key(), accountId(), email(), password()); } /** * Exports this external ID as Git config file text. * * <p>The Git config has exactly one externalId subsection with an accountId and optionally email * and password: * * <pre> * [externalId "username:jdoe"] * accountId = 1003407 * email = [email protected] * password = bcrypt:4:LCbmSBDivK/hhGVQMfkDpA==:XcWn0pKYSVU/UJgOvhidkEtmqCp6oKB7 * </pre> */ @Override public String toString() { Config c = new Config(); writeToConfig(c); return c.toText(); } public void writeToConfig(Config c) { String externalIdKey = key().get(); // Do not use c.setInt(...) to write the account ID because c.setInt(...) persists integers // that can be expressed in KiB as a unit strings, e.g. "1024000" is stored as "100k". Using // c.setString(...) ensures that account IDs are human readable. c.setString( EXTERNAL_ID_SECTION, externalIdKey, ACCOUNT_ID_KEY, Integer.toString(accountId().get())); if (email() != null) { c.setString(EXTERNAL_ID_SECTION, externalIdKey, EMAIL_KEY, email()); } else { c.unset(EXTERNAL_ID_SECTION, externalIdKey, EMAIL_KEY); } if (password() != null) { c.setString(EXTERNAL_ID_SECTION, externalIdKey, PASSWORD_KEY, password()); } else { c.unset(EXTERNAL_ID_SECTION, externalIdKey, PASSWORD_KEY); } } }
ExternalId: Mark plainPassword as Nullable Change-Id: I1de32d42efa497c0e6401f04c81d16d88407e97a Signed-off-by: Edwin Kempin <[email protected]>
java/com/google/gerrit/server/account/externalids/ExternalId.java
ExternalId: Mark plainPassword as Nullable
<ide><path>ava/com/google/gerrit/server/account/externalids/ExternalId.java <ide> } <ide> <ide> public static ExternalId createWithPassword( <del> Key key, Account.Id accountId, @Nullable String email, String plainPassword) { <add> Key key, Account.Id accountId, @Nullable String email, @Nullable String plainPassword) { <ide> plainPassword = Strings.emptyToNull(plainPassword); <ide> String hashedPassword = <ide> plainPassword != null ? HashedPassword.fromPassword(plainPassword).encode() : null; <ide> return create(key, accountId, email, hashedPassword); <ide> } <ide> <del> public static ExternalId createUsername(String id, Account.Id accountId, String plainPassword) { <add> public static ExternalId createUsername( <add> String id, Account.Id accountId, @Nullable String plainPassword) { <ide> return createWithPassword(Key.create(SCHEME_USERNAME, id), accountId, null, plainPassword); <ide> } <ide>
Java
apache-2.0
d01b78b23da3926d8adfd195fac66e0c6b600c04
0
baszero/yanel,wyona/yanel,baszero/yanel,wyona/yanel,baszero/yanel,wyona/yanel,wyona/yanel,wyona/yanel,baszero/yanel,baszero/yanel,wyona/yanel,baszero/yanel
/* * Copyright 2006 Wyona */ package org.wyona.yanel.impl.resources; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.ResourceTypeDefinition; import org.wyona.yanel.core.ResourceTypeRegistry; import org.wyona.yanel.core.api.attributes.CreatableV2; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.attributes.viewable.ViewDescriptor; import org.wyona.yanel.core.util.ResourceAttributeHelper; import org.apache.log4j.Category; import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; /** * */ public class ResourceCreatorResource extends Resource implements ViewableV2{ private static Category log = Category.getInstance(ResourceCreatorResource.class); /** * */ public ResourceCreatorResource() { } /** * */ public boolean exists() { return true; } /** * */ public long getSize() { return -1; } /** * */ public View getView(String viewId) { View view = new View(); view.setMimeType("application/xhtml+xml"); view.setInputStream(new java.io.StringBufferInputStream(getScreen())); return view; } /** * */ public ViewDescriptor[] getViewDescriptors() { ViewDescriptor[] vd = new ViewDescriptor[2]; vd[0] = new ViewDescriptor("default"); vd[0].setMimeType("application/xhtml+xml"); vd[1] = new ViewDescriptor("source"); vd[1].setMimeType("application/xml"); return vd; } /** * Flow */ private String getScreen() { StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); sb.append("<body>"); HttpServletRequest request = getRequest(); Enumeration parameters = request.getParameterNames(); if (!parameters.hasMoreElements()) { getSelectResourceTypeScreen(sb); } else { if (request.getParameter("resource-type") != null) { getResourceScreen(sb); } else if (request.getParameter("save-as") != null) { getSaveAsScreen(sb); } else if (request.getParameter("save") != null) { getSaveScreen(sb); } else { getNoSuchScreen(sb); } } sb.append("</body>"); sb.append("</html>"); return sb.toString(); } /** * */ private void getSelectResourceTypeScreen(StringBuffer sb) { sb.append("<h4>Create resource (step 1)</h4>"); sb.append("<h2>Select resource type</h2>"); sb.append("<form>"); sb.append("Resource Type: <select name=\"resource-type\">"); ResourceTypeRegistry rtr = new ResourceTypeRegistry(); ResourceTypeDefinition[] rtds = rtr.getResourceTypeDefinitions(); for (int i = 0; i < rtds.length; i++) { try { Resource resource = rtr.newResource(rtds[i].getResourceTypeUniversalName()); if (resource != null && ResourceAttributeHelper.hasAttributeImplemented(resource, "Creatable", "2")) { sb.append("<option value=\"" + rtds[i].getResourceTypeNamespace() + "::" + rtds[i].getResourceTypeLocalName() + "\">" + rtds[i].getResourceTypeLocalName() + "</option>"); } } catch(Exception e) { log.error(e); } } sb.append("</select>"); sb.append("<br/><input type=\"submit\" value=\"Next\"/>"); sb.append("</form>"); } /** * */ private void getNoSuchScreen(StringBuffer sb) { sb.append("<p>No such screen!</p>"); } /** * */ private void getSaveAsScreen(StringBuffer sb) { sb.append("<h4>Create resource (step 3)</h4>"); sb.append("<h2>Save As</h2>"); HttpServletRequest request = getRequest(); Enumeration parameters = request.getParameterNames(); if (parameters.hasMoreElements()) { sb.append("<ul>"); while (parameters.hasMoreElements()) { String parameter = (String) parameters.nextElement(); if (parameter.indexOf("rp.") == 0) { sb.append("<li>"+parameter+": "+request.getParameter(parameter)+"</li>"); } } sb.append("</ul>"); } String createName = request.getParameter("create-name"); sb.append("<p>"); sb.append("<form>"); if (createName != null) { sb.append("Name: <input type=\"text\" name=\"create-name\" value=\"" + createName + "\"/>"); } else { sb.append("Name: <input type=\"text\" name=\"create-name\"/>"); } sb.append("<br/><input type=\"submit\" value=\"Save\" name=\"save\"/>"); sb.append("</form>"); sb.append("</p>"); } /** * */ private void getSaveScreen(StringBuffer sb) { sb.append("<h4>Create resource (step 4)</h4>"); sb.append("<h2>Resource has been created</h2>"); String createName = request.getParameter("create-name"); sb.append("<p>New resource can be accessed at: <a href=\""+createName+"\">"+createName+"</a></p>"); } /** * */ private void getResourceScreen(StringBuffer sb) { String rtps = getRequest().getParameter("resource-type"); String resNamespace = rtps.substring(0, rtps.indexOf("::")); String resName = rtps.substring(rtps.indexOf("::") + 2); ResourceTypeRegistry rtr = new ResourceTypeRegistry(); try { String universalName = "<{"+ resNamespace +"}"+ resName +"/>"; log.debug("Universal Name: " + universalName); Resource resource = rtr.newResource(universalName); if (resource != null) { if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Creatable", "2")) { String[] propertyNames = ((CreatableV2) resource).getPropertyNames(); //((CreatableV2) resource).setProperty("Name", createName); sb.append("<h4>Create resource (step 2)</h4>"); sb.append("<h2>Enter/Select resource specific parameters</h2>"); sb.append("<p>Resource Type: " + resName + " ("+resNamespace+")</p>"); sb.append("<form>"); if (propertyNames != null && propertyNames.length > 0) { sb.append("<p>Resource specific properties:</p>"); for (int i = 0; i < propertyNames.length; i++) { sb.append(propertyNames[i] + ": "); String propertyType = ((CreatableV2) resource).getPropertyType(propertyNames[i]); if (propertyType != null && propertyType.equals(CreatableV2.TYPE_UPLOAD)) { sb.append("<input type=\"file\" name=\"rp."+propertyNames[i]+"\"/>"); } else { Object value = ((CreatableV2) resource).getProperty(propertyNames[i]); if (value == null) { sb.append("<input name=\"rp." + propertyNames[i] + "\" value=\"\" size=\"60\"/><br/>"); } else { sb.append("<input name=\"rp." + propertyNames[i] + "\" value=\"" + value + "\" size=\"60\"/><br/>"); } } } } else { sb.append("<p>No resource specific properties!</p>"); } sb.append("<br/><br/><input type=\"submit\" value=\"Save As\" name=\"save-as\"/>"); sb.append("</form>"); } } } catch (Exception e) { sb.append("<p>Exception: "+e+"</p>"); log.error(e); } } }
src/contributions/resources/resource-creator/src/java/org/wyona/yanel/impl/resources/ResourceCreatorResource.java
/* * Copyright 2006 Wyona */ package org.wyona.yanel.impl.resources; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.ResourceTypeDefinition; import org.wyona.yanel.core.ResourceTypeRegistry; import org.wyona.yanel.core.api.attributes.CreatableV2; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.attributes.viewable.ViewDescriptor; import org.wyona.yanel.core.util.ResourceAttributeHelper; import org.apache.log4j.Category; import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; /** * */ public class ResourceCreatorResource extends Resource implements ViewableV2{ private static Category log = Category.getInstance(ResourceCreatorResource.class); /** * */ public ResourceCreatorResource() { } /** * */ public boolean exists() { return true; } /** * */ public long getSize() { return -1; } /** * */ public View getView(String viewId) { View view = new View(); view.setMimeType("application/xhtml+xml"); view.setInputStream(new java.io.StringBufferInputStream(getScreen())); return view; } /** * */ public ViewDescriptor[] getViewDescriptors() { ViewDescriptor[] vd = new ViewDescriptor[2]; vd[0] = new ViewDescriptor("default"); vd[0].setMimeType("application/xhtml+xml"); vd[1] = new ViewDescriptor("source"); vd[1].setMimeType("application/xml"); return vd; } /** * Flow */ private String getScreen() { StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); sb.append("<body>"); HttpServletRequest request = getRequest(); Enumeration parameters = request.getParameterNames(); if (!parameters.hasMoreElements()) { getSelectResourceTypeScreen(sb); } else { if (request.getParameter("resource-type") != null) { getResourceScreen(sb); } else if (request.getParameter("save-as") != null) { getSaveAsScreen(sb); } else if (request.getParameter("save") != null) { getSaveScreen(sb); } else { getNoSuchScreen(sb); } } sb.append("</body>"); sb.append("</html>"); return sb.toString(); } /** * */ private void getSelectResourceTypeScreen(StringBuffer sb) { sb.append("<h4>Create resource (step 1)</h4>"); sb.append("<h2>Select resource type</h2>"); sb.append("<form>"); sb.append("Resource Type: <select name=\"resource-type\">"); ResourceTypeRegistry rtr = new ResourceTypeRegistry(); ResourceTypeDefinition[] rtds = rtr.getResourceTypeDefinitions(); for (int i = 0; i < rtds.length; i++) { try { Resource resource = rtr.newResource(rtds[i].getResourceTypeUniversalName()); if (resource != null && ResourceAttributeHelper.hasAttributeImplemented(resource, "Creatable", "2")) { sb.append("<option value=\"" + rtds[i].getResourceTypeNamespace() + "::" + rtds[i].getResourceTypeLocalName() + "\">" + rtds[i].getResourceTypeLocalName() + "</option>"); } } catch(Exception e) { log.error(e); } } sb.append("</select>"); sb.append("<br/><input type=\"submit\" value=\"Next\"/>"); sb.append("</form>"); } /** * */ private void getNoSuchScreen(StringBuffer sb) { sb.append("<p>No such screen!</p>"); } /** * */ private void getSaveAsScreen(StringBuffer sb) { sb.append("<h4>Create resource (step 3)</h4>"); sb.append("<h2>Save As</h2>"); HttpServletRequest request = getRequest(); Enumeration parameters = request.getParameterNames(); if (parameters.hasMoreElements()) { sb.append("<ul>"); while (parameters.hasMoreElements()) { String parameter = (String) parameters.nextElement(); if (parameter.indexOf("rp.") == 0) { sb.append("<li>"+parameter+": "+request.getParameter(parameter)+"</li>"); } } sb.append("</ul>"); } String createName = request.getParameter("create-name"); sb.append("<p>"); sb.append("<form>"); if (createName != null) { sb.append("Name: <input type=\"text\" name=\"create-name\" value=\"" + createName + "\"/>"); } else { sb.append("Name: <input type=\"text\" name=\"create-name\"/>"); } sb.append("<br/><input type=\"submit\" value=\"Save\" name=\"save\"/>"); sb.append("</form>"); sb.append("</p>"); } /** * */ private void getSaveScreen(StringBuffer sb) { sb.append("<h4>Create resource (step 4)</h4>"); sb.append("<h2>Resource has been created</h2>"); String createName = request.getParameter("create-name"); sb.append("<p>New resource can be accessed at: <a href=\""+createName+"\">"+createName+"</a></p>"); } /** * */ private void getResourceScreen(StringBuffer sb) { String rtps = getRequest().getParameter("resource-type"); String resNamespace = rtps.substring(0, rtps.indexOf("::")); String resName = rtps.substring(rtps.indexOf("::") + 2); ResourceTypeRegistry rtr = new ResourceTypeRegistry(); try { String universalName = "<{"+ resNamespace +"}"+ resName +"/>"; log.debug("Universal Name: " + universalName); Resource resource = rtr.newResource(universalName); if (resource != null) { if (ResourceAttributeHelper.hasAttributeImplemented(resource, "Creatable", "2")) { String[] propertyNames = ((CreatableV2) resource).getPropertyNames(); //((CreatableV2) resource).setProperty("Name", createName); sb.append("<h4>Create resource (step 2)</h4>"); sb.append("<h2>Enter/Select resource specific parameters</h2>"); sb.append("<p>Resource Type: " + resName + " ("+resNamespace+")</p>"); sb.append("<form>"); if (propertyNames != null && propertyNames.length > 0) { sb.append("<p>Resource specific properties:</p>"); for (int i = 0; i < propertyNames.length; i++) { sb.append(propertyNames[i] + ": "); String propertyType = ((CreatableV2) resource).getPropertyType(propertyNames[i]); if (propertyType != null && propertyType.equals(CreatableV2.TYPE_UPLOAD)) { sb.append("<input type=\"file\" name=\"rp."+propertyNames[i]+"\"/>"); } else { sb.append("<input name=\"rp." + propertyNames[i] + "\" value=\"" + ((CreatableV2) resource).getProperty(propertyNames[i]) + "\" size=\"60\"/><br/>"); } } } else { sb.append("<p>No resource specific properties!</p>"); } sb.append("<br/><br/><input type=\"submit\" value=\"Save As\" name=\"save-as\"/>"); sb.append("</form>"); } } } catch (Exception e) { sb.append("<p>Exception: "+e+"</p>"); log.error(e); } } }
check if value is null
src/contributions/resources/resource-creator/src/java/org/wyona/yanel/impl/resources/ResourceCreatorResource.java
check if value is null
<ide><path>rc/contributions/resources/resource-creator/src/java/org/wyona/yanel/impl/resources/ResourceCreatorResource.java <ide> if (propertyType != null && propertyType.equals(CreatableV2.TYPE_UPLOAD)) { <ide> sb.append("<input type=\"file\" name=\"rp."+propertyNames[i]+"\"/>"); <ide> } else { <del> sb.append("<input name=\"rp." + propertyNames[i] <del> + "\" value=\"" <del> + ((CreatableV2) resource).getProperty(propertyNames[i]) <del> + "\" size=\"60\"/><br/>"); <add> Object value = ((CreatableV2) resource).getProperty(propertyNames[i]); <add> if (value == null) { <add> sb.append("<input name=\"rp." + propertyNames[i] + "\" value=\"\" size=\"60\"/><br/>"); <add> } else { <add> sb.append("<input name=\"rp." + propertyNames[i] + "\" value=\"" + value + "\" size=\"60\"/><br/>"); <add> } <ide> } <ide> } <ide> } else {
Java
apache-2.0
52b694331038280b132f8e6be5ddcfb579fed9c2
0
KrisLee/libgdx,czyzby/libgdx,ya7lelkom/libgdx,haedri/libgdx-1,basherone/libgdxcn,czyzby/libgdx,kotcrab/libgdx,MathieuDuponchelle/gdx,tommyettinger/libgdx,azakhary/libgdx,kagehak/libgdx,bsmr-java/libgdx,luischavez/libgdx,kotcrab/libgdx,collinsmith/libgdx,tell10glu/libgdx,Badazdz/libgdx,saltares/libgdx,firefly2442/libgdx,zhimaijoy/libgdx,stinsonga/libgdx,PedroRomanoBarbosa/libgdx,GreenLightning/libgdx,KrisLee/libgdx,JFixby/libgdx,Badazdz/libgdx,ya7lelkom/libgdx,del-sol/libgdx,thepullman/libgdx,haedri/libgdx-1,yangweigbh/libgdx,Heart2009/libgdx,saqsun/libgdx,ttencate/libgdx,Zonglin-Li6565/libgdx,azakhary/libgdx,ThiagoGarciaAlves/libgdx,Wisienkas/libgdx,nelsonsilva/libgdx,stinsonga/libgdx,revo09/libgdx,billgame/libgdx,Arcnor/libgdx,nrallakis/libgdx,libgdx/libgdx,ricardorigodon/libgdx,MovingBlocks/libgdx,junkdog/libgdx,kzganesan/libgdx,tommyettinger/libgdx,luischavez/libgdx,stickyd/libgdx,js78/libgdx,gf11speed/libgdx,alex-dorokhov/libgdx,stinsonga/libgdx,bsmr-java/libgdx,anserran/libgdx,basherone/libgdxcn,samskivert/libgdx,ThiagoGarciaAlves/libgdx,Senth/libgdx,andyvand/libgdx,xoppa/libgdx,billgame/libgdx,curtiszimmerman/libgdx,ya7lelkom/libgdx,collinsmith/libgdx,Xhanim/libgdx,ztv/libgdx,PedroRomanoBarbosa/libgdx,petugez/libgdx,firefly2442/libgdx,hyvas/libgdx,SidneyXu/libgdx,cypherdare/libgdx,kagehak/libgdx,NathanSweet/libgdx,Heart2009/libgdx,js78/libgdx,309746069/libgdx,Xhanim/libgdx,ryoenji/libgdx,UnluckyNinja/libgdx,junkdog/libgdx,yangweigbh/libgdx,ztv/libgdx,ricardorigodon/libgdx,fwolff/libgdx,zhimaijoy/libgdx,js78/libgdx,titovmaxim/libgdx,saqsun/libgdx,nudelchef/libgdx,SidneyXu/libgdx,antag99/libgdx,jasonwee/libgdx,katiepino/libgdx,BlueRiverInteractive/libgdx,gouessej/libgdx,Badazdz/libgdx,djom20/libgdx,copystudy/libgdx,revo09/libgdx,kagehak/libgdx,mumer92/libgdx,anserran/libgdx,thepullman/libgdx,noelsison2/libgdx,sarkanyi/libgdx,curtiszimmerman/libgdx,xoppa/libgdx,FyiurAmron/libgdx,katiepino/libgdx,GreenLightning/libgdx,alireza-hosseini/libgdx,xpenatan/libgdx-LWJGL3,EsikAntony/libgdx,ttencate/libgdx,xoppa/libgdx,luischavez/libgdx,gf11speed/libgdx,UnluckyNinja/libgdx,hyvas/libgdx,andyvand/libgdx,ThiagoGarciaAlves/libgdx,codepoke/libgdx,FyiurAmron/libgdx,fwolff/libgdx,srwonka/libGdx,1yvT0s/libgdx,Thotep/libgdx,Heart2009/libgdx,gdos/libgdx,gdos/libgdx,samskivert/libgdx,jberberick/libgdx,Arcnor/libgdx,MathieuDuponchelle/gdx,del-sol/libgdx,anserran/libgdx,JFixby/libgdx,MathieuDuponchelle/gdx,EsikAntony/libgdx,stickyd/libgdx,js78/libgdx,titovmaxim/libgdx,cypherdare/libgdx,toa5/libgdx,noelsison2/libgdx,lordjone/libgdx,billgame/libgdx,SidneyXu/libgdx,billgame/libgdx,petugez/libgdx,FyiurAmron/libgdx,FyiurAmron/libgdx,xoppa/libgdx,PedroRomanoBarbosa/libgdx,nooone/libgdx,ryoenji/libgdx,hyvas/libgdx,youprofit/libgdx,josephknight/libgdx,youprofit/libgdx,MathieuDuponchelle/gdx,fwolff/libgdx,copystudy/libgdx,Heart2009/libgdx,zhimaijoy/libgdx,del-sol/libgdx,jasonwee/libgdx,andyvand/libgdx,KrisLee/libgdx,katiepino/libgdx,sarkanyi/libgdx,gouessej/libgdx,nooone/libgdx,sjosegarcia/libgdx,Deftwun/libgdx,Xhanim/libgdx,Badazdz/libgdx,jasonwee/libgdx,noelsison2/libgdx,tell10glu/libgdx,sarkanyi/libgdx,tommycli/libgdx,youprofit/libgdx,BlueRiverInteractive/libgdx,saqsun/libgdx,bladecoder/libgdx,sjosegarcia/libgdx,katiepino/libgdx,flaiker/libgdx,alireza-hosseini/libgdx,fiesensee/libgdx,nelsonsilva/libgdx,MikkelTAndersen/libgdx,FredGithub/libgdx,ttencate/libgdx,nudelchef/libgdx,jasonwee/libgdx,Zonglin-Li6565/libgdx,petugez/libgdx,alireza-hosseini/libgdx,Deftwun/libgdx,katiepino/libgdx,hyvas/libgdx,fwolff/libgdx,nooone/libgdx,zhimaijoy/libgdx,bsmr-java/libgdx,collinsmith/libgdx,youprofit/libgdx,shiweihappy/libgdx,ThiagoGarciaAlves/libgdx,azakhary/libgdx,saltares/libgdx,GreenLightning/libgdx,ttencate/libgdx,petugez/libgdx,fwolff/libgdx,copystudy/libgdx,TheAks999/libgdx,samskivert/libgdx,ninoalma/libgdx,JFixby/libgdx,ricardorigodon/libgdx,Zonglin-Li6565/libgdx,jsjolund/libgdx,josephknight/libgdx,MikkelTAndersen/libgdx,shiweihappy/libgdx,SidneyXu/libgdx,noelsison2/libgdx,junkdog/libgdx,bsmr-java/libgdx,BlueRiverInteractive/libgdx,zhimaijoy/libgdx,toa5/libgdx,js78/libgdx,billgame/libgdx,samskivert/libgdx,mumer92/libgdx,gf11speed/libgdx,tommycli/libgdx,FredGithub/libgdx,yangweigbh/libgdx,firefly2442/libgdx,katiepino/libgdx,tell10glu/libgdx,toloudis/libgdx,toa5/libgdx,Thotep/libgdx,PedroRomanoBarbosa/libgdx,zommuter/libgdx,ztv/libgdx,Zonglin-Li6565/libgdx,sjosegarcia/libgdx,srwonka/libGdx,nrallakis/libgdx,shiweihappy/libgdx,collinsmith/libgdx,ryoenji/libgdx,JFixby/libgdx,xoppa/libgdx,kagehak/libgdx,titovmaxim/libgdx,basherone/libgdxcn,ztv/libgdx,309746069/libgdx,bladecoder/libgdx,EsikAntony/libgdx,codepoke/libgdx,nudelchef/libgdx,nave966/libgdx,josephknight/libgdx,gdos/libgdx,titovmaxim/libgdx,firefly2442/libgdx,haedri/libgdx-1,josephknight/libgdx,nave966/libgdx,lordjone/libgdx,xpenatan/libgdx-LWJGL3,djom20/libgdx,cypherdare/libgdx,gdos/libgdx,bsmr-java/libgdx,luischavez/libgdx,ThiagoGarciaAlves/libgdx,ninoalma/libgdx,gouessej/libgdx,sinistersnare/libgdx,thepullman/libgdx,xranby/libgdx,Zonglin-Li6565/libgdx,UnluckyNinja/libgdx,309746069/libgdx,thepullman/libgdx,junkdog/libgdx,MetSystem/libgdx,ThiagoGarciaAlves/libgdx,MathieuDuponchelle/gdx,ttencate/libgdx,tommyettinger/libgdx,titovmaxim/libgdx,MathieuDuponchelle/gdx,czyzby/libgdx,tommycli/libgdx,nelsonsilva/libgdx,noelsison2/libgdx,sarkanyi/libgdx,FredGithub/libgdx,flaiker/libgdx,bsmr-java/libgdx,EsikAntony/libgdx,saltares/libgdx,Senth/libgdx,ricardorigodon/libgdx,FyiurAmron/libgdx,stickyd/libgdx,bsmr-java/libgdx,UnluckyNinja/libgdx,snovak/libgdx,kzganesan/libgdx,KrisLee/libgdx,ricardorigodon/libgdx,jsjolund/libgdx,Heart2009/libgdx,realitix/libgdx,fiesensee/libgdx,antag99/libgdx,thepullman/libgdx,lordjone/libgdx,xranby/libgdx,SidneyXu/libgdx,haedri/libgdx-1,mumer92/libgdx,kotcrab/libgdx,nudelchef/libgdx,azakhary/libgdx,Wisienkas/libgdx,alireza-hosseini/libgdx,nudelchef/libgdx,Dzamir/libgdx,GreenLightning/libgdx,srwonka/libGdx,petugez/libgdx,billgame/libgdx,copystudy/libgdx,haedri/libgdx-1,nave966/libgdx,NathanSweet/libgdx,Arcnor/libgdx,JDReutt/libgdx,MetSystem/libgdx,MathieuDuponchelle/gdx,FyiurAmron/libgdx,309746069/libgdx,BlueRiverInteractive/libgdx,sjosegarcia/libgdx,Gliby/libgdx,GreenLightning/libgdx,saltares/libgdx,bgroenks96/libgdx,EsikAntony/libgdx,samskivert/libgdx,ttencate/libgdx,bgroenks96/libgdx,tommycli/libgdx,MetSystem/libgdx,thepullman/libgdx,designcrumble/libgdx,jasonwee/libgdx,KrisLee/libgdx,sinistersnare/libgdx,jberberick/libgdx,realitix/libgdx,1yvT0s/libgdx,gdos/libgdx,davebaol/libgdx,jberberick/libgdx,fiesensee/libgdx,bgroenks96/libgdx,ryoenji/libgdx,sarkanyi/libgdx,haedri/libgdx-1,MetSystem/libgdx,copystudy/libgdx,Deftwun/libgdx,fwolff/libgdx,Dzamir/libgdx,fiesensee/libgdx,xoppa/libgdx,saqsun/libgdx,JDReutt/libgdx,kagehak/libgdx,xoppa/libgdx,stinsonga/libgdx,kagehak/libgdx,ya7lelkom/libgdx,curtiszimmerman/libgdx,antag99/libgdx,toa5/libgdx,JDReutt/libgdx,realitix/libgdx,xranby/libgdx,lordjone/libgdx,FredGithub/libgdx,FyiurAmron/libgdx,MovingBlocks/libgdx,andyvand/libgdx,gf11speed/libgdx,snovak/libgdx,revo09/libgdx,gdos/libgdx,gdos/libgdx,EsikAntony/libgdx,mumer92/libgdx,Zonglin-Li6565/libgdx,junkdog/libgdx,Thotep/libgdx,codepoke/libgdx,xpenatan/libgdx-LWJGL3,gouessej/libgdx,nudelchef/libgdx,TheAks999/libgdx,titovmaxim/libgdx,Thotep/libgdx,saqsun/libgdx,sjosegarcia/libgdx,bladecoder/libgdx,TheAks999/libgdx,Badazdz/libgdx,cypherdare/libgdx,SidneyXu/libgdx,Gliby/libgdx,TheAks999/libgdx,MovingBlocks/libgdx,EsikAntony/libgdx,JFixby/libgdx,MadcowD/libgdx,ninoalma/libgdx,nooone/libgdx,saltares/libgdx,mumer92/libgdx,youprofit/libgdx,Heart2009/libgdx,1yvT0s/libgdx,josephknight/libgdx,mumer92/libgdx,JDReutt/libgdx,FredGithub/libgdx,ztv/libgdx,toa5/libgdx,xranby/libgdx,TheAks999/libgdx,jasonwee/libgdx,saltares/libgdx,sjosegarcia/libgdx,sarkanyi/libgdx,thepullman/libgdx,TheAks999/libgdx,realitix/libgdx,MetSystem/libgdx,KrisLee/libgdx,anserran/libgdx,codepoke/libgdx,JFixby/libgdx,nrallakis/libgdx,del-sol/libgdx,JFixby/libgdx,Senth/libgdx,Xhanim/libgdx,Gliby/libgdx,Wisienkas/libgdx,tell10glu/libgdx,ya7lelkom/libgdx,Badazdz/libgdx,tommycli/libgdx,ya7lelkom/libgdx,lordjone/libgdx,MadcowD/libgdx,ricardorigodon/libgdx,ryoenji/libgdx,saqsun/libgdx,josephknight/libgdx,yangweigbh/libgdx,MovingBlocks/libgdx,toloudis/libgdx,kzganesan/libgdx,copystudy/libgdx,MetSystem/libgdx,djom20/libgdx,mumer92/libgdx,toloudis/libgdx,Wisienkas/libgdx,lordjone/libgdx,nrallakis/libgdx,nave966/libgdx,revo09/libgdx,ttencate/libgdx,kzganesan/libgdx,bgroenks96/libgdx,noelsison2/libgdx,samskivert/libgdx,nrallakis/libgdx,sinistersnare/libgdx,josephknight/libgdx,BlueRiverInteractive/libgdx,JDReutt/libgdx,BlueRiverInteractive/libgdx,Gliby/libgdx,samskivert/libgdx,nrallakis/libgdx,jberberick/libgdx,toloudis/libgdx,fwolff/libgdx,ThiagoGarciaAlves/libgdx,Dzamir/libgdx,PedroRomanoBarbosa/libgdx,djom20/libgdx,MovingBlocks/libgdx,azakhary/libgdx,xranby/libgdx,ztv/libgdx,JDReutt/libgdx,petugez/libgdx,noelsison2/libgdx,firefly2442/libgdx,billgame/libgdx,realitix/libgdx,sarkanyi/libgdx,Wisienkas/libgdx,czyzby/libgdx,ryoenji/libgdx,flaiker/libgdx,petugez/libgdx,ttencate/libgdx,gouessej/libgdx,alex-dorokhov/libgdx,nave966/libgdx,Zomby2D/libgdx,MovingBlocks/libgdx,Deftwun/libgdx,Gliby/libgdx,davebaol/libgdx,codepoke/libgdx,ninoalma/libgdx,Zonglin-Li6565/libgdx,del-sol/libgdx,collinsmith/libgdx,djom20/libgdx,designcrumble/libgdx,Zomby2D/libgdx,nooone/libgdx,bgroenks96/libgdx,fiesensee/libgdx,KrisLee/libgdx,katiepino/libgdx,tell10glu/libgdx,srwonka/libGdx,alex-dorokhov/libgdx,MadcowD/libgdx,jsjolund/libgdx,designcrumble/libgdx,jberberick/libgdx,youprofit/libgdx,UnluckyNinja/libgdx,davebaol/libgdx,Senth/libgdx,xpenatan/libgdx-LWJGL3,xoppa/libgdx,MovingBlocks/libgdx,stickyd/libgdx,bgroenks96/libgdx,sinistersnare/libgdx,Zomby2D/libgdx,PedroRomanoBarbosa/libgdx,TheAks999/libgdx,curtiszimmerman/libgdx,PedroRomanoBarbosa/libgdx,saltares/libgdx,FredGithub/libgdx,JDReutt/libgdx,snovak/libgdx,shiweihappy/libgdx,ricardorigodon/libgdx,Wisienkas/libgdx,zommuter/libgdx,titovmaxim/libgdx,GreenLightning/libgdx,del-sol/libgdx,xranby/libgdx,jsjolund/libgdx,libgdx/libgdx,MadcowD/libgdx,czyzby/libgdx,flaiker/libgdx,stickyd/libgdx,nudelchef/libgdx,del-sol/libgdx,codepoke/libgdx,junkdog/libgdx,revo09/libgdx,hyvas/libgdx,libgdx/libgdx,309746069/libgdx,fiesensee/libgdx,zommuter/libgdx,zommuter/libgdx,billgame/libgdx,snovak/libgdx,anserran/libgdx,alireza-hosseini/libgdx,309746069/libgdx,jberberick/libgdx,FredGithub/libgdx,NathanSweet/libgdx,bladecoder/libgdx,bgroenks96/libgdx,hyvas/libgdx,tommycli/libgdx,yangweigbh/libgdx,ninoalma/libgdx,Xhanim/libgdx,xranby/libgdx,Dzamir/libgdx,codepoke/libgdx,Wisienkas/libgdx,kotcrab/libgdx,luischavez/libgdx,curtiszimmerman/libgdx,Wisienkas/libgdx,gdos/libgdx,nave966/libgdx,kotcrab/libgdx,srwonka/libGdx,MovingBlocks/libgdx,antag99/libgdx,shiweihappy/libgdx,Zomby2D/libgdx,toloudis/libgdx,MikkelTAndersen/libgdx,Dzamir/libgdx,curtiszimmerman/libgdx,tommycli/libgdx,curtiszimmerman/libgdx,davebaol/libgdx,czyzby/libgdx,Senth/libgdx,sjosegarcia/libgdx,curtiszimmerman/libgdx,jsjolund/libgdx,antag99/libgdx,ya7lelkom/libgdx,anserran/libgdx,309746069/libgdx,haedri/libgdx-1,js78/libgdx,jsjolund/libgdx,jasonwee/libgdx,alireza-hosseini/libgdx,alireza-hosseini/libgdx,youprofit/libgdx,UnluckyNinja/libgdx,MikkelTAndersen/libgdx,MadcowD/libgdx,youprofit/libgdx,zommuter/libgdx,Dzamir/libgdx,luischavez/libgdx,tommyettinger/libgdx,Thotep/libgdx,snovak/libgdx,Arcnor/libgdx,kzganesan/libgdx,nelsonsilva/libgdx,ztv/libgdx,Xhanim/libgdx,MetSystem/libgdx,katiepino/libgdx,designcrumble/libgdx,SidneyXu/libgdx,1yvT0s/libgdx,collinsmith/libgdx,MetSystem/libgdx,1yvT0s/libgdx,MikkelTAndersen/libgdx,copystudy/libgdx,srwonka/libGdx,zommuter/libgdx,sinistersnare/libgdx,toa5/libgdx,antag99/libgdx,toloudis/libgdx,Deftwun/libgdx,JDReutt/libgdx,saqsun/libgdx,alex-dorokhov/libgdx,hyvas/libgdx,sjosegarcia/libgdx,gf11speed/libgdx,309746069/libgdx,Thotep/libgdx,bgroenks96/libgdx,ninoalma/libgdx,noelsison2/libgdx,sinistersnare/libgdx,alex-dorokhov/libgdx,Gliby/libgdx,basherone/libgdxcn,gouessej/libgdx,EsikAntony/libgdx,1yvT0s/libgdx,Dzamir/libgdx,ya7lelkom/libgdx,snovak/libgdx,Deftwun/libgdx,lordjone/libgdx,codepoke/libgdx,realitix/libgdx,shiweihappy/libgdx,MathieuDuponchelle/gdx,kotcrab/libgdx,Badazdz/libgdx,czyzby/libgdx,designcrumble/libgdx,PedroRomanoBarbosa/libgdx,junkdog/libgdx,libgdx/libgdx,xpenatan/libgdx-LWJGL3,FyiurAmron/libgdx,KrisLee/libgdx,MadcowD/libgdx,kagehak/libgdx,kotcrab/libgdx,kzganesan/libgdx,petugez/libgdx,xpenatan/libgdx-LWJGL3,stickyd/libgdx,nave966/libgdx,tell10glu/libgdx,Badazdz/libgdx,flaiker/libgdx,zhimaijoy/libgdx,zhimaijoy/libgdx,flaiker/libgdx,gf11speed/libgdx,djom20/libgdx,Zonglin-Li6565/libgdx,samskivert/libgdx,basherone/libgdxcn,fwolff/libgdx,nave966/libgdx,stickyd/libgdx,UnluckyNinja/libgdx,revo09/libgdx,ninoalma/libgdx,Gliby/libgdx,davebaol/libgdx,czyzby/libgdx,stickyd/libgdx,designcrumble/libgdx,fiesensee/libgdx,xpenatan/libgdx-LWJGL3,lordjone/libgdx,Senth/libgdx,nelsonsilva/libgdx,Dzamir/libgdx,Gliby/libgdx,alex-dorokhov/libgdx,collinsmith/libgdx,gf11speed/libgdx,ninoalma/libgdx,alex-dorokhov/libgdx,azakhary/libgdx,ztv/libgdx,GreenLightning/libgdx,snovak/libgdx,tell10glu/libgdx,libgdx/libgdx,sarkanyi/libgdx,Senth/libgdx,alireza-hosseini/libgdx,revo09/libgdx,andyvand/libgdx,fiesensee/libgdx,nooone/libgdx,ryoenji/libgdx,UnluckyNinja/libgdx,yangweigbh/libgdx,GreenLightning/libgdx,JFixby/libgdx,ricardorigodon/libgdx,Heart2009/libgdx,yangweigbh/libgdx,zommuter/libgdx,luischavez/libgdx,MikkelTAndersen/libgdx,andyvand/libgdx,jberberick/libgdx,realitix/libgdx,shiweihappy/libgdx,luischavez/libgdx,Deftwun/libgdx,gouessej/libgdx,anserran/libgdx,zhimaijoy/libgdx,BlueRiverInteractive/libgdx,cypherdare/libgdx,snovak/libgdx,Deftwun/libgdx,nelsonsilva/libgdx,saltares/libgdx,antag99/libgdx,toa5/libgdx,Arcnor/libgdx,Senth/libgdx,zommuter/libgdx,Heart2009/libgdx,SidneyXu/libgdx,1yvT0s/libgdx,ThiagoGarciaAlves/libgdx,1yvT0s/libgdx,TheAks999/libgdx,Zomby2D/libgdx,Xhanim/libgdx,MathieuDuponchelle/gdx,anserran/libgdx,toloudis/libgdx,hyvas/libgdx,antag99/libgdx,junkdog/libgdx,tell10glu/libgdx,flaiker/libgdx,designcrumble/libgdx,kagehak/libgdx,BlueRiverInteractive/libgdx,bsmr-java/libgdx,jsjolund/libgdx,mumer92/libgdx,kotcrab/libgdx,shiweihappy/libgdx,Xhanim/libgdx,tommycli/libgdx,nrallakis/libgdx,firefly2442/libgdx,revo09/libgdx,nudelchef/libgdx,designcrumble/libgdx,MadcowD/libgdx,MikkelTAndersen/libgdx,haedri/libgdx-1,del-sol/libgdx,jsjolund/libgdx,js78/libgdx,Thotep/libgdx,realitix/libgdx,xpenatan/libgdx-LWJGL3,gf11speed/libgdx,bladecoder/libgdx,andyvand/libgdx,FredGithub/libgdx,saqsun/libgdx,Arcnor/libgdx,firefly2442/libgdx,js78/libgdx,nrallakis/libgdx,tommyettinger/libgdx,djom20/libgdx,Thotep/libgdx,yangweigbh/libgdx,kzganesan/libgdx,copystudy/libgdx,djom20/libgdx,NathanSweet/libgdx,MadcowD/libgdx,flaiker/libgdx,MikkelTAndersen/libgdx,andyvand/libgdx,jberberick/libgdx,collinsmith/libgdx,srwonka/libGdx,jasonwee/libgdx,davebaol/libgdx,stinsonga/libgdx,xranby/libgdx,josephknight/libgdx,srwonka/libGdx,toloudis/libgdx,basherone/libgdxcn,titovmaxim/libgdx,gouessej/libgdx,thepullman/libgdx,firefly2442/libgdx,NathanSweet/libgdx,toa5/libgdx,alex-dorokhov/libgdx
package com.badlogic.gdx.scenes.scene2d.ui; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Group; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.ChangeEvent; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.scenes.scene2d.utils.Layout; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Pools; /** A tree widget where each node has an icon, actor, and child nodes. * <p> * The preferred size of the tree is determined by the preferred size of the actors for the expanded nodes. * <p> * {@link ChangeEvent} is fired when the selected node changes. * @author Nathan Sweet */ public class Tree extends WidgetGroup { TreeStyle style; final Array<Node> rootNodes = new Array(); final Array<Node> selectedNodes = new Array(); float ySpacing = 4, iconSpacing = 2, padding = 0, indentSpacing; private float leftColumnWidth, prefWidth, prefHeight; private boolean sizeInvalid = true; private Node foundNode; Node overNode; private ClickListener clickListener; public Tree (Skin skin) { this(skin.get(TreeStyle.class)); } public Tree (Skin skin, String styleName) { this(skin.get(styleName, TreeStyle.class)); } public Tree (TreeStyle style) { setStyle(style); initialize(); } private void initialize () { addListener(clickListener = new ClickListener() { public void clicked (InputEvent event, float x, float y) { Node node = getNodeAt(y); if (node == null) return; if (node != getNodeAt(getTouchDownY())) return; if (selectedNodes.size > 0 && (Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT))) { // Select range (shift/ctrl). float low = selectedNodes.first().actor.getY(); float high = node.actor.getY(); if (!Gdx.input.isKeyPressed(Keys.CONTROL_LEFT) && !Gdx.input.isKeyPressed(Keys.CONTROL_RIGHT)) selectedNodes.clear(); if (low > high) selectNodes(rootNodes, high, low); else selectNodes(rootNodes, low, high); ChangeEvent changeEvent = Pools.obtain(ChangeEvent.class); fire(changeEvent); Pools.free(changeEvent); return; } if (!Gdx.input.isKeyPressed(Keys.CONTROL_LEFT) && !Gdx.input.isKeyPressed(Keys.CONTROL_RIGHT)) { if (node.children.size > 0) { // Toggle expanded. float rowX = node.actor.getX(); if (node.icon != null) rowX -= iconSpacing + node.icon.getMinWidth(); if (x < rowX) { node.setExpanded(!node.expanded); return; } } selectedNodes.clear(); } // Select single (ctrl). if (!selectedNodes.removeValue(node, true)) selectedNodes.add(node); ChangeEvent changeEvent = Pools.obtain(ChangeEvent.class); fire(changeEvent); Pools.free(changeEvent); } public boolean mouseMoved (InputEvent event, float x, float y) { setOverNode(getNodeAt(y)); return false; } public void exit (InputEvent event, float x, float y, int pointer, Actor toActor) { super.exit(event, x, y, pointer, toActor); if (toActor == null || !toActor.isDescendant(Tree.this)) setOverNode(null); } }); } public void setStyle (TreeStyle style) { this.style = style; indentSpacing = Math.max(style.plus.getMinWidth(), style.minus.getMinWidth()) + iconSpacing; } public void add (Node node) { insert(rootNodes.size, node); } public void insert (int index, Node node) { remove(node); node.parent = null; rootNodes.insert(index, node); node.addToTree(this); invalidateHierarchy(); } public void remove (Node node) { if (node.parent != null) { node.parent.remove(node); return; } rootNodes.removeValue(node, true); node.removeFromTree(this); invalidateHierarchy(); } /** Removes all tree nodes. */ public void clear () { super.clear(); rootNodes.clear(); selectedNodes.clear(); setOverNode(null); } public Array<Node> getNodes () { return rootNodes; } public void invalidate () { super.invalidate(); sizeInvalid = true; } private void computeSize () { sizeInvalid = false; prefWidth = style.plus.getMinWidth(); prefWidth = Math.max(prefWidth, style.minus.getMinWidth()); prefHeight = getHeight(); leftColumnWidth = 0; computeSize(rootNodes, indentSpacing); leftColumnWidth += iconSpacing + padding; prefWidth += leftColumnWidth + padding; prefHeight = getHeight() - (prefHeight + ySpacing); } private void computeSize (Array<Node> nodes, float indent) { float ySpacing = this.ySpacing; for (int i = 0, n = nodes.size; i < n; i++) { Node node = nodes.get(i); float rowWidth = indent + iconSpacing; Actor actor = node.actor; if (actor instanceof Layout) { Layout layout = (Layout)actor; rowWidth += layout.getPrefWidth(); node.height = layout.getPrefHeight(); layout.pack(); } else { rowWidth += actor.getWidth(); node.height = actor.getHeight(); } if (node.icon != null) { rowWidth += iconSpacing * 2 + node.icon.getMinWidth(); node.height = Math.max(node.height, node.icon.getMinHeight()); } prefWidth = Math.max(prefWidth, rowWidth); prefHeight -= node.height + ySpacing; if (node.expanded) computeSize(node.children, indent + indentSpacing); } } public void layout () { if (sizeInvalid) computeSize(); layout(rootNodes, leftColumnWidth + indentSpacing, getHeight()); } private float layout (Array<Node> nodes, float indent, float y) { float ySpacing = this.ySpacing; Drawable plus = style.plus, minus = style.minus; for (int i = 0, n = nodes.size; i < n; i++) { Node node = nodes.get(i); Actor actor = node.actor; float x = indent; if (node.icon != null) x += node.icon.getMinWidth(); y -= node.height; node.actor.setPosition(x, y); y -= ySpacing; if (node.expanded) y = layout(node.children, indent + indentSpacing, y); } return y; } public void draw (SpriteBatch batch, float parentAlpha) { Color color = getColor(); if (style.background != null) { batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); style.background.draw(batch, getX(), getY(), getWidth(), getHeight()); batch.setColor(Color.WHITE); } draw(batch, rootNodes, leftColumnWidth); super.draw(batch, parentAlpha); // Draw actors. } /** Draws selection, icons, and expand icons. */ private void draw (SpriteBatch batch, Array<Node> nodes, float indent) { Drawable plus = style.plus, minus = style.minus; float x = getX(), y = getY(); for (int i = 0, n = nodes.size; i < n; i++) { Node node = nodes.get(i); Actor actor = node.actor; if (selectedNodes.contains(node, true) && style.selection != null) { style.selection.draw(batch, x, y + actor.getY() - ySpacing / 2, getWidth(), node.height + ySpacing); } else if (node == overNode && style.over != null) { style.over.draw(batch, x, y + actor.getY() - ySpacing / 2, getWidth(), node.height + ySpacing); } if (node.icon != null) { float iconY = actor.getY() + Math.round((node.height - node.icon.getMinHeight()) / 2); batch.setColor(actor.getColor()); node.icon.draw(batch, x + node.actor.getX() - iconSpacing - node.icon.getMinWidth(), y + iconY, node.icon.getMinWidth(), node.icon.getMinHeight()); batch.setColor(Color.WHITE); } if (node.children.size == 0) continue; Drawable expandIcon = node.expanded ? minus : plus; float iconY = actor.getY() + Math.round((node.height - expandIcon.getMinHeight()) / 2); expandIcon.draw(batch, x + indent - iconSpacing, y + iconY, expandIcon.getMinWidth(), expandIcon.getMinHeight()); if (node.expanded) draw(batch, node.children, indent + indentSpacing); } } /** @return May be null. */ public Node getNodeAt (float y) { foundNode = null; getNodeAt(rootNodes, y, getHeight()); return foundNode; } private float getNodeAt (Array<Node> nodes, float y, float rowY) { for (int i = 0, n = nodes.size; i < n; i++) { Node node = nodes.get(i); if (y > rowY - node.height - ySpacing / 2 && y <= rowY + ySpacing / 2) { foundNode = node; return -1; } rowY -= node.height + ySpacing; if (node.expanded) { rowY = getNodeAt(node.children, y, rowY); if (rowY == -1) return -1; } } return rowY; } void selectNodes (Array<Node> nodes, float low, float high) { float ySpacing = this.ySpacing; for (int i = 0, n = nodes.size; i < n; i++) { Node node = nodes.get(i); if (node.actor.getY() < low) break; if (node.actor.getY() <= high) selectedNodes.add(node); if (node.expanded) selectNodes(node.children, low, high); } } public Array<Node> getSelection () { return selectedNodes; } public void setSelection (Node node) { selectedNodes.clear(); selectedNodes.add(node); } public void setSelection (Array<Node> nodes) { selectedNodes.clear(); selectedNodes.addAll(nodes); } public void addSelection (Node node) { selectedNodes.add(node); } public void clearSelection () { selectedNodes.clear(); } public TreeStyle getStyle () { return style; } public Array<Node> getRootNodes () { return rootNodes; } public Node getOverNode () { return overNode; } public void setOverNode (Node overNode) { this.overNode = overNode; } /** Sets the amount of horizontal space between the nodes and the left and right edges of the tree. */ public void setPadding (float padding) { this.padding = padding; } /** Sets the amount of vertical space between nodes. */ public void setYSpacing (float ySpacing) { this.ySpacing = ySpacing; } /** Sets the amount of horizontal space between the node actors and icons. */ public void setIconSpacing (float iconSpacing) { this.iconSpacing = iconSpacing; } public float getPrefWidth () { if (sizeInvalid) computeSize(); return prefWidth; } public float getPrefHeight () { if (sizeInvalid) computeSize(); return prefHeight; } /** Returns the node with the specified object, or null. */ public Node findNode (Object object) { if (object == null) throw new IllegalArgumentException("object cannot be null."); return findNode(rootNodes, object); } static Node findNode (Array<Node> nodes, Object object) { for (int i = 0, n = nodes.size; i < n; i++) { Node node = nodes.get(i); if (object.equals(node.object)) return node; } for (int i = 0, n = nodes.size; i < n; i++) { Node node = nodes.get(i); Node found = findNode(node.children, object); if (found != null) return found; } return null; } public void collapseAll () { collapseAll(rootNodes); } static void collapseAll (Array<Node> nodes) { for (int i = 0, n = nodes.size; i < n; i++) { Node node = nodes.get(i); node.setExpanded(false); collapseAll(node.children); } } public void expandAll () { expandAll(rootNodes); } static void expandAll (Array<Node> nodes) { for (int i = 0, n = nodes.size; i < n; i++) { Node node = nodes.get(i); node.expandAll(); } } /** Returns the click listener the tree uses for clicking on nodes and the over node. */ public ClickListener getClickListener () { return clickListener; } static public class Node { Actor actor; Node parent; final Array<Node> children = new Array(0); boolean expanded; Drawable icon; float height; Object object; public Node (Actor actor) { if (actor == null) throw new IllegalArgumentException("actor cannot be null."); this.actor = actor; } public void setExpanded (boolean expanded) { if (expanded == this.expanded || children.size == 0) return; this.expanded = expanded; Tree tree = getTree(); if (tree == null) return; if (expanded) { for (int i = 0, n = children.size; i < n; i++) children.get(i).addToTree(tree); } else { for (int i = 0, n = children.size; i < n; i++) children.get(i).removeFromTree(tree); } tree.invalidateHierarchy(); } /** Called to add the actor to the tree when the node's parent is expanded. */ protected void addToTree (Tree tree) { tree.addActor(actor); if (!expanded) return; for (int i = 0, n = children.size; i < n; i++) children.get(i).addToTree(tree); } /** Called to remove the actor from the tree when the node's parent is collapsed. */ protected void removeFromTree (Tree tree) { tree.removeActor(actor); if (!expanded) return; for (int i = 0, n = children.size; i < n; i++) children.get(i).removeFromTree(tree); } public void add (Node node) { insert(children.size, node); } public void insert (int index, Node node) { node.parent = this; children.insert(index, node); if (!expanded) return; Tree tree = getTree(); if (tree == null) return; for (int i = 0, n = children.size; i < n; i++) children.get(i).addToTree(tree); } public void remove () { Tree tree = getTree(); if (tree == null) return; tree.remove(this); } public void remove (Node node) { children.removeValue(node, true); if (!expanded) return; Tree tree = getTree(); if (tree == null) return; node.removeFromTree(tree); if (children.size == 0) expanded = false; } public void removeAll () { Tree tree = getTree(); if (tree != null) { for (int i = 0, n = children.size; i < n; i++) children.get(i).removeFromTree(tree); } children.clear(); } /** Returns the tree this node is currently in, or null. */ public Tree getTree () { Group parent = actor.getParent(); if (!(parent instanceof Tree)) return null; return (Tree)parent; } public Actor getActor () { return actor; } public boolean isExpanded () { return expanded; } public Array<Node> getChildren () { return children; } public Node getParent () { return parent; } /** Sets an icon that will be drawn to the left of the actor. */ public void setIcon (Drawable icon) { this.icon = icon; } public Object getObject () { return object; } /** Sets an application specific object for this node. */ public void setObject (Object object) { this.object = object; } public Drawable getIcon () { return icon; } /** Returns this node or the child node with the specified object, or null. */ public Node findNode (Object object) { if (object == null) throw new IllegalArgumentException("object cannot be null."); if (object.equals(this.object)) return this; return Tree.findNode(children, object); } /** Collapses all nodes under and including this node. */ public void collapseAll () { setExpanded(false); Tree.collapseAll(children); } /** Expands all nodes under and including this node. */ public void expandAll () { setExpanded(true); Tree.expandAll(children); } /** Expands all parent nodes of this node. */ public void expandTo () { Node node = parent; while (node != null) { node.setExpanded(true); node = node.parent; } } } /** The style for a {@link Tree}. * @author Nathan Sweet */ static public class TreeStyle { public Drawable plus, minus; /** Optional. */ public Drawable over, selection, background; public TreeStyle () { } public TreeStyle (Drawable plus, Drawable minus, Drawable selection) { this.plus = plus; this.minus = minus; this.selection = selection; } public TreeStyle (TreeStyle style) { this.plus = style.plus; this.minus = style.minus; this.selection = style.selection; } } }
gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Tree.java
package com.badlogic.gdx.scenes.scene2d.ui; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input.Keys; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.scenes.scene2d.Actor; import com.badlogic.gdx.scenes.scene2d.Group; import com.badlogic.gdx.scenes.scene2d.InputEvent; import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.ChangeEvent; import com.badlogic.gdx.scenes.scene2d.utils.ClickListener; import com.badlogic.gdx.scenes.scene2d.utils.Drawable; import com.badlogic.gdx.scenes.scene2d.utils.Layout; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Pools; /** A tree widget where each node has an icon, actor, and child nodes. * <p> * The preferred size of the tree is determined by the preferred size of the actors for the expanded nodes. * <p> * {@link ChangeEvent} is fired when the selected node changes. * @author Nathan Sweet */ public class Tree extends WidgetGroup { TreeStyle style; final Array<Node> rootNodes = new Array(); final Array<Node> selectedNodes = new Array(); float ySpacing = 4, iconSpacing = 2, padding = 0, indentSpacing; private float leftColumnWidth, prefWidth, prefHeight; private boolean sizeInvalid = true; private Node foundNode; Node overNode; private ClickListener clickListener; public Tree (Skin skin) { this(skin.get(TreeStyle.class)); } public Tree (Skin skin, String styleName) { this(skin.get(styleName, TreeStyle.class)); } public Tree (TreeStyle style) { setStyle(style); initialize(); } private void initialize () { addListener(clickListener = new ClickListener() { public void clicked (InputEvent event, float x, float y) { Node node = getNodeAt(y); if (node == null) return; if (node != getNodeAt(getTouchDownY())) return; if (selectedNodes.size > 0 && (Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT))) { // Select range (shift/ctrl). float low = selectedNodes.first().actor.getY(); float high = node.actor.getY(); if (!Gdx.input.isKeyPressed(Keys.CONTROL_LEFT) && !Gdx.input.isKeyPressed(Keys.CONTROL_RIGHT)) selectedNodes.clear(); if (low > high) selectNodes(rootNodes, high, low); else selectNodes(rootNodes, low, high); ChangeEvent changeEvent = Pools.obtain(ChangeEvent.class); fire(changeEvent); Pools.free(changeEvent); return; } if (!Gdx.input.isKeyPressed(Keys.CONTROL_LEFT) && !Gdx.input.isKeyPressed(Keys.CONTROL_RIGHT)) { if (node.children.size > 0) { // Toggle expanded. float rowX = node.actor.getX(); if (node.icon != null) rowX -= iconSpacing + node.icon.getMinWidth(); if (x < rowX) { node.setExpanded(!node.expanded); return; } } selectedNodes.clear(); } // Select single (ctrl). if (!selectedNodes.removeValue(node, true)) selectedNodes.add(node); ChangeEvent changeEvent = Pools.obtain(ChangeEvent.class); fire(changeEvent); Pools.free(changeEvent); } public boolean mouseMoved (InputEvent event, float x, float y) { setOverNode(getNodeAt(y)); return false; } public void exit (InputEvent event, float x, float y, int pointer, Actor toActor) { super.exit(event, x, y, pointer, toActor); if (toActor == null || !toActor.isDescendant(Tree.this)) setOverNode(null); } }); } public void setStyle (TreeStyle style) { this.style = style; indentSpacing = Math.max(style.plus.getMinWidth(), style.minus.getMinWidth()) + iconSpacing; } public void add (Node node) { insert(rootNodes.size, node); } public void insert (int index, Node node) { remove(node); node.parent = null; rootNodes.insert(index, node); node.addToTree(this); invalidateHierarchy(); } public void remove (Node node) { if (node.parent != null) { node.parent.remove(node); return; } rootNodes.removeValue(node, true); node.removeFromTree(this); invalidateHierarchy(); } /** Removes all tree nodes. */ public void clear () { super.clear(); rootNodes.clear(); selectedNodes.clear(); setOverNode(null); } public Array<Node> getNodes () { return rootNodes; } public void invalidate () { super.invalidate(); sizeInvalid = true; } private void computeSize () { sizeInvalid = false; prefWidth = style.plus.getMinWidth(); prefWidth = Math.max(prefWidth, style.minus.getMinWidth()); prefHeight = getHeight(); leftColumnWidth = 0; computeSize(rootNodes, indentSpacing); leftColumnWidth += iconSpacing + padding; prefWidth += leftColumnWidth + padding; prefHeight = getHeight() - (prefHeight + ySpacing); } private void computeSize (Array<Node> nodes, float indent) { float ySpacing = this.ySpacing; for (int i = 0, n = nodes.size; i < n; i++) { Node node = nodes.get(i); float rowWidth = indent + iconSpacing; Actor actor = node.actor; if (actor instanceof Layout) { Layout layout = (Layout)actor; rowWidth += layout.getPrefWidth(); node.height = layout.getPrefHeight(); layout.pack(); } else { rowWidth += actor.getWidth(); node.height = actor.getHeight(); } if (node.icon != null) { rowWidth += iconSpacing * 2 + node.icon.getMinWidth(); node.height = Math.max(node.height, node.icon.getMinHeight()); } prefWidth = Math.max(prefWidth, rowWidth); prefHeight -= node.height + ySpacing; if (node.expanded) computeSize(node.children, indent + indentSpacing); } } public void layout () { if (sizeInvalid) computeSize(); layout(rootNodes, leftColumnWidth + indentSpacing, getHeight()); } private float layout (Array<Node> nodes, float indent, float y) { float ySpacing = this.ySpacing; Drawable plus = style.plus, minus = style.minus; for (int i = 0, n = nodes.size; i < n; i++) { Node node = nodes.get(i); Actor actor = node.actor; float x = indent; if (node.icon != null) x += node.icon.getMinWidth(); y -= node.height; node.actor.setPosition(x, y); y -= ySpacing; if (node.expanded) y = layout(node.children, indent + indentSpacing, y); } return y; } public void draw (SpriteBatch batch, float parentAlpha) { Color color = getColor(); if (style.background != null) { batch.setColor(color.r, color.g, color.b, color.a * parentAlpha); style.background.draw(batch, getX(), getY(), getWidth(), getHeight()); batch.setColor(Color.WHITE); } draw(batch, rootNodes, leftColumnWidth); super.draw(batch, parentAlpha); // Draw actors. } /** Draws selection, icons, and expand icons. */ private void draw (SpriteBatch batch, Array<Node> nodes, float indent) { Drawable plus = style.plus, minus = style.minus; float x = getX(), y = getY(); for (int i = 0, n = nodes.size; i < n; i++) { Node node = nodes.get(i); Actor actor = node.actor; if (selectedNodes.contains(node, true) && style.selection != null) { style.selection.draw(batch, x, y + actor.getY() - ySpacing / 2, getWidth(), node.height + ySpacing); } else if (node == overNode && style.over != null) { style.over.draw(batch, x, y + actor.getY() - ySpacing / 2, getWidth(), node.height + ySpacing); } if (node.icon != null) { float iconY = actor.getY() + Math.round((node.height - node.icon.getMinHeight()) / 2); batch.setColor(actor.getColor()); node.icon.draw(batch, x + node.actor.getX() - iconSpacing - node.icon.getMinWidth(), y + iconY, node.icon.getMinWidth(), node.icon.getMinHeight()); batch.setColor(Color.WHITE); } if (node.children.size == 0) continue; Drawable expandIcon = node.expanded ? minus : plus; float iconY = actor.getY() + Math.round((node.height - expandIcon.getMinHeight()) / 2); expandIcon.draw(batch, x + indent - iconSpacing, y + iconY, expandIcon.getMinWidth(), expandIcon.getMinHeight()); if (node.expanded) draw(batch, node.children, indent + indentSpacing); } } /** @return May be null. */ public Node getNodeAt (float y) { foundNode = null; getNodeAt(rootNodes, y, getHeight()); return foundNode; } private float getNodeAt (Array<Node> nodes, float y, float rowY) { for (int i = 0, n = nodes.size; i < n; i++) { Node node = nodes.get(i); if (y > rowY - node.height - ySpacing / 2 && y <= rowY + ySpacing / 2) { foundNode = node; return -1; } rowY -= node.height + ySpacing; if (node.expanded) { rowY = getNodeAt(node.children, y, rowY); if (rowY == -1) return -1; } } return rowY; } void selectNodes (Array<Node> nodes, float low, float high) { float ySpacing = this.ySpacing; for (int i = 0, n = nodes.size; i < n; i++) { Node node = nodes.get(i); if (node.actor.getY() < low) break; if (node.actor.getY() <= high) selectedNodes.add(node); if (node.expanded) selectNodes(node.children, low, high); } } public Array<Node> getSelection () { return selectedNodes; } public void setSelection (Node node) { selectedNodes.clear(); selectedNodes.add(node); } public void setSelection (Array<Node> nodes) { selectedNodes.clear(); selectedNodes.addAll(nodes); } public void addSelection (Node node) { selectedNodes.add(node); } public void clearSelection () { selectedNodes.clear(); } public TreeStyle getStyle () { return style; } public Array<Node> getRootNodes () { return rootNodes; } public Node getOverNode () { return overNode; } public void setOverNode (Node overNode) { this.overNode = overNode; } /** Sets the amount of horizontal space between the nodes and the left and right edges of the tree. */ public void setPadding (float padding) { this.padding = padding; } /** Sets the amount of vertical space between nodes. */ public void setYSpacing (float ySpacing) { this.ySpacing = ySpacing; } /** Sets the amount of horizontal space between the node actors and icons. */ public void setIconSpacing (float iconSpacing) { this.iconSpacing = iconSpacing; } public float getPrefWidth () { if (sizeInvalid) computeSize(); return prefWidth; } public float getPrefHeight () { if (sizeInvalid) computeSize(); return prefHeight; } /** Returns the node with the specified object, or null. */ public Node findNode (Object object) { if (object == null) throw new IllegalArgumentException("object cannot be null."); return findNode(rootNodes, object); } static Node findNode (Array<Node> nodes, Object object) { for (int i = 0, n = nodes.size; i < n; i++) { Node node = nodes.get(i); if (object.equals(node.object)) return node; } for (int i = 0, n = nodes.size; i < n; i++) { Node node = nodes.get(i); Node found = findNode(node.children, object); if (found != null) return found; } return null; } public void collapseAll () { collapseAll(rootNodes); } static void collapseAll (Array<Node> nodes) { for (int i = 0, n = nodes.size; i < n; i++) { Node node = nodes.get(i); node.setExpanded(false); collapseAll(node.children); } } public void expandAll () { expandAll(rootNodes); } static void expandAll (Array<Node> nodes) { for (int i = 0, n = nodes.size; i < n; i++) { Node node = nodes.get(i); node.setExpanded(true); expandAll(node.children); } } /** Returns the click listener the tree uses for clicking on nodes and the over node. */ public ClickListener getClickListener () { return clickListener; } static public class Node { Actor actor; Node parent; final Array<Node> children = new Array(0); boolean expanded; Drawable icon; float height; Object object; public Node (Actor actor) { if (actor == null) throw new IllegalArgumentException("actor cannot be null."); this.actor = actor; } public void setExpanded (boolean expanded) { if (expanded == this.expanded || children.size == 0) return; this.expanded = expanded; Tree tree = getTree(); if (tree == null) return; if (expanded) { for (int i = 0, n = children.size; i < n; i++) children.get(i).addToTree(tree); } else { for (int i = 0, n = children.size; i < n; i++) children.get(i).removeFromTree(tree); } tree.invalidateHierarchy(); } /** Called to add the actor to the tree when the node's parent is expanded. */ protected void addToTree (Tree tree) { tree.addActor(actor); if (!expanded) return; for (int i = 0, n = children.size; i < n; i++) children.get(i).addToTree(tree); } /** Called to remove the actor from the tree when the node's parent is collapsed. */ protected void removeFromTree (Tree tree) { tree.removeActor(actor); if (!expanded) return; for (int i = 0, n = children.size; i < n; i++) children.get(i).removeFromTree(tree); } public void add (Node node) { insert(children.size, node); } public void insert (int index, Node node) { node.parent = this; children.insert(index, node); if (!expanded) return; Tree tree = getTree(); if (tree == null) return; for (int i = 0, n = children.size; i < n; i++) children.get(i).addToTree(tree); } public void remove () { Tree tree = getTree(); if (tree == null) return; tree.remove(this); } public void remove (Node node) { children.removeValue(node, true); if (!expanded) return; Tree tree = getTree(); if (tree == null) return; node.removeFromTree(tree); if (children.size == 0) expanded = false; } public void removeAll () { Tree tree = getTree(); if (tree != null) { for (int i = 0, n = children.size; i < n; i++) children.get(i).removeFromTree(tree); } children.clear(); } /** Returns the tree this node is currently in, or null. */ public Tree getTree () { Group parent = actor.getParent(); if (!(parent instanceof Tree)) return null; return (Tree)parent; } public Actor getActor () { return actor; } public boolean isExpanded () { return expanded; } public Array<Node> getChildren () { return children; } public Node getParent () { return parent; } /** Sets an icon that will be drawn to the left of the actor. */ public void setIcon (Drawable icon) { this.icon = icon; } public Object getObject () { return object; } /** Sets an application specific object for this node. */ public void setObject (Object object) { this.object = object; } public Drawable getIcon () { return icon; } /** Returns this node or the child node with the specified object, or null. */ public Node findNode (Object object) { if (object == null) throw new IllegalArgumentException("object cannot be null."); if (object.equals(this.object)) return this; return Tree.findNode(children, object); } /** Collapses all nodes under and including this node. */ public void collapseAll () { setExpanded(false); Tree.collapseAll(children); } /** Expands all nodes under and including this node. */ public void expandAll () { setExpanded(true); Tree.expandAll(children); } /** Expands all parent nodes of this node. */ public void expandTo () { Node node = parent; while (node != null) { node.setExpanded(true); node = node.parent; } } } /** The style for a {@link Tree}. * @author Nathan Sweet */ static public class TreeStyle { public Drawable plus, minus; /** Optional. */ public Drawable over, selection, background; public TreeStyle () { } public TreeStyle (Drawable plus, Drawable minus, Drawable selection) { this.plus = plus; this.minus = minus; this.selection = selection; } public TreeStyle (TreeStyle style) { this.plus = style.plus; this.minus = style.minus; this.selection = style.selection; } } }
Tree, enable overriding expandAll.
gdx/src/com/badlogic/gdx/scenes/scene2d/ui/Tree.java
Tree, enable overriding expandAll.
<ide><path>dx/src/com/badlogic/gdx/scenes/scene2d/ui/Tree.java <ide> static void expandAll (Array<Node> nodes) { <ide> for (int i = 0, n = nodes.size; i < n; i++) { <ide> Node node = nodes.get(i); <del> node.setExpanded(true); <del> expandAll(node.children); <add> node.expandAll(); <ide> } <ide> } <ide>
Java
apache-2.0
496e89eae5911e74148cdda5b584ef0abe9169c9
0
jekh/LittleProxy,adamfisk/LittleProxy,rwtemple/LittleProxy,ganskef/LittleProxy,ganskef/LittleProxy,verygoodsecurity/LittleProxy,ganskef/LittleProxy,rwtemple/LittleProxy,verygoodsecurity/LittleProxy,jekh/LittleProxy,adamfisk/LittleProxy,adamfisk/LittleProxy,ganskef/LittleProxy,verygoodsecurity/LittleProxy,jekh/LittleProxy,verygoodsecurity/LittleProxy,jekh/LittleProxy,rwtemple/LittleProxy,rwtemple/LittleProxy,verygoodsecurity/LittleProxy,ganskef/LittleProxy,jekh/LittleProxy,adamfisk/LittleProxy,rwtemple/LittleProxy,adamfisk/LittleProxy
package org.littleshoot.proxy.impl; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseEncoder; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.timeout.IdleStateHandler; import io.netty.handler.traffic.GlobalTrafficShapingHandler; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.StringUtils; import org.littleshoot.proxy.ActivityTracker; import org.littleshoot.proxy.FlowContext; import org.littleshoot.proxy.FullFlowContext; import org.littleshoot.proxy.HttpFilters; import org.littleshoot.proxy.HttpFiltersAdapter; import org.littleshoot.proxy.ProxyAuthenticator; import org.littleshoot.proxy.SslEngineSource; import javax.net.ssl.SSLSession; import java.io.UnsupportedEncodingException; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.nio.channels.ClosedChannelException; import java.nio.charset.Charset; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Pattern; import static org.littleshoot.proxy.impl.ConnectionState.AWAITING_CHUNK; import static org.littleshoot.proxy.impl.ConnectionState.AWAITING_INITIAL; import static org.littleshoot.proxy.impl.ConnectionState.AWAITING_PROXY_AUTHENTICATION; import static org.littleshoot.proxy.impl.ConnectionState.DISCONNECT_REQUESTED; import static org.littleshoot.proxy.impl.ConnectionState.NEGOTIATING_CONNECT; /** * <p> * Represents a connection from a client to our proxy. Each * ClientToProxyConnection can have multiple {@link ProxyToServerConnection}s, * at most one per outbound host:port. * </p> * * <p> * Once a ProxyToServerConnection has been created for a given server, it is * continually reused. The ProxyToServerConnection goes through its own * lifecycle of connects and disconnects, with different underlying * {@link Channel}s, but only a single ProxyToServerConnection object is used * per server. The one exception to this is CONNECT tunneling - if a connection * has been used for CONNECT tunneling, that connection will never be reused. * </p> * * <p> * As the ProxyToServerConnections receive responses from their servers, they * feed these back to the client by calling * {@link #respond(ProxyToServerConnection, HttpFilters, HttpRequest, HttpResponse, HttpObject)} * . * </p> */ public class ClientToProxyConnection extends ProxyConnection<HttpRequest> { private static final HttpResponseStatus CONNECTION_ESTABLISHED = new HttpResponseStatus( 200, "HTTP/1.1 200 Connection established"); /** * Used for case-insensitive comparisons when parsing Connection header values. */ private static final String LOWERCASE_TRANSFER_ENCODING_HEADER = HttpHeaders.Names.TRANSFER_ENCODING.toLowerCase(Locale.US); /** * Used for case-insensitive comparisons when checking direct proxy request. */ private static final Pattern HTTP_SCHEME = Pattern.compile("^http://.*", Pattern.CASE_INSENSITIVE); /** * Keep track of all ProxyToServerConnections by host+port. */ private final Map<String, ProxyToServerConnection> serverConnectionsByHostAndPort = new ConcurrentHashMap<String, ProxyToServerConnection>(); /** * Keep track of how many servers are currently in the process of * connecting. */ private final AtomicInteger numberOfCurrentlyConnectingServers = new AtomicInteger( 0); /** * Keep track of how many servers are currently connected. */ private final AtomicInteger numberOfCurrentlyConnectedServers = new AtomicInteger( 0); /** * Keep track of how many times we were able to reuse a connection. */ private final AtomicInteger numberOfReusedServerConnections = new AtomicInteger( 0); /** * This is the current server connection that we're using while transferring * chunked data. */ private volatile ProxyToServerConnection currentServerConnection; /** * The current filters to apply to incoming requests/chunks. */ private volatile HttpFilters currentFilters = new HttpFiltersAdapter(null); private volatile SSLSession clientSslSession; /** * Tracks whether or not this ClientToProxyConnection is current doing MITM. */ private volatile boolean mitming = false; private AtomicBoolean authenticated = new AtomicBoolean(); private final GlobalTrafficShapingHandler globalTrafficShapingHandler; /** * The current HTTP request that this connection is currently servicing. */ private volatile HttpRequest currentRequest; ClientToProxyConnection( final DefaultHttpProxyServer proxyServer, SslEngineSource sslEngineSource, boolean authenticateClients, ChannelPipeline pipeline, GlobalTrafficShapingHandler globalTrafficShapingHandler) { super(AWAITING_INITIAL, proxyServer, false); initChannelPipeline(pipeline); if (sslEngineSource != null) { LOG.debug("Enabling encryption of traffic from client to proxy"); encrypt(pipeline, sslEngineSource.newSslEngine(), authenticateClients) .addListener( new GenericFutureListener<Future<? super Channel>>() { @Override public void operationComplete( Future<? super Channel> future) throws Exception { if (future.isSuccess()) { clientSslSession = sslEngine .getSession(); recordClientSSLHandshakeSucceeded(); } } }); } this.globalTrafficShapingHandler = globalTrafficShapingHandler; LOG.debug("Created ClientToProxyConnection"); } /*************************************************************************** * Reading **************************************************************************/ @Override protected ConnectionState readHTTPInitial(HttpRequest httpRequest) { LOG.debug("Got request: {}", httpRequest); boolean authenticationRequired = authenticationRequired(httpRequest); if (authenticationRequired) { LOG.debug("Not authenticated!!"); return AWAITING_PROXY_AUTHENTICATION; } else { return doReadHTTPInitial(httpRequest); } } /** * <p> * Reads an {@link HttpRequest}. * </p> * * <p> * If we don't yet have a {@link ProxyToServerConnection} for the desired * server, this takes care of creating it. * </p> * * <p> * Note - the "server" could be a chained proxy, not the final endpoint for * the request. * </p> * * @param httpRequest * @return */ private ConnectionState doReadHTTPInitial(HttpRequest httpRequest) { // Make a copy of the original request this.currentRequest = copy(httpRequest); // Set up our filters based on the original request. If the HttpFiltersSource returns null (meaning the request/response // should not be filtered), fall back to the default no-op filter source. HttpFilters filterInstance = proxyServer.getFiltersSource().filterRequest(currentRequest, ctx); if (filterInstance != null) { currentFilters = filterInstance; } // Send the request through the clientToProxyRequest filter, and respond with the short-circuit response if required HttpResponse clientToProxyFilterResponse = currentFilters.clientToProxyRequest(httpRequest); if (clientToProxyFilterResponse != null) { LOG.debug("Responding to client with short-circuit response from filter: {}", clientToProxyFilterResponse); boolean keepAlive = respondWithShortCircuitResponse(clientToProxyFilterResponse); if (keepAlive) { return AWAITING_INITIAL; } else { return DISCONNECT_REQUESTED; } } // short-circuit requests that treat the proxy as the "origin" server, to avoid infinite loops if (isRequestToOriginServer(httpRequest)) { boolean keepAlive = writeBadRequest(httpRequest); if (keepAlive) { return AWAITING_INITIAL; } else { return DISCONNECT_REQUESTED; } } // Identify our server and chained proxy String serverHostAndPort = identifyHostAndPort(httpRequest); LOG.debug("Ensuring that hostAndPort are available in {}", httpRequest.getUri()); if (serverHostAndPort == null || StringUtils.isBlank(serverHostAndPort)) { LOG.warn("No host and port found in {}", httpRequest.getUri()); boolean keepAlive = writeBadGateway(httpRequest); if (keepAlive) { return AWAITING_INITIAL; } else { return DISCONNECT_REQUESTED; } } LOG.debug("Finding ProxyToServerConnection for: {}", serverHostAndPort); currentServerConnection = isMitming() || isTunneling() ? this.currentServerConnection : this.serverConnectionsByHostAndPort.get(serverHostAndPort); boolean newConnectionRequired = false; if (ProxyUtils.isCONNECT(httpRequest)) { LOG.debug( "Not reusing existing ProxyToServerConnection because request is a CONNECT for: {}", serverHostAndPort); newConnectionRequired = true; } else if (currentServerConnection == null) { LOG.debug("Didn't find existing ProxyToServerConnection for: {}", serverHostAndPort); newConnectionRequired = true; } if (newConnectionRequired) { try { currentServerConnection = ProxyToServerConnection.create( proxyServer, this, serverHostAndPort, currentFilters, httpRequest, globalTrafficShapingHandler); if (currentServerConnection == null) { LOG.debug("Unable to create server connection, probably no chained proxies available"); boolean keepAlive = writeBadGateway(httpRequest); resumeReading(); if (keepAlive) { return AWAITING_INITIAL; } else { return DISCONNECT_REQUESTED; } } // Remember the connection for later serverConnectionsByHostAndPort.put(serverHostAndPort, currentServerConnection); } catch (UnknownHostException uhe) { LOG.info("Bad Host {}", httpRequest.getUri()); boolean keepAlive = writeBadGateway(httpRequest); resumeReading(); if (keepAlive) { return AWAITING_INITIAL; } else { return DISCONNECT_REQUESTED; } } } else { LOG.debug("Reusing existing server connection: {}", currentServerConnection); numberOfReusedServerConnections.incrementAndGet(); } modifyRequestHeadersToReflectProxying(httpRequest); HttpResponse proxyToServerFilterResponse = currentFilters.proxyToServerRequest(httpRequest); if (proxyToServerFilterResponse != null) { LOG.debug("Responding to client with short-circuit response from filter: {}", proxyToServerFilterResponse); boolean keepAlive = respondWithShortCircuitResponse(proxyToServerFilterResponse); if (keepAlive) { return AWAITING_INITIAL; } else { return DISCONNECT_REQUESTED; } } LOG.debug("Writing request to ProxyToServerConnection"); currentServerConnection.write(httpRequest, currentFilters); // Figure out our next state if (ProxyUtils.isCONNECT(httpRequest)) { return NEGOTIATING_CONNECT; } else if (ProxyUtils.isChunked(httpRequest)) { return AWAITING_CHUNK; } else { return AWAITING_INITIAL; } } /** * Returns true if the specified request is a request to an origin server, rather than to a proxy server. If this * request is being MITM'd, this method always returns false. The format of requests to a proxy server are defined * in RFC 7230, section 5.3.2 (all other requests are considered requests to an origin server): <pre> When making a request to a proxy, other than a CONNECT or server-wide OPTIONS request (as detailed below), a client MUST send the target URI in absolute-form as the request-target. [...] An example absolute-form of request-line would be: GET http://www.example.org/pub/WWW/TheProject.html HTTP/1.1 To allow for transition to the absolute-form for all requests in some future version of HTTP, a server MUST accept the absolute-form in requests, even though HTTP/1.1 clients will only send them in requests to proxies. </pre> * * @param httpRequest the request to evaluate * @return true if the specified request is a request to an origin server, otherwise false */ private boolean isRequestToOriginServer(HttpRequest httpRequest) { // while MITMing, all HTTPS requests are requests to the origin server, since the client does not know // the request is being MITM'd by the proxy if (httpRequest.getMethod() == HttpMethod.CONNECT || isMitming()) { return false; } // direct requests to the proxy have the path only without a scheme String uri = httpRequest.getUri(); return !HTTP_SCHEME.matcher(uri).matches(); } @Override protected void readHTTPChunk(HttpContent chunk) { currentFilters.clientToProxyRequest(chunk); currentFilters.proxyToServerRequest(chunk); currentServerConnection.write(chunk); } @Override protected void readRaw(ByteBuf buf) { currentServerConnection.write(buf); } /*************************************************************************** * Writing **************************************************************************/ /** * Send a response to the client. * * @param serverConnection * the ProxyToServerConnection that's responding * @param filters * the filters to apply to the response * @param currentHttpRequest * the HttpRequest that prompted this response * @param currentHttpResponse * the HttpResponse corresponding to this data (when doing * chunked transfers, this is the initial HttpResponse object * that came in before the other chunks) * @param httpObject * the data with which to respond */ void respond(ProxyToServerConnection serverConnection, HttpFilters filters, HttpRequest currentHttpRequest, HttpResponse currentHttpResponse, HttpObject httpObject) { // we are sending a response to the client, so we are done handling this request this.currentRequest = null; httpObject = filters.serverToProxyResponse(httpObject); if (httpObject == null) { forceDisconnect(serverConnection); return; } if (httpObject instanceof HttpResponse) { HttpResponse httpResponse = (HttpResponse) httpObject; // if this HttpResponse does not have any means of signaling the end of the message body other than closing // the connection, convert the message to a "Transfer-Encoding: chunked" HTTP response. This avoids the need // to close the client connection to indicate the end of the message. (Responses to HEAD requests "must be" empty.) if (!ProxyUtils.isHead(currentHttpRequest) && !ProxyUtils.isResponseSelfTerminating(httpResponse)) { // if this is not a FullHttpResponse, duplicate the HttpResponse from the server before sending it to // the client. this allows us to set the Transfer-Encoding to chunked without interfering with netty's // handling of the response from the server. if we modify the original HttpResponse from the server, // netty will not generate the appropriate LastHttpContent when it detects the connection closure from // the server (see HttpObjectDecoder#decodeLast). (This does not apply to FullHttpResponses, for which // netty already generates the empty final chunk when Transfer-Encoding is chunked.) if (!(httpResponse instanceof FullHttpResponse)) { HttpResponse duplicateResponse = ProxyUtils.duplicateHttpResponse(httpResponse); // set the httpObject and httpResponse to the duplicated response, to allow all other standard processing // (filtering, header modification for proxying, etc.) to be applied. httpObject = httpResponse = duplicateResponse; } HttpHeaders.setTransferEncodingChunked(httpResponse); } fixHttpVersionHeaderIfNecessary(httpResponse); modifyResponseHeadersToReflectProxying(httpResponse); } httpObject = filters.proxyToClientResponse(httpObject); if (httpObject == null) { forceDisconnect(serverConnection); return; } write(httpObject); if (ProxyUtils.isLastChunk(httpObject)) { writeEmptyBuffer(); } closeConnectionsAfterWriteIfNecessary(serverConnection, currentHttpRequest, currentHttpResponse, httpObject); } /*************************************************************************** * Connection Lifecycle **************************************************************************/ /** * Tells the Client that its HTTP CONNECT request was successful. */ ConnectionFlowStep RespondCONNECTSuccessful = new ConnectionFlowStep( this, NEGOTIATING_CONNECT) { @Override boolean shouldSuppressInitialRequest() { return true; } protected Future<?> execute() { LOG.debug("Responding with CONNECT successful"); HttpResponse response = responseFor(HttpVersion.HTTP_1_1, CONNECTION_ESTABLISHED); response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); response.headers().set("Proxy-Connection", HttpHeaders.Values.KEEP_ALIVE); ProxyUtils.addVia(response); return writeToChannel(response); }; }; /** * On connect of the client, start waiting for an initial * {@link HttpRequest}. */ @Override protected void connected() { super.connected(); become(AWAITING_INITIAL); recordClientConnected(); } @Override protected void timedOut() { boolean clientReadMoreRecentlyThanServer = currentServerConnection == null || this.lastReadTime > currentServerConnection.lastReadTime; if (clientReadMoreRecentlyThanServer) { LOG.debug("Server timed out: {}", currentServerConnection); currentFilters.serverToProxyResponseTimedOut(); writeGatewayTimeout(currentRequest); // DO NOT call super.timedOut() if the server timed out, to avoid closing the connection unnecessarily } else { super.timedOut(); } } /** * On disconnect of the client, disconnect all server connections. */ @Override protected void disconnected() { super.disconnected(); for (ProxyToServerConnection serverConnection : serverConnectionsByHostAndPort .values()) { serverConnection.disconnect(); } recordClientDisconnected(); } /** * Called when {@link ProxyToServerConnection} starts its connection flow. * * @param serverConnection */ protected void serverConnectionFlowStarted( ProxyToServerConnection serverConnection) { stopReading(); this.numberOfCurrentlyConnectingServers.incrementAndGet(); } /** * If the {@link ProxyToServerConnection} completes its connection lifecycle * successfully, this method is called to let us know about it. * * @param serverConnection * @param shouldForwardInitialRequest */ protected void serverConnectionSucceeded( ProxyToServerConnection serverConnection, boolean shouldForwardInitialRequest) { LOG.debug("Connection to server succeeded: {}", serverConnection.getRemoteAddress()); resumeReadingIfNecessary(); become(shouldForwardInitialRequest ? getCurrentState() : AWAITING_INITIAL); numberOfCurrentlyConnectedServers.incrementAndGet(); } /** * If the {@link ProxyToServerConnection} fails to complete its connection * lifecycle successfully, this method is called to let us know about it. * * <p> * After failing to connect to the server, one of two things can happen: * </p> * * <ol> * <li>If the server was a chained proxy, we fall back to connecting to the * ultimate endpoint directly.</li> * <li>If the server was the ultimate endpoint, we return a 502 Bad Gateway * to the client.</li> * </ol> * * @param serverConnection * @param lastStateBeforeFailure * @param cause * what caused the failure * * @return true if we're falling back to a another chained proxy (or direct * connection) and trying again */ protected boolean serverConnectionFailed( ProxyToServerConnection serverConnection, ConnectionState lastStateBeforeFailure, Throwable cause) { resumeReadingIfNecessary(); HttpRequest initialRequest = serverConnection.getInitialRequest(); try { if (serverConnection.connectionFailed(cause)) { LOG.info( "Failed to connect via chained proxy, falling back to next chained proxy. Last state before failure: {}", lastStateBeforeFailure, cause); return true; } else { LOG.debug( "Connection to server failed: {}. Last state before failure: {}", serverConnection.getRemoteAddress(), lastStateBeforeFailure, cause); connectionFailedUnrecoverably(initialRequest, serverConnection); return false; } } catch (UnknownHostException uhe) { connectionFailedUnrecoverably(initialRequest, serverConnection); return false; } } private void connectionFailedUnrecoverably(HttpRequest initialRequest, ProxyToServerConnection serverConnection) { // the connection to the server failed, so disconnect the server and remove the ProxyToServerConnection from the // map of open server connections serverConnection.disconnect(); this.serverConnectionsByHostAndPort.remove(serverConnection.getServerHostAndPort()); boolean keepAlive = writeBadGateway(initialRequest); if (keepAlive) { become(AWAITING_INITIAL); } else { become(DISCONNECT_REQUESTED); } } private void resumeReadingIfNecessary() { if (this.numberOfCurrentlyConnectingServers.decrementAndGet() == 0) { LOG.debug("All servers have finished attempting to connect, resuming reading from client."); resumeReading(); } } /*************************************************************************** * Other Lifecycle **************************************************************************/ /** * On disconnect of the server, track that we have one fewer connected * servers and then disconnect the client if necessary. * * @param serverConnection */ protected void serverDisconnected(ProxyToServerConnection serverConnection) { numberOfCurrentlyConnectedServers.decrementAndGet(); // for non-SSL connections, do not disconnect the client from the proxy, even if this was the last server connection. // this allows clients to continue to use the open connection to the proxy to make future requests. for SSL // connections, whether we are tunneling or MITMing, we need to disconnect the client because there is always // exactly one ClientToProxyConnection per ProxyToServerConnection, and vice versa. if (isTunneling() || isMitming()) { disconnect(); } } /** * When the ClientToProxyConnection becomes saturated, stop reading on all * associated ProxyToServerConnections. */ @Override synchronized protected void becameSaturated() { super.becameSaturated(); for (ProxyToServerConnection serverConnection : serverConnectionsByHostAndPort .values()) { synchronized (serverConnection) { if (this.isSaturated()) { serverConnection.stopReading(); } } } } /** * When the ClientToProxyConnection becomes writable, resume reading on all * associated ProxyToServerConnections. */ @Override synchronized protected void becameWritable() { super.becameWritable(); for (ProxyToServerConnection serverConnection : serverConnectionsByHostAndPort .values()) { synchronized (serverConnection) { if (!this.isSaturated()) { serverConnection.resumeReading(); } } } } /** * When a server becomes saturated, we stop reading from the client. * * @param serverConnection */ synchronized protected void serverBecameSaturated( ProxyToServerConnection serverConnection) { if (serverConnection.isSaturated()) { LOG.info("Connection to server became saturated, stopping reading"); stopReading(); } } /** * When a server becomes writeable, we check to see if all servers are * writeable and if they are, we resume reading. * * @param serverConnection */ synchronized protected void serverBecameWriteable( ProxyToServerConnection serverConnection) { boolean anyServersSaturated = false; for (ProxyToServerConnection otherServerConnection : serverConnectionsByHostAndPort .values()) { if (otherServerConnection.isSaturated()) { anyServersSaturated = true; break; } } if (!anyServersSaturated) { LOG.info("All server connections writeable, resuming reading"); resumeReading(); } } @Override protected void exceptionCaught(Throwable cause) { String message = "Caught an exception on ClientToProxyConnection"; boolean shouldWarn = cause instanceof ClosedChannelException || cause.getMessage().contains("Connection reset by peer"); if (shouldWarn) { LOG.warn(message, cause); } else { LOG.error(message, cause); } disconnect(); } /*************************************************************************** * Connection Management **************************************************************************/ /** * Initialize the {@ChannelPipeline} for the client to * proxy channel. * * @param pipeline */ private void initChannelPipeline(ChannelPipeline pipeline) { LOG.debug("Configuring ChannelPipeline"); pipeline.addLast("bytesReadMonitor", bytesReadMonitor); // We want to allow longer request lines, headers, and chunks // respectively. pipeline.addLast("decoder", new HttpRequestDecoder(8192, 8192 * 2, 8192 * 2)); pipeline.addLast("requestReadMonitor", requestReadMonitor); // Enable aggregation for filtering if necessary int numberOfBytesToBuffer = proxyServer.getFiltersSource() .getMaximumRequestBufferSizeInBytes(); if (numberOfBytesToBuffer > 0) { aggregateContentForFiltering(pipeline, numberOfBytesToBuffer); } pipeline.addLast("bytesWrittenMonitor", bytesWrittenMonitor); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("responseWrittenMonitor", responseWrittenMonitor); pipeline.addLast( "idle", new IdleStateHandler(0, 0, proxyServer .getIdleConnectionTimeout())); pipeline.addLast("handler", this); } /** * This method takes care of closing client to proxy and/or proxy to server * connections after finishing a write. */ private void closeConnectionsAfterWriteIfNecessary( ProxyToServerConnection serverConnection, HttpRequest currentHttpRequest, HttpResponse currentHttpResponse, HttpObject httpObject) { boolean closeServerConnection = shouldCloseServerConnection( currentHttpRequest, currentHttpResponse, httpObject); boolean closeClientConnection = shouldCloseClientConnection( currentHttpRequest, currentHttpResponse, httpObject); if (closeServerConnection) { LOG.debug("Closing remote connection after writing to client"); serverConnection.disconnect(); } if (closeClientConnection) { LOG.debug("Closing connection to client after writes"); disconnect(); } } private void forceDisconnect(ProxyToServerConnection serverConnection) { LOG.debug("Forcing disconnect"); serverConnection.disconnect(); disconnect(); } /** * Determine whether or not the client connection should be closed. * * @param req * @param res * @param httpObject * @return */ private boolean shouldCloseClientConnection(HttpRequest req, HttpResponse res, HttpObject httpObject) { if (ProxyUtils.isChunked(res)) { // If the response is chunked, we want to return false unless it's // the last chunk. If it is the last chunk, then we want to pass // through to the same close semantics we'd otherwise use. if (httpObject != null) { if (!ProxyUtils.isLastChunk(httpObject)) { String uri = null; if (req != null) { uri = req.getUri(); } LOG.debug("Not closing client connection on middle chunk for {}", uri); return false; } else { LOG.debug("Handling last chunk. Using normal client connection closing rules."); } } } if (!HttpHeaders.isKeepAlive(req)) { LOG.debug("Closing client connection since request is not keep alive: {}", req); // Here we simply want to close the connection because the // client itself has requested it be closed in the request. return true; } // ignore the response's keep-alive; we can keep this client connection open as long as the client allows it. LOG.debug("Not closing client connection for request: {}", req); return false; } /** * Determines if the remote connection should be closed based on the request * and response pair. If the request is HTTP 1.0 with no keep-alive header, * for example, the connection should be closed. * * This in part determines if we should close the connection. Here's the * relevant section of RFC 2616: * * "HTTP/1.1 defines the "close" connection option for the sender to signal * that the connection will be closed after completion of the response. For * example, * * Connection: close * * in either the request or the response header fields indicates that the * connection SHOULD NOT be considered `persistent' (section 8.1) after the * current request/response is complete." * * @param req * The request. * @param res * The response. * @param msg * The message. * @return Returns true if the connection should close. */ private boolean shouldCloseServerConnection(HttpRequest req, HttpResponse res, HttpObject msg) { if (ProxyUtils.isChunked(res)) { // If the response is chunked, we want to return false unless it's // the last chunk. If it is the last chunk, then we want to pass // through to the same close semantics we'd otherwise use. if (msg != null) { if (!ProxyUtils.isLastChunk(msg)) { String uri = null; if (req != null) { uri = req.getUri(); } LOG.debug("Not closing server connection on middle chunk for {}", uri); return false; } else { LOG.debug("Handling last chunk. Using normal server connection closing rules."); } } } // ignore the request's keep-alive; we can keep this server connection open as long as the server allows it. if (!HttpHeaders.isKeepAlive(res)) { LOG.debug("Closing server connection since response is not keep alive: {}", res); // In this case, we want to honor the Connection: close header // from the remote server and close that connection. We don't // necessarily want to close the connection to the client, however // as it's possible it has other connections open. return true; } LOG.debug("Not closing server connection for response: {}", res); return false; } /*************************************************************************** * Authentication **************************************************************************/ /** * <p> * Checks whether the given HttpRequest requires authentication. * </p> * * <p> * If the request contains credentials, these are checked. * </p> * * <p> * If authentication is still required, either because no credentials were * provided or the credentials were wrong, this writes a 407 response to the * client. * </p> * * @param request * @return */ private boolean authenticationRequired(HttpRequest request) { if (authenticated.get()) { return false; } final ProxyAuthenticator authenticator = proxyServer .getProxyAuthenticator(); if (authenticator == null) return false; if (!request.headers().contains(HttpHeaders.Names.PROXY_AUTHORIZATION)) { writeAuthenticationRequired(); return true; } List<String> values = request.headers().getAll( HttpHeaders.Names.PROXY_AUTHORIZATION); String fullValue = values.iterator().next(); String value = StringUtils.substringAfter(fullValue, "Basic ") .trim(); byte[] decodedValue = Base64.decodeBase64(value); try { String decodedString = new String(decodedValue, "UTF-8"); String userName = StringUtils.substringBefore(decodedString, ":"); String password = StringUtils.substringAfter(decodedString, ":"); if (!authenticator.authenticate(userName, password)) { writeAuthenticationRequired(); return true; } } catch (UnsupportedEncodingException e) { LOG.error("Could not decode?", e); } LOG.info("Got proxy authorization!"); // We need to remove the header before sending the request on. String authentication = request.headers().get( HttpHeaders.Names.PROXY_AUTHORIZATION); LOG.info(authentication); request.headers().remove(HttpHeaders.Names.PROXY_AUTHORIZATION); authenticated.set(true); return false; } private void writeAuthenticationRequired() { String body = "<!DOCTYPE HTML \"-//IETF//DTD HTML 2.0//EN\">\n" + "<html><head>\n" + "<title>407 Proxy Authentication Required</title>\n" + "</head><body>\n" + "<h1>Proxy Authentication Required</h1>\n" + "<p>This server could not verify that you\n" + "are authorized to access the document\n" + "requested. Either you supplied the wrong\n" + "credentials (e.g., bad password), or your\n" + "browser doesn't understand how to supply\n" + "the credentials required.</p>\n" + "</body></html>\n"; DefaultFullHttpResponse response = responseFor(HttpVersion.HTTP_1_1, HttpResponseStatus.PROXY_AUTHENTICATION_REQUIRED, body); HttpHeaders.setDate(response, new Date()); response.headers().set("Proxy-Authenticate", "Basic realm=\"Restricted Files\""); write(response); } /*************************************************************************** * Request/Response Rewriting **************************************************************************/ /** * Copy the given {@link HttpRequest} verbatim. * * @param original * @return */ private HttpRequest copy(HttpRequest original) { if (original instanceof DefaultFullHttpRequest) { ByteBuf content = ((DefaultFullHttpRequest) original).content(); return new DefaultFullHttpRequest(original.getProtocolVersion(), original.getMethod(), original.getUri(), content); } else { return new DefaultHttpRequest(original.getProtocolVersion(), original.getMethod(), original.getUri()); } } /** * Chunked encoding is an HTTP 1.1 feature, but sometimes we get a chunked * response that reports its HTTP version as 1.0. In this case, we change it * to 1.1. * * @param httpResponse */ private void fixHttpVersionHeaderIfNecessary(HttpResponse httpResponse) { String te = httpResponse.headers().get( HttpHeaders.Names.TRANSFER_ENCODING); if (StringUtils.isNotBlank(te) && te.equalsIgnoreCase(HttpHeaders.Values.CHUNKED)) { if (httpResponse.getProtocolVersion() != HttpVersion.HTTP_1_1) { LOG.debug("Fixing HTTP version."); httpResponse.setProtocolVersion(HttpVersion.HTTP_1_1); } } } /** * If and only if our proxy is not running in transparent mode, modify the * request headers to reflect that it was proxied. * * @param httpRequest */ private void modifyRequestHeadersToReflectProxying(HttpRequest httpRequest) { if (!currentServerConnection.hasUpstreamChainedProxy()) { LOG.debug("Modifying request for proxy chaining"); // Strip host from uri String uri = httpRequest.getUri(); String adjustedUri = ProxyUtils.stripHost(uri); LOG.debug("Stripped host from uri: {} yielding: {}", uri, adjustedUri); httpRequest.setUri(adjustedUri); } if (!proxyServer.isTransparent()) { LOG.debug("Modifying request headers for proxying"); HttpHeaders headers = httpRequest.headers(); removeSDCHEncoding(headers); switchProxyConnectionHeader(headers); stripConnectionTokens(headers); stripHopByHopHeaders(headers); ProxyUtils.addVia(httpRequest); } } /** * If and only if our proxy is not running in transparent mode, modify the * response headers to reflect that it was proxied. * * @param httpResponse * @return */ private void modifyResponseHeadersToReflectProxying( HttpResponse httpResponse) { if (!proxyServer.isTransparent()) { HttpHeaders headers = httpResponse.headers(); stripConnectionTokens(headers); stripHopByHopHeaders(headers); ProxyUtils.addVia(httpResponse); /* * RFC2616 Section 14.18 * * A received message that does not have a Date header field MUST be * assigned one by the recipient if the message will be cached by * that recipient or gatewayed via a protocol which requires a Date. */ if (!headers.contains(HttpHeaders.Names.DATE)) { HttpHeaders.setDate(httpResponse, new Date()); } } } /** * Remove sdch from encodings we accept since we can't decode it. * * @param headers * The headers to modify */ private void removeSDCHEncoding(HttpHeaders headers) { String ae = headers.get(HttpHeaders.Names.ACCEPT_ENCODING); if (StringUtils.isNotBlank(ae)) { // String noSdch = ae.replace(",sdch", "").replace("sdch", ""); headers.set(HttpHeaders.Names.ACCEPT_ENCODING, noSdch); LOG.debug("Removed sdch and inserted: {}", noSdch); } } /** * Switch the de-facto standard "Proxy-Connection" header to "Connection" * when we pass it along to the remote host. This is largely undocumented * but seems to be what most browsers and servers expect. * * @param headers * The headers to modify */ private void switchProxyConnectionHeader(HttpHeaders headers) { String proxyConnectionKey = "Proxy-Connection"; if (headers.contains(proxyConnectionKey)) { String header = headers.get(proxyConnectionKey); headers.remove(proxyConnectionKey); headers.set(HttpHeaders.Names.CONNECTION, header); } } /** * RFC2616 Section 14.10 * * HTTP/1.1 proxies MUST parse the Connection header field before a message * is forwarded and, for each connection-token in this field, remove any * header field(s) from the message with the same name as the * connection-token. * * @param headers * The headers to modify */ private void stripConnectionTokens(HttpHeaders headers) { if (headers.contains(HttpHeaders.Names.CONNECTION)) { for (String headerValue : headers.getAll(HttpHeaders.Names.CONNECTION)) { for (String connectionToken : ProxyUtils.splitCommaSeparatedHeaderValues(headerValue)) { // do not strip out the Transfer-Encoding header if it is specified in the Connection header, since LittleProxy does not // normally modify the Transfer-Encoding of the message. if (!LOWERCASE_TRANSFER_ENCODING_HEADER.equals(connectionToken.toLowerCase(Locale.US))) { headers.remove(connectionToken); } } } } } /** * Removes all headers that should not be forwarded. See RFC 2616 13.5.1 * End-to-end and Hop-by-hop Headers. * * @param headers * The headers to modify */ private void stripHopByHopHeaders(HttpHeaders headers) { Set<String> headerNames = headers.names(); for (String headerName : headerNames) { if (ProxyUtils.shouldRemoveHopByHopHeader(headerName)) { headers.remove(headerName); } } } /*************************************************************************** * Miscellaneous **************************************************************************/ /** * Tells the client that something went wrong trying to proxy its request. If the Bad Gateway is a response to * an HTTP HEAD request, the response will contain no body, but the Content-Length header will be set to the * value it would have been if this 502 Bad Gateway were in response to a GET. * * @param httpRequest the HttpRequest that is resulting in the Bad Gateway response * @return true if the connection will be kept open, or false if it will be disconnected */ private boolean writeBadGateway(HttpRequest httpRequest) { String body = "Bad Gateway: " + httpRequest.getUri(); DefaultFullHttpResponse response = responseFor(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_GATEWAY, body); if (ProxyUtils.isHEAD(httpRequest)) { // don't allow any body content in response to a HEAD request response.content().clear(); } return respondWithShortCircuitResponse(response); } /** * Tells the client that the request was malformed or erroneous. If the Bad Request is a response to * an HTTP HEAD request, the response will contain no body, but the Content-Length header will be set to the * value it would have been if this Bad Request were in response to a GET. * * @return true if the connection will be kept open, or false if it will be disconnected */ private boolean writeBadRequest(HttpRequest httpRequest) { String body = "Bad Request to URI: " + httpRequest.getUri(); DefaultFullHttpResponse response = responseFor(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST, body); if (ProxyUtils.isHEAD(httpRequest)) { // don't allow any body content in response to a HEAD request response.content().clear(); } return respondWithShortCircuitResponse(response); } /** * Tells the client that the connection to the server, or possibly to some intermediary service (such as DNS), timed out. * If the Gateway Timeout is a response to an HTTP HEAD request, the response will contain no body, but the * Content-Length header will be set to the value it would have been if this 504 Gateway Timeout were in response to a GET. * * @param httpRequest the HttpRequest that is resulting in the Gateway Timeout response * @return true if the connection will be kept open, or false if it will be disconnected */ private boolean writeGatewayTimeout(HttpRequest httpRequest) { String body = "Gateway Timeout"; DefaultFullHttpResponse response = responseFor(HttpVersion.HTTP_1_1, HttpResponseStatus.GATEWAY_TIMEOUT, body); if (httpRequest != null && ProxyUtils.isHEAD(httpRequest)) { // don't allow any body content in response to a HEAD request response.content().clear(); } return respondWithShortCircuitResponse(response); } /** * Responds to the client with the specified "short-circuit" response. The response will be sent through the * {@link HttpFilters#proxyToClientResponse(HttpObject)} filter method before writing it to the client. The client * will not be disconnected, unless the response includes a "Connection: close" header, or the filter returns * a null HttpResponse (in which case no response will be written to the client and the connection will be * disconnected immediately). If the response is not a Bad Gateway or Gateway Timeout response, the response's headers * will be modified to reflect proxying, including adding a Via header, Date header, etc. * * @param httpResponse the response to return to the client * @return true if the connection will be kept open, or false if it will be disconnected. */ private boolean respondWithShortCircuitResponse(HttpResponse httpResponse) { // we are sending a response to the client, so we are done handling this request this.currentRequest = null; HttpResponse filteredResponse = (HttpResponse) currentFilters.proxyToClientResponse(httpResponse); if (filteredResponse == null) { disconnect(); return false; } // allow short-circuit messages to close the connection. normally the Connection header would be stripped when modifying // the message for proxying, so save the keep-alive status before the modifications are made. boolean isKeepAlive = HttpHeaders.isKeepAlive(httpResponse); // if the response is not a Bad Gateway or Gateway Timeout, modify the headers "as if" the short-circuit response were proxied int statusCode = httpResponse.getStatus().code(); if (statusCode != HttpResponseStatus.BAD_GATEWAY.code() && statusCode != HttpResponseStatus.GATEWAY_TIMEOUT.code()) { modifyResponseHeadersToReflectProxying(httpResponse); } // restore the keep alive status, if it was overwritten when modifying headers for proxying HttpHeaders.setKeepAlive(httpResponse, isKeepAlive); write(httpResponse); if (ProxyUtils.isLastChunk(httpResponse)) { writeEmptyBuffer(); } if (!HttpHeaders.isKeepAlive(httpResponse)) { disconnect(); return false; } return true; } /** * Factory for {@link DefaultFullHttpResponse}s. * * @param httpVersion * @param status * @param body * @return */ private DefaultFullHttpResponse responseFor(HttpVersion httpVersion, HttpResponseStatus status, String body) { byte[] bytes = body.getBytes(Charset.forName("UTF-8")); ByteBuf content = Unpooled.copiedBuffer(bytes); return responseFor(httpVersion, status, content, bytes.length); } /** * Factory for {@link DefaultFullHttpResponse}s. * * @param httpVersion * @param status * @param body * @param contentLength * @return */ private DefaultFullHttpResponse responseFor(HttpVersion httpVersion, HttpResponseStatus status, ByteBuf body, int contentLength) { DefaultFullHttpResponse response = body != null ? new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, status, body) : new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status); if (body != null) { response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, contentLength); response.headers().set("Content-Type", "text/html; charset=UTF-8"); } return response; } /** * Factory for {@link DefaultFullHttpResponse}s. * * @param httpVersion * @param status * @return */ private DefaultFullHttpResponse responseFor(HttpVersion httpVersion, HttpResponseStatus status) { return responseFor(httpVersion, status, (ByteBuf) null, 0); } /** * Identify the host and port for a request. * * @param httpRequest * @return */ private String identifyHostAndPort(HttpRequest httpRequest) { String hostAndPort = ProxyUtils.parseHostAndPort(httpRequest); if (StringUtils.isBlank(hostAndPort)) { List<String> hosts = httpRequest.headers().getAll( HttpHeaders.Names.HOST); if (hosts != null && !hosts.isEmpty()) { hostAndPort = hosts.get(0); } } return hostAndPort; } /** * Write an empty buffer at the end of a chunked transfer. We need to do * this to handle the way Netty creates HttpChunks from responses that * aren't in fact chunked from the remote server using Transfer-Encoding: * chunked. Netty turns these into pseudo-chunked responses in cases where * the response would otherwise fill up too much memory or where the length * of the response body is unknown. This is handy because it means we can * start streaming response bodies back to the client without reading the * entire response. The problem is that in these pseudo-cases the last chunk * is encoded to null, and this thwarts normal ChannelFutures from * propagating operationComplete events on writes to appropriate channel * listeners. We work around this by writing an empty buffer in those cases * and using the empty buffer's future instead to handle any operations we * need to when responses are fully written back to clients. */ private void writeEmptyBuffer() { write(Unpooled.EMPTY_BUFFER); } public boolean isMitming() { return mitming; } protected void setMitming(boolean isMitming) { this.mitming = isMitming; } /*************************************************************************** * Activity Tracking/Statistics * * We track statistics on bytes, requests and responses by adding handlers * at the appropriate parts of the pipeline (see initChannelPipeline()). **************************************************************************/ private final BytesReadMonitor bytesReadMonitor = new BytesReadMonitor() { @Override protected void bytesRead(int numberOfBytes) { FlowContext flowContext = flowContext(); for (ActivityTracker tracker : proxyServer .getActivityTrackers()) { tracker.bytesReceivedFromClient(flowContext, numberOfBytes); } } }; private RequestReadMonitor requestReadMonitor = new RequestReadMonitor() { @Override protected void requestRead(HttpRequest httpRequest) { FlowContext flowContext = flowContext(); for (ActivityTracker tracker : proxyServer .getActivityTrackers()) { tracker.requestReceivedFromClient(flowContext, httpRequest); } } }; private BytesWrittenMonitor bytesWrittenMonitor = new BytesWrittenMonitor() { @Override protected void bytesWritten(int numberOfBytes) { FlowContext flowContext = flowContext(); for (ActivityTracker tracker : proxyServer .getActivityTrackers()) { tracker.bytesSentToClient(flowContext, numberOfBytes); } } }; private ResponseWrittenMonitor responseWrittenMonitor = new ResponseWrittenMonitor() { @Override protected void responseWritten(HttpResponse httpResponse) { FlowContext flowContext = flowContext(); for (ActivityTracker tracker : proxyServer .getActivityTrackers()) { tracker.responseSentToClient(flowContext, httpResponse); } } }; private void recordClientConnected() { try { InetSocketAddress clientAddress = getClientAddress(); for (ActivityTracker tracker : proxyServer .getActivityTrackers()) { tracker.clientConnected(clientAddress); } } catch (Exception e) { LOG.error("Unable to recordClientConnected", e); } } private void recordClientSSLHandshakeSucceeded() { try { InetSocketAddress clientAddress = getClientAddress(); for (ActivityTracker tracker : proxyServer .getActivityTrackers()) { tracker.clientSSLHandshakeSucceeded( clientAddress, clientSslSession); } } catch (Exception e) { LOG.error("Unable to recorClientSSLHandshakeSucceeded", e); } } private void recordClientDisconnected() { try { InetSocketAddress clientAddress = getClientAddress(); for (ActivityTracker tracker : proxyServer .getActivityTrackers()) { tracker.clientDisconnected( clientAddress, clientSslSession); } } catch (Exception e) { LOG.error("Unable to recordClientDisconnected", e); } } public InetSocketAddress getClientAddress() { if (channel == null) { return null; } return (InetSocketAddress) channel.remoteAddress(); } private FlowContext flowContext() { if (currentServerConnection != null) { return new FullFlowContext(this, currentServerConnection); } else { return new FlowContext(this); } } }
src/main/java/org/littleshoot/proxy/impl/ClientToProxyConnection.java
package org.littleshoot.proxy.impl; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelPipeline; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpContent; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpObject; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseEncoder; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.timeout.IdleStateHandler; import io.netty.handler.traffic.GlobalTrafficShapingHandler; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.StringUtils; import org.littleshoot.proxy.ActivityTracker; import org.littleshoot.proxy.FlowContext; import org.littleshoot.proxy.FullFlowContext; import org.littleshoot.proxy.HttpFilters; import org.littleshoot.proxy.HttpFiltersAdapter; import org.littleshoot.proxy.ProxyAuthenticator; import org.littleshoot.proxy.SslEngineSource; import javax.net.ssl.SSLSession; import java.io.UnsupportedEncodingException; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.nio.channels.ClosedChannelException; import java.nio.charset.Charset; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Pattern; import static org.littleshoot.proxy.impl.ConnectionState.AWAITING_CHUNK; import static org.littleshoot.proxy.impl.ConnectionState.AWAITING_INITIAL; import static org.littleshoot.proxy.impl.ConnectionState.AWAITING_PROXY_AUTHENTICATION; import static org.littleshoot.proxy.impl.ConnectionState.DISCONNECT_REQUESTED; import static org.littleshoot.proxy.impl.ConnectionState.NEGOTIATING_CONNECT; /** * <p> * Represents a connection from a client to our proxy. Each * ClientToProxyConnection can have multiple {@link ProxyToServerConnection}s, * at most one per outbound host:port. * </p> * * <p> * Once a ProxyToServerConnection has been created for a given server, it is * continually reused. The ProxyToServerConnection goes through its own * lifecycle of connects and disconnects, with different underlying * {@link Channel}s, but only a single ProxyToServerConnection object is used * per server. The one exception to this is CONNECT tunneling - if a connection * has been used for CONNECT tunneling, that connection will never be reused. * </p> * * <p> * As the ProxyToServerConnections receive responses from their servers, they * feed these back to the client by calling * {@link #respond(ProxyToServerConnection, HttpFilters, HttpRequest, HttpResponse, HttpObject)} * . * </p> */ public class ClientToProxyConnection extends ProxyConnection<HttpRequest> { private static final HttpResponseStatus CONNECTION_ESTABLISHED = new HttpResponseStatus( 200, "HTTP/1.1 200 Connection established"); /** * Used for case-insensitive comparisons when parsing Connection header values. */ private static final String LOWERCASE_TRANSFER_ENCODING_HEADER = HttpHeaders.Names.TRANSFER_ENCODING.toLowerCase(Locale.US); /** * Used for case-insensitive comparisons when checking direct proxy request. */ private static final Pattern HTTP_SCHEME = Pattern.compile("^http://.*", Pattern.CASE_INSENSITIVE); /** * Keep track of all ProxyToServerConnections by host+port. */ private final Map<String, ProxyToServerConnection> serverConnectionsByHostAndPort = new ConcurrentHashMap<String, ProxyToServerConnection>(); /** * Keep track of how many servers are currently in the process of * connecting. */ private final AtomicInteger numberOfCurrentlyConnectingServers = new AtomicInteger( 0); /** * Keep track of how many servers are currently connected. */ private final AtomicInteger numberOfCurrentlyConnectedServers = new AtomicInteger( 0); /** * Keep track of how many times we were able to reuse a connection. */ private final AtomicInteger numberOfReusedServerConnections = new AtomicInteger( 0); /** * This is the current server connection that we're using while transferring * chunked data. */ private volatile ProxyToServerConnection currentServerConnection; /** * The current filters to apply to incoming requests/chunks. */ private volatile HttpFilters currentFilters = new HttpFiltersAdapter(null); private volatile SSLSession clientSslSession; /** * Tracks whether or not this ClientToProxyConnection is current doing MITM. */ private volatile boolean mitming = false; private AtomicBoolean authenticated = new AtomicBoolean(); private final GlobalTrafficShapingHandler globalTrafficShapingHandler; /** * The current HTTP request that this connection is currently servicing. */ private volatile HttpRequest currentRequest; ClientToProxyConnection( final DefaultHttpProxyServer proxyServer, SslEngineSource sslEngineSource, boolean authenticateClients, ChannelPipeline pipeline, GlobalTrafficShapingHandler globalTrafficShapingHandler) { super(AWAITING_INITIAL, proxyServer, false); initChannelPipeline(pipeline); if (sslEngineSource != null) { LOG.debug("Enabling encryption of traffic from client to proxy"); encrypt(pipeline, sslEngineSource.newSslEngine(), authenticateClients) .addListener( new GenericFutureListener<Future<? super Channel>>() { @Override public void operationComplete( Future<? super Channel> future) throws Exception { if (future.isSuccess()) { clientSslSession = sslEngine .getSession(); recordClientSSLHandshakeSucceeded(); } } }); } this.globalTrafficShapingHandler = globalTrafficShapingHandler; LOG.debug("Created ClientToProxyConnection"); } /*************************************************************************** * Reading **************************************************************************/ @Override protected ConnectionState readHTTPInitial(HttpRequest httpRequest) { LOG.debug("Got request: {}", httpRequest); boolean authenticationRequired = authenticationRequired(httpRequest); if (authenticationRequired) { LOG.debug("Not authenticated!!"); return AWAITING_PROXY_AUTHENTICATION; } else { return doReadHTTPInitial(httpRequest); } } /** * <p> * Reads an {@link HttpRequest}. * </p> * * <p> * If we don't yet have a {@link ProxyToServerConnection} for the desired * server, this takes care of creating it. * </p> * * <p> * Note - the "server" could be a chained proxy, not the final endpoint for * the request. * </p> * * @param httpRequest * @return */ private ConnectionState doReadHTTPInitial(HttpRequest httpRequest) { // Make a copy of the original request this.currentRequest = copy(httpRequest); // Set up our filters based on the original request. If the HttpFiltersSource returns null (meaning the request/response // should not be filtered), fall back to the default no-op filter source. HttpFilters filterInstance = proxyServer.getFiltersSource().filterRequest(currentRequest, ctx); if (filterInstance != null) { currentFilters = filterInstance; } // Send the request through the clientToProxyRequest filter, and respond with the short-circuit response if required HttpResponse clientToProxyFilterResponse = currentFilters.clientToProxyRequest(httpRequest); if (clientToProxyFilterResponse != null) { LOG.debug("Responding to client with short-circuit response from filter: {}", clientToProxyFilterResponse); boolean keepAlive = respondWithShortCircuitResponse(clientToProxyFilterResponse); if (keepAlive) { return AWAITING_INITIAL; } else { return DISCONNECT_REQUESTED; } } // short-circuit requests that treat the proxy as the "origin" server, to avoid infinite loops if (isRequestToOriginServer(httpRequest)) { boolean keepAlive = writeBadRequest(httpRequest); if (keepAlive) { return AWAITING_INITIAL; } else { return DISCONNECT_REQUESTED; } } // Identify our server and chained proxy String serverHostAndPort = identifyHostAndPort(httpRequest); LOG.debug("Ensuring that hostAndPort are available in {}", httpRequest.getUri()); if (serverHostAndPort == null || StringUtils.isBlank(serverHostAndPort)) { LOG.warn("No host and port found in {}", httpRequest.getUri()); boolean keepAlive = writeBadGateway(httpRequest); if (keepAlive) { return AWAITING_INITIAL; } else { return DISCONNECT_REQUESTED; } } LOG.debug("Finding ProxyToServerConnection for: {}", serverHostAndPort); currentServerConnection = isMitming() || isTunneling() ? this.currentServerConnection : this.serverConnectionsByHostAndPort.get(serverHostAndPort); boolean newConnectionRequired = false; if (ProxyUtils.isCONNECT(httpRequest)) { LOG.debug( "Not reusing existing ProxyToServerConnection because request is a CONNECT for: {}", serverHostAndPort); newConnectionRequired = true; } else if (currentServerConnection == null) { LOG.debug("Didn't find existing ProxyToServerConnection for: {}", serverHostAndPort); newConnectionRequired = true; } if (newConnectionRequired) { try { currentServerConnection = ProxyToServerConnection.create( proxyServer, this, serverHostAndPort, currentFilters, httpRequest, globalTrafficShapingHandler); if (currentServerConnection == null) { LOG.debug("Unable to create server connection, probably no chained proxies available"); boolean keepAlive = writeBadGateway(httpRequest); resumeReading(); if (keepAlive) { return AWAITING_INITIAL; } else { return DISCONNECT_REQUESTED; } } // Remember the connection for later serverConnectionsByHostAndPort.put(serverHostAndPort, currentServerConnection); } catch (UnknownHostException uhe) { LOG.info("Bad Host {}", httpRequest.getUri()); boolean keepAlive = writeBadGateway(httpRequest); resumeReading(); if (keepAlive) { return AWAITING_INITIAL; } else { return DISCONNECT_REQUESTED; } } } else { LOG.debug("Reusing existing server connection: {}", currentServerConnection); numberOfReusedServerConnections.incrementAndGet(); } modifyRequestHeadersToReflectProxying(httpRequest); HttpResponse proxyToServerFilterResponse = currentFilters.proxyToServerRequest(httpRequest); if (proxyToServerFilterResponse != null) { LOG.debug("Responding to client with short-circuit response from filter: {}", proxyToServerFilterResponse); boolean keepAlive = respondWithShortCircuitResponse(proxyToServerFilterResponse); if (keepAlive) { return AWAITING_INITIAL; } else { return DISCONNECT_REQUESTED; } } LOG.debug("Writing request to ProxyToServerConnection"); currentServerConnection.write(httpRequest, currentFilters); // Figure out our next state if (ProxyUtils.isCONNECT(httpRequest)) { return NEGOTIATING_CONNECT; } else if (ProxyUtils.isChunked(httpRequest)) { return AWAITING_CHUNK; } else { return AWAITING_INITIAL; } } /** * Returns true if the specified request is a request to an origin server, rather than to a proxy server. If this * request is being MITM'd, this method always returns false. The format of requests to a proxy server are defined * in RFC 7230, section 5.3.2 (all other requests are considered requests to an origin server): <pre> When making a request to a proxy, other than a CONNECT or server-wide OPTIONS request (as detailed below), a client MUST send the target URI in absolute-form as the request-target. [...] An example absolute-form of request-line would be: GET http://www.example.org/pub/WWW/TheProject.html HTTP/1.1 To allow for transition to the absolute-form for all requests in some future version of HTTP, a server MUST accept the absolute-form in requests, even though HTTP/1.1 clients will only send them in requests to proxies. </pre> * * @param httpRequest the request to evaluate * @return true if the specified request is a request to an origin server, otherwise false */ private boolean isRequestToOriginServer(HttpRequest httpRequest) { // while MITMing, all HTTPS requests are requests to the origin server, since the client does not know // the request is being MITM'd by the proxy if (httpRequest.getMethod() == HttpMethod.CONNECT || isMitming()) { return false; } // direct requests to the proxy have the path only without a scheme String uri = httpRequest.getUri(); return !HTTP_SCHEME.matcher(uri).matches(); } @Override protected void readHTTPChunk(HttpContent chunk) { currentFilters.clientToProxyRequest(chunk); currentFilters.proxyToServerRequest(chunk); currentServerConnection.write(chunk); } @Override protected void readRaw(ByteBuf buf) { currentServerConnection.write(buf); } /*************************************************************************** * Writing **************************************************************************/ /** * Send a response to the client. * * @param serverConnection * the ProxyToServerConnection that's responding * @param filters * the filters to apply to the response * @param currentHttpRequest * the HttpRequest that prompted this response * @param currentHttpResponse * the HttpResponse corresponding to this data (when doing * chunked transfers, this is the initial HttpResponse object * that came in before the other chunks) * @param httpObject * the data with which to respond */ void respond(ProxyToServerConnection serverConnection, HttpFilters filters, HttpRequest currentHttpRequest, HttpResponse currentHttpResponse, HttpObject httpObject) { // we are sending a response to the client, so we are done handling this request this.currentRequest = null; httpObject = filters.serverToProxyResponse(httpObject); if (httpObject == null) { forceDisconnect(serverConnection); return; } if (httpObject instanceof HttpResponse) { HttpResponse httpResponse = (HttpResponse) httpObject; // if this HttpResponse does not have any means of signaling the end of the message body other than closing // the connection, convert the message to a "Transfer-Encoding: chunked" HTTP response. This avoids the need // to close the client connection to indicate the end of the message. (Responses to HEAD requests "must be" empty.) if (!ProxyUtils.isHead(currentHttpRequest) && !ProxyUtils.isResponseSelfTerminating(httpResponse)) { // if this is not a FullHttpResponse, duplicate the HttpResponse from the server before sending it to // the client. this allows us to set the Transfer-Encoding to chunked without interfering with netty's // handling of the response from the server. if we modify the original HttpResponse from the server, // netty will not generate the appropriate LastHttpContent when it detects the connection closure from // the server (see HttpObjectDecoder#decodeLast). (This does not apply to FullHttpResponses, for which // netty already generates the empty final chunk when Transfer-Encoding is chunked.) if (!(httpResponse instanceof FullHttpResponse)) { HttpResponse duplicateResponse = ProxyUtils.duplicateHttpResponse(httpResponse); // set the httpObject and httpResponse to the duplicated response, to allow all other standard processing // (filtering, header modification for proxying, etc.) to be applied. httpObject = httpResponse = duplicateResponse; } HttpHeaders.setTransferEncodingChunked(httpResponse); } fixHttpVersionHeaderIfNecessary(httpResponse); modifyResponseHeadersToReflectProxying(httpResponse); } httpObject = filters.proxyToClientResponse(httpObject); if (httpObject == null) { forceDisconnect(serverConnection); return; } write(httpObject); if (ProxyUtils.isLastChunk(httpObject)) { writeEmptyBuffer(); } closeConnectionsAfterWriteIfNecessary(serverConnection, currentHttpRequest, currentHttpResponse, httpObject); } /*************************************************************************** * Connection Lifecycle **************************************************************************/ /** * Tells the Client that its HTTP CONNECT request was successful. */ ConnectionFlowStep RespondCONNECTSuccessful = new ConnectionFlowStep( this, NEGOTIATING_CONNECT) { @Override boolean shouldSuppressInitialRequest() { return true; } protected Future<?> execute() { LOG.debug("Responding with CONNECT successful"); HttpResponse response = responseFor(HttpVersion.HTTP_1_1, CONNECTION_ESTABLISHED); response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE); response.headers().set("Proxy-Connection", HttpHeaders.Values.KEEP_ALIVE); ProxyUtils.addVia(response); return writeToChannel(response); }; }; /** * On connect of the client, start waiting for an initial * {@link HttpRequest}. */ @Override protected void connected() { super.connected(); become(AWAITING_INITIAL); recordClientConnected(); } @Override protected void timedOut() { boolean clientReadMoreRecentlyThanServer = currentServerConnection == null || this.lastReadTime > currentServerConnection.lastReadTime; if (clientReadMoreRecentlyThanServer) { LOG.debug("Server timed out: {}", currentServerConnection); currentFilters.serverToProxyResponseTimedOut(); writeGatewayTimeout(currentRequest); // DO NOT call super.timedOut() if the server timed out, to avoid closing the connection unnecessarily } else { super.timedOut(); } } /** * On disconnect of the client, disconnect all server connections. */ @Override protected void disconnected() { super.disconnected(); for (ProxyToServerConnection serverConnection : serverConnectionsByHostAndPort .values()) { serverConnection.disconnect(); } recordClientDisconnected(); } /** * Called when {@link ProxyToServerConnection} starts its connection flow. * * @param serverConnection */ protected void serverConnectionFlowStarted( ProxyToServerConnection serverConnection) { stopReading(); this.numberOfCurrentlyConnectingServers.incrementAndGet(); } /** * If the {@link ProxyToServerConnection} completes its connection lifecycle * successfully, this method is called to let us know about it. * * @param serverConnection * @param shouldForwardInitialRequest */ protected void serverConnectionSucceeded( ProxyToServerConnection serverConnection, boolean shouldForwardInitialRequest) { LOG.debug("Connection to server succeeded: {}", serverConnection.getRemoteAddress()); resumeReadingIfNecessary(); become(shouldForwardInitialRequest ? getCurrentState() : AWAITING_INITIAL); numberOfCurrentlyConnectedServers.incrementAndGet(); } /** * If the {@link ProxyToServerConnection} fails to complete its connection * lifecycle successfully, this method is called to let us know about it. * * <p> * After failing to connect to the server, one of two things can happen: * </p> * * <ol> * <li>If the server was a chained proxy, we fall back to connecting to the * ultimate endpoint directly.</li> * <li>If the server was the ultimate endpoint, we return a 502 Bad Gateway * to the client.</li> * </ol> * * @param serverConnection * @param lastStateBeforeFailure * @param cause * what caused the failure * * @return true if we're falling back to a another chained proxy (or direct * connection) and trying again */ protected boolean serverConnectionFailed( ProxyToServerConnection serverConnection, ConnectionState lastStateBeforeFailure, Throwable cause) { resumeReadingIfNecessary(); HttpRequest initialRequest = serverConnection.getInitialRequest(); try { if (serverConnection.connectionFailed(cause)) { LOG.info( "Failed to connect via chained proxy, falling back to next chained proxy. Last state before failure: {}", lastStateBeforeFailure, cause); return true; } else { LOG.debug( "Connection to server failed: {}. Last state before failure: {}", serverConnection.getRemoteAddress(), lastStateBeforeFailure, cause); connectionFailedUnrecoverably(initialRequest, serverConnection); return false; } } catch (UnknownHostException uhe) { connectionFailedUnrecoverably(initialRequest, serverConnection); return false; } } private void connectionFailedUnrecoverably(HttpRequest initialRequest, ProxyToServerConnection serverConnection) { // the connection to the server failed, so disconnect the server and remove the ProxyToServerConnection from the // map of open server connections serverConnection.disconnect(); this.serverConnectionsByHostAndPort.remove(serverConnection.getServerHostAndPort()); boolean keepAlive = writeBadGateway(initialRequest); if (keepAlive) { become(AWAITING_INITIAL); } else { become(DISCONNECT_REQUESTED); } } private void resumeReadingIfNecessary() { if (this.numberOfCurrentlyConnectingServers.decrementAndGet() == 0) { LOG.debug("All servers have finished attempting to connect, resuming reading from client."); resumeReading(); } } /*************************************************************************** * Other Lifecycle **************************************************************************/ /** * On disconnect of the server, track that we have one fewer connected * servers and then disconnect the client if necessary. * * @param serverConnection */ protected void serverDisconnected(ProxyToServerConnection serverConnection) { numberOfCurrentlyConnectedServers.decrementAndGet(); // for non-SSL connections, do not disconnect the client from the proxy, even if this was the last server connection. // this allows clients to continue to use the open connection to the proxy to make future requests. for SSL // connections, whether we are tunneling or MITMing, we need to disconnect the client because there is always // exactly one ClientToProxyConnection per ProxyToServerConnection, and vice versa. if (isTunneling() || isMitming()) { disconnect(); } } /** * When the ClientToProxyConnection becomes saturated, stop reading on all * associated ProxyToServerConnections. */ @Override synchronized protected void becameSaturated() { super.becameSaturated(); for (ProxyToServerConnection serverConnection : serverConnectionsByHostAndPort .values()) { synchronized (serverConnection) { if (this.isSaturated()) { serverConnection.stopReading(); } } } } /** * When the ClientToProxyConnection becomes writable, resume reading on all * associated ProxyToServerConnections. */ @Override synchronized protected void becameWritable() { super.becameWritable(); for (ProxyToServerConnection serverConnection : serverConnectionsByHostAndPort .values()) { synchronized (serverConnection) { if (!this.isSaturated()) { serverConnection.resumeReading(); } } } } /** * When a server becomes saturated, we stop reading from the client. * * @param serverConnection */ synchronized protected void serverBecameSaturated( ProxyToServerConnection serverConnection) { if (serverConnection.isSaturated()) { LOG.info("Connection to server became saturated, stopping reading"); stopReading(); } } /** * When a server becomes writeable, we check to see if all servers are * writeable and if they are, we resume reading. * * @param serverConnection */ synchronized protected void serverBecameWriteable( ProxyToServerConnection serverConnection) { boolean anyServersSaturated = false; for (ProxyToServerConnection otherServerConnection : serverConnectionsByHostAndPort .values()) { if (otherServerConnection.isSaturated()) { anyServersSaturated = true; break; } } if (!anyServersSaturated) { LOG.info("All server connections writeable, resuming reading"); resumeReading(); } } @Override protected void exceptionCaught(Throwable cause) { String message = "Caught an exception on ClientToProxyConnection"; boolean shouldWarn = cause instanceof ClosedChannelException || cause.getMessage().contains("Connection reset by peer"); if (shouldWarn) { LOG.warn(message, cause); } else { LOG.error(message, cause); } disconnect(); } /*************************************************************************** * Connection Management **************************************************************************/ /** * Initialize the {@ChannelPipeline} for the client to * proxy channel. * * @param pipeline */ private void initChannelPipeline(ChannelPipeline pipeline) { LOG.debug("Configuring ChannelPipeline"); pipeline.addLast("bytesReadMonitor", bytesReadMonitor); // We want to allow longer request lines, headers, and chunks // respectively. pipeline.addLast("decoder", new HttpRequestDecoder(8192, 8192 * 2, 8192 * 2)); pipeline.addLast("requestReadMonitor", requestReadMonitor); // Enable aggregation for filtering if necessary int numberOfBytesToBuffer = proxyServer.getFiltersSource() .getMaximumRequestBufferSizeInBytes(); if (numberOfBytesToBuffer > 0) { aggregateContentForFiltering(pipeline, numberOfBytesToBuffer); } pipeline.addLast("bytesWrittenMonitor", bytesWrittenMonitor); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("responseWrittenMonitor", responseWrittenMonitor); pipeline.addLast( "idle", new IdleStateHandler(0, 0, proxyServer .getIdleConnectionTimeout())); pipeline.addLast("handler", this); } /** * This method takes care of closing client to proxy and/or proxy to server * connections after finishing a write. */ private void closeConnectionsAfterWriteIfNecessary( ProxyToServerConnection serverConnection, HttpRequest currentHttpRequest, HttpResponse currentHttpResponse, HttpObject httpObject) { boolean closeServerConnection = shouldCloseServerConnection( currentHttpRequest, currentHttpResponse, httpObject); boolean closeClientConnection = shouldCloseClientConnection( currentHttpRequest, currentHttpResponse, httpObject); if (closeServerConnection) { LOG.debug("Closing remote connection after writing to client"); serverConnection.disconnect(); } if (closeClientConnection) { LOG.debug("Closing connection to client after writes"); disconnect(); } } private void forceDisconnect(ProxyToServerConnection serverConnection) { LOG.debug("Forcing disconnect"); serverConnection.disconnect(); disconnect(); } /** * Determine whether or not the client connection should be closed. * * @param req * @param res * @param httpObject * @return */ private boolean shouldCloseClientConnection(HttpRequest req, HttpResponse res, HttpObject httpObject) { if (ProxyUtils.isChunked(res)) { // If the response is chunked, we want to return false unless it's // the last chunk. If it is the last chunk, then we want to pass // through to the same close semantics we'd otherwise use. if (httpObject != null) { if (!ProxyUtils.isLastChunk(httpObject)) { String uri = null; if (req != null) { uri = req.getUri(); } LOG.debug("Not closing client connection on middle chunk for {}", uri); return false; } else { LOG.debug("Handling last chunk. Using normal client connection closing rules."); } } } if (!HttpHeaders.isKeepAlive(req)) { LOG.debug("Closing client connection since request is not keep alive: {}", req); // Here we simply want to close the connection because the // client itself has requested it be closed in the request. return true; } // ignore the response's keep-alive; we can keep this client connection open as long as the client allows it. LOG.debug("Not closing client connection for request: {}", req); return false; } /** * Determines if the remote connection should be closed based on the request * and response pair. If the request is HTTP 1.0 with no keep-alive header, * for example, the connection should be closed. * * This in part determines if we should close the connection. Here's the * relevant section of RFC 2616: * * "HTTP/1.1 defines the "close" connection option for the sender to signal * that the connection will be closed after completion of the response. For * example, * * Connection: close * * in either the request or the response header fields indicates that the * connection SHOULD NOT be considered `persistent' (section 8.1) after the * current request/response is complete." * * @param req * The request. * @param res * The response. * @param msg * The message. * @return Returns true if the connection should close. */ private boolean shouldCloseServerConnection(HttpRequest req, HttpResponse res, HttpObject msg) { if (ProxyUtils.isChunked(res)) { // If the response is chunked, we want to return false unless it's // the last chunk. If it is the last chunk, then we want to pass // through to the same close semantics we'd otherwise use. if (msg != null) { if (!ProxyUtils.isLastChunk(msg)) { String uri = null; if (req != null) { uri = req.getUri(); } LOG.debug("Not closing server connection on middle chunk for {}", uri); return false; } else { LOG.debug("Handling last chunk. Using normal server connection closing rules."); } } } // ignore the request's keep-alive; we can keep this server connection open as long as the server allows it. if (!HttpHeaders.isKeepAlive(res)) { LOG.debug("Closing server connection since response is not keep alive: {}", res); // In this case, we want to honor the Connection: close header // from the remote server and close that connection. We don't // necessarily want to close the connection to the client, however // as it's possible it has other connections open. return true; } LOG.debug("Not closing server connection for response: {}", res); return false; } /*************************************************************************** * Authentication **************************************************************************/ /** * <p> * Checks whether the given HttpRequest requires authentication. * </p> * * <p> * If the request contains credentials, these are checked. * </p> * * <p> * If authentication is still required, either because no credentials were * provided or the credentials were wrong, this writes a 407 response to the * client. * </p> * * @param request * @return */ private boolean authenticationRequired(HttpRequest request) { if (authenticated.get()) { return false; } final ProxyAuthenticator authenticator = proxyServer .getProxyAuthenticator(); if (authenticator == null) return false; if (!request.headers().contains(HttpHeaders.Names.PROXY_AUTHORIZATION)) { writeAuthenticationRequired(); return true; } List<String> values = request.headers().getAll( HttpHeaders.Names.PROXY_AUTHORIZATION); String fullValue = values.iterator().next(); String value = StringUtils.substringAfter(fullValue, "Basic ") .trim(); byte[] decodedValue = Base64.decodeBase64(value); try { String decodedString = new String(decodedValue, "UTF-8"); String userName = StringUtils.substringBefore(decodedString, ":"); String password = StringUtils.substringAfter(decodedString, ":"); if (!authenticator.authenticate(userName, password)) { writeAuthenticationRequired(); return true; } } catch (UnsupportedEncodingException e) { LOG.error("Could not decode?", e); } LOG.info("Got proxy authorization!"); // We need to remove the header before sending the request on. String authentication = request.headers().get( HttpHeaders.Names.PROXY_AUTHORIZATION); LOG.info(authentication); request.headers().remove(HttpHeaders.Names.PROXY_AUTHORIZATION); authenticated.set(true); return false; } private void writeAuthenticationRequired() { String body = "<!DOCTYPE HTML \"-//IETF//DTD HTML 2.0//EN\">\n" + "<html><head>\n" + "<title>407 Proxy Authentication Required</title>\n" + "</head><body>\n" + "<h1>Proxy Authentication Required</h1>\n" + "<p>This server could not verify that you\n" + "are authorized to access the document\n" + "requested. Either you supplied the wrong\n" + "credentials (e.g., bad password), or your\n" + "browser doesn't understand how to supply\n" + "the credentials required.</p>\n" + "</body></html>\n"; DefaultFullHttpResponse response = responseFor(HttpVersion.HTTP_1_1, HttpResponseStatus.PROXY_AUTHENTICATION_REQUIRED, body); HttpHeaders.setDate(response, new Date()); response.headers().set("Proxy-Authenticate", "Basic realm=\"Restricted Files\""); write(response); } /*************************************************************************** * Request/Response Rewriting **************************************************************************/ /** * Copy the given {@link HttpRequest} verbatim. * * @param original * @return */ private HttpRequest copy(HttpRequest original) { if (original instanceof DefaultFullHttpRequest) { ByteBuf content = ((DefaultFullHttpRequest) original).content(); return new DefaultFullHttpRequest(original.getProtocolVersion(), original.getMethod(), original.getUri(), content); } else { return new DefaultHttpRequest(original.getProtocolVersion(), original.getMethod(), original.getUri()); } } /** * Chunked encoding is an HTTP 1.1 feature, but sometimes we get a chunked * response that reports its HTTP version as 1.0. In this case, we change it * to 1.1. * * @param httpResponse */ private void fixHttpVersionHeaderIfNecessary(HttpResponse httpResponse) { String te = httpResponse.headers().get( HttpHeaders.Names.TRANSFER_ENCODING); if (StringUtils.isNotBlank(te) && te.equalsIgnoreCase(HttpHeaders.Values.CHUNKED)) { if (httpResponse.getProtocolVersion() != HttpVersion.HTTP_1_1) { LOG.debug("Fixing HTTP version."); httpResponse.setProtocolVersion(HttpVersion.HTTP_1_1); } } } /** * If and only if our proxy is not running in transparent mode, modify the * request headers to reflect that it was proxied. * * @param httpRequest */ private void modifyRequestHeadersToReflectProxying(HttpRequest httpRequest) { if (!proxyServer.isTransparent()) { LOG.debug("Modifying request headers for proxying"); if (!currentServerConnection.hasUpstreamChainedProxy()) { LOG.debug("Modifying request for proxy chaining"); // Strip host from uri String uri = httpRequest.getUri(); String adjustedUri = ProxyUtils.stripHost(uri); LOG.debug("Stripped host from uri: {} yielding: {}", uri, adjustedUri); httpRequest.setUri(adjustedUri); } HttpHeaders headers = httpRequest.headers(); removeSDCHEncoding(headers); switchProxyConnectionHeader(headers); stripConnectionTokens(headers); stripHopByHopHeaders(headers); ProxyUtils.addVia(httpRequest); } } /** * If and only if our proxy is not running in transparent mode, modify the * response headers to reflect that it was proxied. * * @param httpResponse * @return */ private void modifyResponseHeadersToReflectProxying( HttpResponse httpResponse) { if (!proxyServer.isTransparent()) { HttpHeaders headers = httpResponse.headers(); stripConnectionTokens(headers); stripHopByHopHeaders(headers); ProxyUtils.addVia(httpResponse); /* * RFC2616 Section 14.18 * * A received message that does not have a Date header field MUST be * assigned one by the recipient if the message will be cached by * that recipient or gatewayed via a protocol which requires a Date. */ if (!headers.contains(HttpHeaders.Names.DATE)) { HttpHeaders.setDate(httpResponse, new Date()); } } } /** * Remove sdch from encodings we accept since we can't decode it. * * @param headers * The headers to modify */ private void removeSDCHEncoding(HttpHeaders headers) { String ae = headers.get(HttpHeaders.Names.ACCEPT_ENCODING); if (StringUtils.isNotBlank(ae)) { // String noSdch = ae.replace(",sdch", "").replace("sdch", ""); headers.set(HttpHeaders.Names.ACCEPT_ENCODING, noSdch); LOG.debug("Removed sdch and inserted: {}", noSdch); } } /** * Switch the de-facto standard "Proxy-Connection" header to "Connection" * when we pass it along to the remote host. This is largely undocumented * but seems to be what most browsers and servers expect. * * @param headers * The headers to modify */ private void switchProxyConnectionHeader(HttpHeaders headers) { String proxyConnectionKey = "Proxy-Connection"; if (headers.contains(proxyConnectionKey)) { String header = headers.get(proxyConnectionKey); headers.remove(proxyConnectionKey); headers.set(HttpHeaders.Names.CONNECTION, header); } } /** * RFC2616 Section 14.10 * * HTTP/1.1 proxies MUST parse the Connection header field before a message * is forwarded and, for each connection-token in this field, remove any * header field(s) from the message with the same name as the * connection-token. * * @param headers * The headers to modify */ private void stripConnectionTokens(HttpHeaders headers) { if (headers.contains(HttpHeaders.Names.CONNECTION)) { for (String headerValue : headers.getAll(HttpHeaders.Names.CONNECTION)) { for (String connectionToken : ProxyUtils.splitCommaSeparatedHeaderValues(headerValue)) { // do not strip out the Transfer-Encoding header if it is specified in the Connection header, since LittleProxy does not // normally modify the Transfer-Encoding of the message. if (!LOWERCASE_TRANSFER_ENCODING_HEADER.equals(connectionToken.toLowerCase(Locale.US))) { headers.remove(connectionToken); } } } } } /** * Removes all headers that should not be forwarded. See RFC 2616 13.5.1 * End-to-end and Hop-by-hop Headers. * * @param headers * The headers to modify */ private void stripHopByHopHeaders(HttpHeaders headers) { Set<String> headerNames = headers.names(); for (String headerName : headerNames) { if (ProxyUtils.shouldRemoveHopByHopHeader(headerName)) { headers.remove(headerName); } } } /*************************************************************************** * Miscellaneous **************************************************************************/ /** * Tells the client that something went wrong trying to proxy its request. If the Bad Gateway is a response to * an HTTP HEAD request, the response will contain no body, but the Content-Length header will be set to the * value it would have been if this 502 Bad Gateway were in response to a GET. * * @param httpRequest the HttpRequest that is resulting in the Bad Gateway response * @return true if the connection will be kept open, or false if it will be disconnected */ private boolean writeBadGateway(HttpRequest httpRequest) { String body = "Bad Gateway: " + httpRequest.getUri(); DefaultFullHttpResponse response = responseFor(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_GATEWAY, body); if (ProxyUtils.isHEAD(httpRequest)) { // don't allow any body content in response to a HEAD request response.content().clear(); } return respondWithShortCircuitResponse(response); } /** * Tells the client that the request was malformed or erroneous. If the Bad Request is a response to * an HTTP HEAD request, the response will contain no body, but the Content-Length header will be set to the * value it would have been if this Bad Request were in response to a GET. * * @return true if the connection will be kept open, or false if it will be disconnected */ private boolean writeBadRequest(HttpRequest httpRequest) { String body = "Bad Request to URI: " + httpRequest.getUri(); DefaultFullHttpResponse response = responseFor(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST, body); if (ProxyUtils.isHEAD(httpRequest)) { // don't allow any body content in response to a HEAD request response.content().clear(); } return respondWithShortCircuitResponse(response); } /** * Tells the client that the connection to the server, or possibly to some intermediary service (such as DNS), timed out. * If the Gateway Timeout is a response to an HTTP HEAD request, the response will contain no body, but the * Content-Length header will be set to the value it would have been if this 504 Gateway Timeout were in response to a GET. * * @param httpRequest the HttpRequest that is resulting in the Gateway Timeout response * @return true if the connection will be kept open, or false if it will be disconnected */ private boolean writeGatewayTimeout(HttpRequest httpRequest) { String body = "Gateway Timeout"; DefaultFullHttpResponse response = responseFor(HttpVersion.HTTP_1_1, HttpResponseStatus.GATEWAY_TIMEOUT, body); if (httpRequest != null && ProxyUtils.isHEAD(httpRequest)) { // don't allow any body content in response to a HEAD request response.content().clear(); } return respondWithShortCircuitResponse(response); } /** * Responds to the client with the specified "short-circuit" response. The response will be sent through the * {@link HttpFilters#proxyToClientResponse(HttpObject)} filter method before writing it to the client. The client * will not be disconnected, unless the response includes a "Connection: close" header, or the filter returns * a null HttpResponse (in which case no response will be written to the client and the connection will be * disconnected immediately). If the response is not a Bad Gateway or Gateway Timeout response, the response's headers * will be modified to reflect proxying, including adding a Via header, Date header, etc. * * @param httpResponse the response to return to the client * @return true if the connection will be kept open, or false if it will be disconnected. */ private boolean respondWithShortCircuitResponse(HttpResponse httpResponse) { // we are sending a response to the client, so we are done handling this request this.currentRequest = null; HttpResponse filteredResponse = (HttpResponse) currentFilters.proxyToClientResponse(httpResponse); if (filteredResponse == null) { disconnect(); return false; } // allow short-circuit messages to close the connection. normally the Connection header would be stripped when modifying // the message for proxying, so save the keep-alive status before the modifications are made. boolean isKeepAlive = HttpHeaders.isKeepAlive(httpResponse); // if the response is not a Bad Gateway or Gateway Timeout, modify the headers "as if" the short-circuit response were proxied int statusCode = httpResponse.getStatus().code(); if (statusCode != HttpResponseStatus.BAD_GATEWAY.code() && statusCode != HttpResponseStatus.GATEWAY_TIMEOUT.code()) { modifyResponseHeadersToReflectProxying(httpResponse); } // restore the keep alive status, if it was overwritten when modifying headers for proxying HttpHeaders.setKeepAlive(httpResponse, isKeepAlive); write(httpResponse); if (ProxyUtils.isLastChunk(httpResponse)) { writeEmptyBuffer(); } if (!HttpHeaders.isKeepAlive(httpResponse)) { disconnect(); return false; } return true; } /** * Factory for {@link DefaultFullHttpResponse}s. * * @param httpVersion * @param status * @param body * @return */ private DefaultFullHttpResponse responseFor(HttpVersion httpVersion, HttpResponseStatus status, String body) { byte[] bytes = body.getBytes(Charset.forName("UTF-8")); ByteBuf content = Unpooled.copiedBuffer(bytes); return responseFor(httpVersion, status, content, bytes.length); } /** * Factory for {@link DefaultFullHttpResponse}s. * * @param httpVersion * @param status * @param body * @param contentLength * @return */ private DefaultFullHttpResponse responseFor(HttpVersion httpVersion, HttpResponseStatus status, ByteBuf body, int contentLength) { DefaultFullHttpResponse response = body != null ? new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, status, body) : new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status); if (body != null) { response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, contentLength); response.headers().set("Content-Type", "text/html; charset=UTF-8"); } return response; } /** * Factory for {@link DefaultFullHttpResponse}s. * * @param httpVersion * @param status * @return */ private DefaultFullHttpResponse responseFor(HttpVersion httpVersion, HttpResponseStatus status) { return responseFor(httpVersion, status, (ByteBuf) null, 0); } /** * Identify the host and port for a request. * * @param httpRequest * @return */ private String identifyHostAndPort(HttpRequest httpRequest) { String hostAndPort = ProxyUtils.parseHostAndPort(httpRequest); if (StringUtils.isBlank(hostAndPort)) { List<String> hosts = httpRequest.headers().getAll( HttpHeaders.Names.HOST); if (hosts != null && !hosts.isEmpty()) { hostAndPort = hosts.get(0); } } return hostAndPort; } /** * Write an empty buffer at the end of a chunked transfer. We need to do * this to handle the way Netty creates HttpChunks from responses that * aren't in fact chunked from the remote server using Transfer-Encoding: * chunked. Netty turns these into pseudo-chunked responses in cases where * the response would otherwise fill up too much memory or where the length * of the response body is unknown. This is handy because it means we can * start streaming response bodies back to the client without reading the * entire response. The problem is that in these pseudo-cases the last chunk * is encoded to null, and this thwarts normal ChannelFutures from * propagating operationComplete events on writes to appropriate channel * listeners. We work around this by writing an empty buffer in those cases * and using the empty buffer's future instead to handle any operations we * need to when responses are fully written back to clients. */ private void writeEmptyBuffer() { write(Unpooled.EMPTY_BUFFER); } public boolean isMitming() { return mitming; } protected void setMitming(boolean isMitming) { this.mitming = isMitming; } /*************************************************************************** * Activity Tracking/Statistics * * We track statistics on bytes, requests and responses by adding handlers * at the appropriate parts of the pipeline (see initChannelPipeline()). **************************************************************************/ private final BytesReadMonitor bytesReadMonitor = new BytesReadMonitor() { @Override protected void bytesRead(int numberOfBytes) { FlowContext flowContext = flowContext(); for (ActivityTracker tracker : proxyServer .getActivityTrackers()) { tracker.bytesReceivedFromClient(flowContext, numberOfBytes); } } }; private RequestReadMonitor requestReadMonitor = new RequestReadMonitor() { @Override protected void requestRead(HttpRequest httpRequest) { FlowContext flowContext = flowContext(); for (ActivityTracker tracker : proxyServer .getActivityTrackers()) { tracker.requestReceivedFromClient(flowContext, httpRequest); } } }; private BytesWrittenMonitor bytesWrittenMonitor = new BytesWrittenMonitor() { @Override protected void bytesWritten(int numberOfBytes) { FlowContext flowContext = flowContext(); for (ActivityTracker tracker : proxyServer .getActivityTrackers()) { tracker.bytesSentToClient(flowContext, numberOfBytes); } } }; private ResponseWrittenMonitor responseWrittenMonitor = new ResponseWrittenMonitor() { @Override protected void responseWritten(HttpResponse httpResponse) { FlowContext flowContext = flowContext(); for (ActivityTracker tracker : proxyServer .getActivityTrackers()) { tracker.responseSentToClient(flowContext, httpResponse); } } }; private void recordClientConnected() { try { InetSocketAddress clientAddress = getClientAddress(); for (ActivityTracker tracker : proxyServer .getActivityTrackers()) { tracker.clientConnected(clientAddress); } } catch (Exception e) { LOG.error("Unable to recordClientConnected", e); } } private void recordClientSSLHandshakeSucceeded() { try { InetSocketAddress clientAddress = getClientAddress(); for (ActivityTracker tracker : proxyServer .getActivityTrackers()) { tracker.clientSSLHandshakeSucceeded( clientAddress, clientSslSession); } } catch (Exception e) { LOG.error("Unable to recorClientSSLHandshakeSucceeded", e); } } private void recordClientDisconnected() { try { InetSocketAddress clientAddress = getClientAddress(); for (ActivityTracker tracker : proxyServer .getActivityTrackers()) { tracker.clientDisconnected( clientAddress, clientSslSession); } } catch (Exception e) { LOG.error("Unable to recordClientDisconnected", e); } } public InetSocketAddress getClientAddress() { if (channel == null) { return null; } return (InetSocketAddress) channel.remoteAddress(); } private FlowContext flowContext() { if (currentServerConnection != null) { return new FullFlowContext(this, currentServerConnection); } else { return new FlowContext(this); } } }
Host should be removed from URI even when transparently proxying (as the target is the HTTP server).
src/main/java/org/littleshoot/proxy/impl/ClientToProxyConnection.java
Host should be removed from URI even when transparently proxying (as the target is the HTTP server).
<ide><path>rc/main/java/org/littleshoot/proxy/impl/ClientToProxyConnection.java <ide> * @param httpRequest <ide> */ <ide> private void modifyRequestHeadersToReflectProxying(HttpRequest httpRequest) { <add> if (!currentServerConnection.hasUpstreamChainedProxy()) { <add> LOG.debug("Modifying request for proxy chaining"); <add> // Strip host from uri <add> String uri = httpRequest.getUri(); <add> String adjustedUri = ProxyUtils.stripHost(uri); <add> LOG.debug("Stripped host from uri: {} yielding: {}", uri, <add> adjustedUri); <add> httpRequest.setUri(adjustedUri); <add> } <ide> if (!proxyServer.isTransparent()) { <ide> LOG.debug("Modifying request headers for proxying"); <del> <del> if (!currentServerConnection.hasUpstreamChainedProxy()) { <del> LOG.debug("Modifying request for proxy chaining"); <del> // Strip host from uri <del> String uri = httpRequest.getUri(); <del> String adjustedUri = ProxyUtils.stripHost(uri); <del> LOG.debug("Stripped host from uri: {} yielding: {}", uri, <del> adjustedUri); <del> httpRequest.setUri(adjustedUri); <del> } <ide> <ide> HttpHeaders headers = httpRequest.headers(); <ide>
Java
mit
41add8dc47aaeb94fdacf29d0ec5206638b77bcf
0
andresdominguez/ng-sort
package com.andresdominguez.ngsort; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.intellij.lang.javascript.JSDocTokenTypes; import com.intellij.lang.javascript.psi.JSParameter; import com.intellij.lang.javascript.psi.JSParameterList; import com.intellij.lang.javascript.psi.jsdoc.JSDocTag; import com.intellij.openapi.editor.Document; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiComment; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class NgSorter { private final Document document; private final CommentAndParamList commentAndParamList; public NgSorter(Document document, CommentAndParamList commentAndParamList) { this.document = document; this.commentAndParamList = commentAndParamList; } public void sort() { final String fileText = document.getText(); final List<JSDocTag> paramsInComments = findParamsInComments(commentAndParamList.comment); final List<JSDocTag> sortedParams = getSortedCommentParams(paramsInComments); Collections.reverse(paramsInComments); // Replace from bottom to top. Start with the function args. sortFunctionArgs(commentAndParamList.parameterList, document); // Replace @param tags in reverse order. for (int i = 0; i < paramsInComments.size(); i++) { JSDocTag jsDocTag = sortedParams.get(i); String substring = getParamText(fileText, jsDocTag); TextRange range = getTextRange(paramsInComments.get(i)); document.replaceString(range.getStartOffset(), range.getEndOffset(), substring); } } private void sortFunctionArgs(JSParameterList parameterList, Document document) { List<String> sortedArgs = new ArrayList<>(); for (JSParameter parameter : parameterList.getParameters()) { sortedArgs.add(parameter.getName()); } Collections.sort(sortedArgs); String args = Joiner.on(", ").join(sortedArgs); int startOffset = parameterList.getTextOffset() + 1; int endOffset = parameterList.getTextLength() + startOffset - 2; document.replaceString(startOffset, endOffset, args); } @NotNull private List<JSDocTag> findParamsInComments(PsiComment comment) { return Lists.newArrayList(Iterables.filter( PsiTreeUtil.findChildrenOfType(comment, JSDocTag.class), new Predicate<JSDocTag>() { @Override public boolean apply(JSDocTag docTag) { return "param".equals(docTag.getName()); } })); } @NotNull private List<JSDocTag> getSortedCommentParams(List<JSDocTag> paramsInComments) { List<JSDocTag> sortedParams = new ArrayList<>(paramsInComments); Collections.sort(sortedParams, new Comparator<JSDocTag>() { @Override public int compare(JSDocTag left, JSDocTag right) { String rightText = right.getDocCommentData() == null ? "" : right.getDocCommentData().getText(); String leftText = left.getDocCommentData() == null ? "" : left.getDocCommentData().getText(); return rightText.compareTo(leftText); } }); return sortedParams; } private TextRange getTextRange(JSDocTag jsDocTag) { TextRange tr = jsDocTag.getTextRange(); int endOffset = tr.getEndOffset(); PsiElement runner = jsDocTag.getNextSibling(); while (true) { IElementType elementType = runner.getNode().getElementType(); if (!elementType.equals(JSDocTokenTypes.DOC_COMMENT_END) && !elementType.equals(JSDocTokenTypes.DOC_TAG_NAME) && !elementType.equals(JSDocTokenTypes.DOC_TAG)) { endOffset = runner.getTextRange().getEndOffset(); runner = runner.getNextSibling(); } else { return new TextRange(tr.getStartOffset(), endOffset); } } } @NotNull private String getParamText(String fileText, JSDocTag jsDocTag) { TextRange sortedParam = getTextRange(jsDocTag); return fileText.substring(sortedParam.getStartOffset(), sortedParam.getEndOffset()); } }
src/com/andresdominguez/ngsort/NgSorter.java
package com.andresdominguez.ngsort; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.intellij.lang.javascript.JSDocTokenTypes; import com.intellij.lang.javascript.psi.JSParameter; import com.intellij.lang.javascript.psi.JSParameterList; import com.intellij.lang.javascript.psi.jsdoc.JSDocTag; import com.intellij.openapi.editor.Document; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiComment; import com.intellij.psi.PsiElement; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class NgSorter { private final Document document; private final CommentAndParamList commentAndParamList; public NgSorter(Document document, CommentAndParamList commentAndParamList) { this.document = document; this.commentAndParamList = commentAndParamList; } public void sort() { final String fileText = document.getText(); final List<JSDocTag> paramsInComments = NgSorter.findParamsInComments(commentAndParamList.comment); final List<JSDocTag> sortedParams = NgSorter.getSortedCommentParams(paramsInComments); Collections.reverse(paramsInComments); // Replace from bottom to top. Start with the function args. NgSorter.sortFunctionArgs(commentAndParamList.parameterList, document); // Replace @param tags in reverse order. for (int i = 0; i < paramsInComments.size(); i++) { JSDocTag jsDocTag = sortedParams.get(i); String substring = NgSorter.getParamText(fileText, jsDocTag); TextRange range = NgSorter.getTextRange(paramsInComments.get(i)); document.replaceString(range.getStartOffset(), range.getEndOffset(), substring); } } static void sortFunctionArgs(JSParameterList parameterList, Document document) { List<String> sortedArgs = new ArrayList<>(); for (JSParameter parameter : parameterList.getParameters()) { sortedArgs.add(parameter.getName()); } Collections.sort(sortedArgs); String args = Joiner.on(", ").join(sortedArgs); int startOffset = parameterList.getTextOffset() + 1; int endOffset = parameterList.getTextLength() + startOffset - 2; document.replaceString(startOffset, endOffset, args); } @NotNull static List<JSDocTag> findParamsInComments(PsiComment comment) { return Lists.newArrayList(Iterables.filter( PsiTreeUtil.findChildrenOfType(comment, JSDocTag.class), new Predicate<JSDocTag>() { @Override public boolean apply(JSDocTag docTag) { return "param".equals(docTag.getName()); } })); } @NotNull static List<JSDocTag> getSortedCommentParams(List<JSDocTag> paramsInComments) { List<JSDocTag> sortedParams = new ArrayList<>(paramsInComments); Collections.sort(sortedParams, new Comparator<JSDocTag>() { @Override public int compare(JSDocTag left, JSDocTag right) { String rightText = right.getDocCommentData() == null ? "" : right.getDocCommentData().getText(); String leftText = left.getDocCommentData() == null ? "" : left.getDocCommentData().getText(); return rightText.compareTo(leftText); } }); return sortedParams; } static TextRange getTextRange(JSDocTag jsDocTag) { TextRange tr = jsDocTag.getTextRange(); int endOffset = tr.getEndOffset(); PsiElement runner = jsDocTag.getNextSibling(); while (true) { IElementType elementType = runner.getNode().getElementType(); if (!elementType.equals(JSDocTokenTypes.DOC_COMMENT_END) && !elementType.equals(JSDocTokenTypes.DOC_TAG_NAME) && !elementType.equals(JSDocTokenTypes.DOC_TAG)) { endOffset = runner.getTextRange().getEndOffset(); runner = runner.getNextSibling(); } else { return new TextRange(tr.getStartOffset(), endOffset); } } } @NotNull static String getParamText(String fileText, JSDocTag jsDocTag) { TextRange sortedParam = getTextRange(jsDocTag); return fileText.substring(sortedParam.getStartOffset(), sortedParam.getEndOffset()); } }
remove static
src/com/andresdominguez/ngsort/NgSorter.java
remove static
<ide><path>rc/com/andresdominguez/ngsort/NgSorter.java <ide> <ide> public void sort() { <ide> final String fileText = document.getText(); <del> final List<JSDocTag> paramsInComments = NgSorter.findParamsInComments(commentAndParamList.comment); <del> final List<JSDocTag> sortedParams = NgSorter.getSortedCommentParams(paramsInComments); <add> final List<JSDocTag> paramsInComments = findParamsInComments(commentAndParamList.comment); <add> final List<JSDocTag> sortedParams = getSortedCommentParams(paramsInComments); <ide> <ide> Collections.reverse(paramsInComments); <ide> <ide> // Replace from bottom to top. Start with the function args. <del> NgSorter.sortFunctionArgs(commentAndParamList.parameterList, document); <add> sortFunctionArgs(commentAndParamList.parameterList, document); <ide> <ide> // Replace @param tags in reverse order. <ide> for (int i = 0; i < paramsInComments.size(); i++) { <ide> JSDocTag jsDocTag = sortedParams.get(i); <del> String substring = NgSorter.getParamText(fileText, jsDocTag); <add> String substring = getParamText(fileText, jsDocTag); <ide> <del> TextRange range = NgSorter.getTextRange(paramsInComments.get(i)); <add> TextRange range = getTextRange(paramsInComments.get(i)); <ide> <ide> document.replaceString(range.getStartOffset(), range.getEndOffset(), substring); <ide> } <ide> } <ide> <del> static void sortFunctionArgs(JSParameterList parameterList, Document document) { <add> private void sortFunctionArgs(JSParameterList parameterList, Document document) { <ide> List<String> sortedArgs = new ArrayList<>(); <ide> for (JSParameter parameter : parameterList.getParameters()) { <ide> sortedArgs.add(parameter.getName()); <ide> } <ide> <ide> @NotNull <del> static List<JSDocTag> findParamsInComments(PsiComment comment) { <add> private List<JSDocTag> findParamsInComments(PsiComment comment) { <ide> return Lists.newArrayList(Iterables.filter( <ide> PsiTreeUtil.findChildrenOfType(comment, JSDocTag.class), <ide> new Predicate<JSDocTag>() { <ide> } <ide> <ide> @NotNull <del> static List<JSDocTag> getSortedCommentParams(List<JSDocTag> paramsInComments) { <add> private List<JSDocTag> getSortedCommentParams(List<JSDocTag> paramsInComments) { <ide> List<JSDocTag> sortedParams = new ArrayList<>(paramsInComments); <ide> Collections.sort(sortedParams, new Comparator<JSDocTag>() { <ide> @Override <ide> return sortedParams; <ide> } <ide> <del> static TextRange getTextRange(JSDocTag jsDocTag) { <add> private TextRange getTextRange(JSDocTag jsDocTag) { <ide> TextRange tr = jsDocTag.getTextRange(); <ide> int endOffset = tr.getEndOffset(); <ide> <ide> } <ide> <ide> @NotNull <del> static String getParamText(String fileText, JSDocTag jsDocTag) { <add> private String getParamText(String fileText, JSDocTag jsDocTag) { <ide> TextRange sortedParam = getTextRange(jsDocTag); <ide> return fileText.substring(sortedParam.getStartOffset(), sortedParam.getEndOffset()); <ide> }
Java
apache-2.0
a4815319e574d411ae7a21c55b9719bc66dda8a4
0
protyposis/MediaPlayer-Extended,protyposis/MediaPlayer-Extended,protyposis/Spectaculum,protyposis/Spectaculum
/* * Copyright (c) 2014 Mario Guggenberger <[email protected]> * * This file is part of ITEC MediaPlayer. * * ITEC MediaPlayer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ITEC MediaPlayer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ITEC MediaPlayer. If not, see <http://www.gnu.org/licenses/>. */ package at.aau.itec.android.mediaplayerdemo; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.webkit.WebView; import android.widget.Button; import android.widget.TextView; import com.crashlytics.android.Crashlytics; import io.fabric.sdk.android.Fabric; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import at.aau.itec.android.mediaplayer.MediaSource; import at.aau.itec.android.mediaplayer.dash.DashSource; public class MainActivity extends Activity implements VideoURIInputDialogFragment.OnVideoURISelectedListener { private static final String TAG = MainActivity.class.getSimpleName(); private static final int REQUEST_LOAD_VIDEO = 1; private Button mVideoSelectButton; private Button mVideoSelect2Button; private Button mVideoViewButton; private Button mGLVideoViewButton; private Button mGLCameraViewButton; private Button mSideBySideButton; private Button mSideBySideSeekTestButton; private TextView mVideoUriText; private int mVideoUriTextColor; private Uri mVideoUri; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(BuildConfig.CRASHLYTICS_CONFIGURED) { Fabric.with(this, new Crashlytics()); } else { Log.w(TAG, "Crashlytics not configured!"); } setContentView(R.layout.activity_main); mVideoSelectButton = (Button) findViewById(R.id.videoselect); mVideoSelect2Button = (Button) findViewById(R.id.videoselect2); mVideoViewButton = (Button) findViewById(R.id.videoview); mGLVideoViewButton = (Button) findViewById(R.id.glvideoview); mGLCameraViewButton = (Button) findViewById(R.id.glcameraview); mSideBySideButton = (Button) findViewById(R.id.sidebyside); mSideBySideSeekTestButton = (Button) findViewById(R.id.sidebysideseektest); mVideoUriText = (TextView) findViewById(R.id.videouri); mVideoUriTextColor = mVideoUriText.getCurrentTextColor(); mVideoSelectButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // open the picker... Log.d(TAG, "opening video picker..."); Intent intent = null; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { intent = new Intent(Intent.ACTION_PICK); } else { intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); } intent.setType("video/*"); startActivityForResult(intent, REQUEST_LOAD_VIDEO); } }); mVideoSelect2Button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { VideoURIInputDialogFragment dialog = new VideoURIInputDialogFragment(); dialog.show(getFragmentManager(), null); } }); mVideoViewButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, VideoViewActivity.class).setData(mVideoUri)); } }); mGLVideoViewButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, GLVideoViewActivity.class).setData(mVideoUri)); } }); mGLCameraViewButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, GLCameraViewActivity.class).setData(mVideoUri)); } }); mSideBySideButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, SideBySideActivity.class).setData(mVideoUri)); } }); mSideBySideSeekTestButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, SideBySideSeekTestActivity.class).setData(mVideoUri)); } }); ((Button) findViewById(R.id.licenses)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { WebView licensesWebView = new WebView(MainActivity.this); licensesWebView.loadUrl("file:///android_asset/licenses.html"); new AlertDialog.Builder(MainActivity.this) .setTitle(getString(R.string.open_source_licenses)) .setView(licensesWebView) .create() .show(); } }); Uri uri = null; if (getIntent().getData() != null) { // The intent-filter probably caught an url, open it... uri = getIntent().getData(); } else { String savedUriString = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()) .getString("lastUri", ""); if(!"".equals(savedUriString)) { uri = Uri.parse(savedUriString); } } // internet streaming test files //uri = Uri.parse("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"); //uri = Uri.parse("http://www-itec.uni-klu.ac.at/dash/js/content/bunny_4000.webm"); // internet DASH streaming test files //uri = Uri.parse("http://www-itec.uni-klu.ac.at/dash/js/content/bigbuckbunny_1080p.mpd"); //uri = Uri.parse("http://www-itec.uni-klu.ac.at/dash/js/content/bunny_ibmff_1080.mpd"); //uri = Uri.parse("http://dj9wk94416cg5.cloudfront.net/sintel2/sintel.mpd"); if(savedInstanceState != null) { uri = savedInstanceState.getParcelable("uri"); } updateUri(uri); versionInfos(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == REQUEST_LOAD_VIDEO) { Log.d(TAG, "onActivityResult REQUEST_LOAD_VIDEO"); if(resultCode == RESULT_OK) { updateUri(data.getData()); } else { Log.w(TAG, "no file specified"); } } else { super.onActivityResult(requestCode, resultCode, data); } } @Override public void onVideoURISelected(Uri uri) { updateUri(uri); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putParcelable("uri", mVideoUri); super.onSaveInstanceState(outState); } private void updateUri(final Uri uri) { if(uri == null) { mVideoUriText.setText(getString(R.string.uri_missing)); mVideoViewButton.setEnabled(false); mGLVideoViewButton.setEnabled(false); mSideBySideButton.setEnabled(false); mSideBySideSeekTestButton.setEnabled(false); } else { updateUri(null); // disable buttons // Validate content URI if(uri.getScheme().equals("content")) { ContentResolver cr = getContentResolver(); try { cr.openInputStream(uri).close(); } catch (Exception e) { // The content URI is invalid, probably because the file has been removed // or the system rebooted (which invalidates content URIs). return; } } mVideoUriText.setText("Loading..."); Utils.uriToMediaSourceAsync(MainActivity.this, uri, new Utils.MediaSourceAsyncCallbackHandler() { @Override public void onMediaSourceLoaded(MediaSource mediaSource) { String text = uri.toString(); if (mediaSource instanceof DashSource) { text = "DASH: " + text; } mVideoUriText.setText(text); mVideoUriText.setTextColor(mVideoUriTextColor); mVideoUri = uri; mVideoViewButton.setEnabled(true); mGLVideoViewButton.setEnabled(true); mSideBySideButton.setEnabled(!(mediaSource instanceof DashSource)); mSideBySideSeekTestButton.setEnabled(true); PreferenceManager.getDefaultSharedPreferences(getApplicationContext()) .edit().putString("lastUri", uri.toString()).commit(); } @Override public void onException(Exception e) { mVideoUriText.setText("Error loading video" + (e.getMessage() != null ? ": " + e.getMessage() : " :(")); mVideoUriText.setTextColor(Color.RED); Log.e(TAG, "Error loading video", e); } }); } } private void versionInfos() { String versionInfos = ""; Map<String, Class> components = new LinkedHashMap<String, Class>(); components.put("MediaPlayer", at.aau.itec.android.mediaplayer.BuildConfig.class); components.put("MediaPlayer-DASH", at.aau.itec.android.mediaplayer.dash.BuildConfig.class); components.put("MediaPlayer-GLES", at.aau.itec.android.mediaplayer.gles.BuildConfig.class); components.put("MediaPlayer-GLES-FlowAbs", at.aau.itec.android.mediaplayer.gles.flowabs.BuildConfig.class); components.put("MediaPlayer-GLES-QrMarker", at.aau.itec.android.mediaplayer.gles.qrmarker.BuildConfig.class); components.put("MediaPlayerDemo", at.aau.itec.android.mediaplayerdemo.BuildConfig.class); Iterator<String> componentIterator = components.keySet().iterator(); while(componentIterator.hasNext()) { String component = componentIterator.next(); versionInfos += component + ":" + versionInfo(components.get(component)); if(componentIterator.hasNext()) { versionInfos += ", "; } } ((TextView) findViewById(R.id.versioninfos)).setText(versionInfos); } private String versionInfo(Class buildInfo) { String info = ""; try { info += buildInfo.getField("VERSION_NAME").get(null).toString(); info += "/"; info += buildInfo.getField("VERSION_CODE").get(null).toString(); info += "/"; info += buildInfo.getField("BUILD_TYPE").get(null).toString(); info += buildInfo.getField("FLAVOR").get(null).toString(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } return info.length() == 0 ? "n/a" : info; } }
MediaPlayerDemo/src/main/java/at/aau/itec/android/mediaplayerdemo/MainActivity.java
/* * Copyright (c) 2014 Mario Guggenberger <[email protected]> * * This file is part of ITEC MediaPlayer. * * ITEC MediaPlayer is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ITEC MediaPlayer is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ITEC MediaPlayer. If not, see <http://www.gnu.org/licenses/>. */ package at.aau.itec.android.mediaplayerdemo; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.webkit.WebView; import android.widget.Button; import android.widget.TextView; import com.crashlytics.android.Crashlytics; import io.fabric.sdk.android.Fabric; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import at.aau.itec.android.mediaplayer.MediaSource; import at.aau.itec.android.mediaplayer.dash.DashSource; public class MainActivity extends Activity implements VideoURIInputDialogFragment.OnVideoURISelectedListener { private static final String TAG = MainActivity.class.getSimpleName(); private static final int REQUEST_LOAD_VIDEO = 1; private Button mVideoSelectButton; private Button mVideoSelect2Button; private Button mVideoViewButton; private Button mGLVideoViewButton; private Button mGLCameraViewButton; private Button mSideBySideButton; private Button mSideBySideSeekTestButton; private TextView mVideoUriText; private int mVideoUriTextColor; private Uri mVideoUri; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(BuildConfig.CRASHLYTICS_CONFIGURED) { Fabric.with(this, new Crashlytics()); } else { Log.w(TAG, "Crashlytics not configured!"); } setContentView(R.layout.activity_main); mVideoSelectButton = (Button) findViewById(R.id.videoselect); mVideoSelect2Button = (Button) findViewById(R.id.videoselect2); mVideoViewButton = (Button) findViewById(R.id.videoview); mGLVideoViewButton = (Button) findViewById(R.id.glvideoview); mGLCameraViewButton = (Button) findViewById(R.id.glcameraview); mSideBySideButton = (Button) findViewById(R.id.sidebyside); mSideBySideSeekTestButton = (Button) findViewById(R.id.sidebysideseektest); mVideoUriText = (TextView) findViewById(R.id.videouri); mVideoUriTextColor = mVideoUriText.getCurrentTextColor(); mVideoSelectButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // open the picker... Log.d(TAG, "opening video picker..."); Intent intent = null; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { intent = new Intent(Intent.ACTION_PICK); } else { intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); intent.addCategory(Intent.CATEGORY_OPENABLE); } intent.setType("video/*"); startActivityForResult(intent, REQUEST_LOAD_VIDEO); } }); mVideoSelect2Button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { VideoURIInputDialogFragment dialog = new VideoURIInputDialogFragment(); dialog.show(getFragmentManager(), null); } }); mVideoViewButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, VideoViewActivity.class).setData(mVideoUri)); } }); mGLVideoViewButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, GLVideoViewActivity.class).setData(mVideoUri)); } }); mGLCameraViewButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, GLCameraViewActivity.class).setData(mVideoUri)); } }); mSideBySideButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, SideBySideActivity.class).setData(mVideoUri)); } }); mSideBySideSeekTestButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, SideBySideSeekTestActivity.class).setData(mVideoUri)); } }); ((Button) findViewById(R.id.licenses)).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { WebView licensesWebView = new WebView(MainActivity.this); licensesWebView.loadUrl("file:///android_asset/licenses.html"); new AlertDialog.Builder(MainActivity.this) .setTitle(getString(R.string.open_source_licenses)) .setView(licensesWebView) .create() .show(); } }); Uri uri = null; if (getIntent().getData() != null) { // The intent-filter probably caught an url, open it... uri = getIntent().getData(); } else { String savedUriString = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()) .getString("lastUri", ""); if(!"".equals(savedUriString)) { uri = Uri.parse(savedUriString); } } // internet streaming test files //uri = Uri.parse("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"); //uri = Uri.parse("http://www-itec.uni-klu.ac.at/dash/js/content/bunny_4000.webm"); // internet DASH streaming test files //uri = Uri.parse("http://www-itec.uni-klu.ac.at/dash/js/content/bigbuckbunny_1080p.mpd"); //uri = Uri.parse("http://www-itec.uni-klu.ac.at/dash/js/content/bunny_ibmff_1080.mpd"); //uri = Uri.parse("http://dj9wk94416cg5.cloudfront.net/sintel2/sintel.mpd"); if(savedInstanceState != null) { uri = savedInstanceState.getParcelable("uri"); } updateUri(uri); versionInfos(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == REQUEST_LOAD_VIDEO) { Log.d(TAG, "onActivityResult REQUEST_LOAD_VIDEO"); if(resultCode == RESULT_OK) { updateUri(data.getData()); } else { Log.w(TAG, "no file specified"); } } else { super.onActivityResult(requestCode, resultCode, data); } } @Override public void onVideoURISelected(Uri uri) { updateUri(uri); } @Override protected void onSaveInstanceState(Bundle outState) { outState.putParcelable("uri", mVideoUri); super.onSaveInstanceState(outState); } private void updateUri(final Uri uri) { if(uri == null) { mVideoUriText.setText(getString(R.string.uri_missing)); mVideoViewButton.setEnabled(false); mGLVideoViewButton.setEnabled(false); mSideBySideButton.setEnabled(false); mSideBySideSeekTestButton.setEnabled(false); } else { updateUri(null); // disable buttons mVideoUriText.setText("Loading..."); Utils.uriToMediaSourceAsync(MainActivity.this, uri, new Utils.MediaSourceAsyncCallbackHandler() { @Override public void onMediaSourceLoaded(MediaSource mediaSource) { String text = uri.toString(); if (mediaSource instanceof DashSource) { text = "DASH: " + text; } mVideoUriText.setText(text); mVideoUriText.setTextColor(mVideoUriTextColor); mVideoUri = uri; mVideoViewButton.setEnabled(true); mGLVideoViewButton.setEnabled(true); mSideBySideButton.setEnabled(!(mediaSource instanceof DashSource)); mSideBySideSeekTestButton.setEnabled(true); PreferenceManager.getDefaultSharedPreferences(getApplicationContext()) .edit().putString("lastUri", uri.toString()).commit(); } @Override public void onException(Exception e) { mVideoUriText.setText("Error loading video" + (e.getMessage() != null ? ": " + e.getMessage() : " :(")); mVideoUriText.setTextColor(Color.RED); Log.e(TAG, "Error loading video", e); } }); } } private void versionInfos() { String versionInfos = ""; Map<String, Class> components = new LinkedHashMap<String, Class>(); components.put("MediaPlayer", at.aau.itec.android.mediaplayer.BuildConfig.class); components.put("MediaPlayer-DASH", at.aau.itec.android.mediaplayer.dash.BuildConfig.class); components.put("MediaPlayer-GLES", at.aau.itec.android.mediaplayer.gles.BuildConfig.class); components.put("MediaPlayer-GLES-FlowAbs", at.aau.itec.android.mediaplayer.gles.flowabs.BuildConfig.class); components.put("MediaPlayer-GLES-QrMarker", at.aau.itec.android.mediaplayer.gles.qrmarker.BuildConfig.class); components.put("MediaPlayerDemo", at.aau.itec.android.mediaplayerdemo.BuildConfig.class); Iterator<String> componentIterator = components.keySet().iterator(); while(componentIterator.hasNext()) { String component = componentIterator.next(); versionInfos += component + ":" + versionInfo(components.get(component)); if(componentIterator.hasNext()) { versionInfos += ", "; } } ((TextView) findViewById(R.id.versioninfos)).setText(versionInfos); } private String versionInfo(Class buildInfo) { String info = ""; try { info += buildInfo.getField("VERSION_NAME").get(null).toString(); info += "/"; info += buildInfo.getField("VERSION_CODE").get(null).toString(); info += "/"; info += buildInfo.getField("BUILD_TYPE").get(null).toString(); info += buildInfo.getField("FLAVOR").get(null).toString(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } return info.length() == 0 ? "n/a" : info; } }
Discard invalid content URIs (e.g. after system reboot)
MediaPlayerDemo/src/main/java/at/aau/itec/android/mediaplayerdemo/MainActivity.java
Discard invalid content URIs (e.g. after system reboot)
<ide><path>ediaPlayerDemo/src/main/java/at/aau/itec/android/mediaplayerdemo/MainActivity.java <ide> <ide> import android.app.Activity; <ide> import android.app.AlertDialog; <add>import android.content.ContentResolver; <ide> import android.content.Intent; <ide> import android.graphics.Color; <ide> import android.net.Uri; <ide> mSideBySideSeekTestButton.setEnabled(false); <ide> } else { <ide> updateUri(null); // disable buttons <add> <add> // Validate content URI <add> if(uri.getScheme().equals("content")) { <add> ContentResolver cr = getContentResolver(); <add> try { <add> cr.openInputStream(uri).close(); <add> } catch (Exception e) { <add> // The content URI is invalid, probably because the file has been removed <add> // or the system rebooted (which invalidates content URIs). <add> return; <add> } <add> } <add> <ide> mVideoUriText.setText("Loading..."); <ide> <ide> Utils.uriToMediaSourceAsync(MainActivity.this, uri, new Utils.MediaSourceAsyncCallbackHandler() {
Java
apache-2.0
f3c8f224812cf4113b8560b914b352f6b5e48907
0
luj1985/dionysus,luj1985/dionysus,luj1985/dionysus
package com.huixinpn.dionysus.dto.psychtest; import com.huixinpn.dionysus.domain.psychtest.PsychTest; import com.huixinpn.dionysus.domain.psychtest.PsychTestItem; import com.huixinpn.dionysus.dto.EntityData; import lombok.Data; import lombok.NoArgsConstructor; import java.util.ArrayList; import java.util.Collection; @Data @NoArgsConstructor public class PsychTestData extends EntityData { private String title; private String description; private Collection<Long> items = new ArrayList<>(); public PsychTestData(PsychTest test) { super(test); this.title = test.getTitle(); this.description = test.getDescription(); for(PsychTestItem item : test.getItems()){ items.add(item.getId()); } } }
dionysus-rest/src/main/java/com/huixinpn/dionysus/dto/psychtest/PsychTestData.java
package com.huixinpn.dionysus.dto.psychtest; import com.huixinpn.dionysus.domain.psychtest.PsychTest; import com.huixinpn.dionysus.dto.EntityData; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class PsychTestData extends EntityData { private String title; private String description; public PsychTestData(PsychTest test) { super(test); this.title = test.getTitle(); this.description = test.getDescription(); } }
PsychTestData will return array of PsychTestItem only containing ids
dionysus-rest/src/main/java/com/huixinpn/dionysus/dto/psychtest/PsychTestData.java
PsychTestData will return array of PsychTestItem only containing ids
<ide><path>ionysus-rest/src/main/java/com/huixinpn/dionysus/dto/psychtest/PsychTestData.java <ide> package com.huixinpn.dionysus.dto.psychtest; <ide> <ide> import com.huixinpn.dionysus.domain.psychtest.PsychTest; <add>import com.huixinpn.dionysus.domain.psychtest.PsychTestItem; <ide> import com.huixinpn.dionysus.dto.EntityData; <ide> import lombok.Data; <ide> import lombok.NoArgsConstructor; <add> <add>import java.util.ArrayList; <add>import java.util.Collection; <ide> <ide> @Data <ide> @NoArgsConstructor <ide> <ide> private String title; <ide> private String description; <add> private Collection<Long> items = new ArrayList<>(); <ide> <ide> public PsychTestData(PsychTest test) { <ide> super(test); <ide> this.title = test.getTitle(); <ide> this.description = test.getDescription(); <add> for(PsychTestItem item : test.getItems()){ <add> items.add(item.getId()); <add> } <ide> } <ide> <ide> }
Java
mit
bb911a0d46378d68e85bce3801e3742588719b0e
0
SergioPadilla/ERP
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package sekegex; import DataType.*; import Utils.TypeClient; import java.sql.Date; import Utils.StatusTask; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.*; import java.util.Arrays; import java.util.Vector; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; /** * * @author Sergio * * Class to work with MySQL */ public class MySQLTools { private static final MySQLTools instance = new MySQLTools(); private static String sDriver = "com.mysql.jdbc.Driver"; private static String sURL = "jdbc:mysql://85.10.205.173:3306/erpseke"; private static String user="sekegex"; private static String pass="sekegex"; //private static String sURL = "jdbc:mysql://85.10.205.173:3306/erpseke"; private MySQLTools(){} public static MySQLTools getInstance(){ return instance; } //Encrypting functions private static String encrypt(String text) { String secretKey = "97f8c8e8a2802a"; //llave para encriptar datos String base64EncryptedString = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8")); byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); SecretKey key = new SecretKeySpec(keyBytes, "DESede"); Cipher cipher = Cipher.getInstance("DESede"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] plainTextBytes = text.getBytes("utf-8"); byte[] buf = cipher.doFinal(plainTextBytes); byte[] base64Bytes = Base64.encodeBase64(buf); base64EncryptedString = new String(base64Bytes); } catch (Exception ex) { } return base64EncryptedString; } private static String decrypt(String textEncrypted) throws Exception { String secretKey = "97f8c8e8a2802a"; String base64EncryptedString = ""; try { byte[] message = Base64.decodeBase64(textEncrypted.getBytes("utf-8")); MessageDigest md = MessageDigest.getInstance("MD5"); byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8")); byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); SecretKey key = new SecretKeySpec(keyBytes, "DESede"); Cipher decipher = Cipher.getInstance("DESede"); decipher.init(Cipher.DECRYPT_MODE, key); byte[] plainText = decipher.doFinal(message); base64EncryptedString = new String(plainText, "UTF-8"); } catch (Exception ex) { } return base64EncryptedString; } private static String toHexadecimal(byte[] digest){ String hash = ""; for(byte aux : digest) { int b = aux & 0xff; if (Integer.toHexString(b).length() == 1) hash += "0"; hash += Integer.toHexString(b); } return hash; } public static String encryptSHA(String message){ byte[] digest = null; byte[] buffer = message.getBytes(); try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-512"); messageDigest.reset(); messageDigest.update(buffer); digest = messageDigest.digest(); } catch (NoSuchAlgorithmException ex) { System.out.println("Error creando Digest"); } return toHexadecimal(digest); } //END Encrypting functions public static void install(){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("CREATE TABLE clientes (id_cliente INT NOT NULL PRIMARY KEY AUTO_INCREMENT, tipo ENUM('FREELANCE', 'BUSINESS'),nombre TEXT, apellidos TEXT, nif varchar(10) UNIQUE , email TEXT, fecha_alta DATETIME)"); stmt.executeUpdate(); stmt = con.prepareStatement("CREATE TABLE productos (id_producto INT NOT NULL PRIMARY KEY AUTO_INCREMENT, nombre TEXT, descripcion TEXT, importe FLOAT, ventas INT DEFAULT 0)"); stmt.executeUpdate(); stmt = con.prepareStatement("CREATE TABLE facturas (id_factura INT NOT NULL PRIMARY KEY AUTO_INCREMENT, fecha DATETIME,id_cliente INT, FOREIGN KEY (id_cliente) REFERENCES clientes(id_cliente) ON DELETE CASCADE)"); stmt.executeUpdate(); stmt = con.prepareStatement("CREATE TABLE compras (id_producto INT, id_factura INT,precio FLOAT, PRIMARY KEY(id_producto,id_factura),FOREIGN KEY (id_factura) REFERENCES facturas (id_factura) ON DELETE CASCADE)"); stmt.executeUpdate(); stmt = con.prepareStatement("CREATE TABLE servidores (id_servidor INT NOT NULL PRIMARY KEY AUTO_INCREMENT, id_cliente INT, nombre TEXT, ruta_de_acceso TEXT, usuario_ftp TEXT, password_ftp TEXT, usuario_host TEXT, password_host TEXT, FOREIGN KEY (id_cliente) REFERENCES clientes (id_cliente) ON DELETE CASCADE)"); stmt.executeUpdate(); stmt = con.prepareStatement("CREATE TABLE dominios (id_dominio INT NOT NULL PRIMARY KEY AUTO_INCREMENT, id_servidor INT, web TEXT,FOREIGN KEY (id_servidor) REFERENCES servidores (id_servidor) ON DELETE CASCADE)"); stmt.executeUpdate(); stmt = con.prepareStatement("CREATE TABLE empleados (id_empleado INT NOT NULL PRIMARY KEY AUTO_INCREMENT, dni varchar(9) UNIQUE NOT NULL, nombre TEXT, password TEXT, apellidos TEXT, rol INT)"); stmt.executeUpdate(); stmt = con.prepareStatement("CREATE TABLE tareas (id_tarea INT NOT NULL PRIMARY KEY AUTO_INCREMENT,titulo TEXT, fecha DATE, id_tarea_padre INT, horas_estimadas TIME, empleado_asignado INT, estado ENUM('TO_DO', 'DEVELOPMENT', 'DONE'), descripcion TEXT,FOREIGN KEY (empleado_asignado) REFERENCES empleados (id_empleado) ON DELETE CASCADE)"); stmt.executeUpdate(); stmt = con.prepareStatement("CREATE TABLE registros (id_registro INT NOT NULL PRIMARY KEY AUTO_INCREMENT,id_tarea INT, horas_trabajadas TIME, descripcion TEXT, fecha DATE,FOREIGN KEY (id_tarea) REFERENCES tareas (id_tarea) ON DELETE CASCADE"); stmt.executeUpdate(); stmt = con.prepareStatement("CREATE TABLE comentarios (id_comentario INT NOT NULL PRIMARY KEY AUTO_INCREMENT, texto TEXT, tarea INT,FOREIGN KEY (tarea) REFERENCES tareas (id_tarea) ON DELETE CASCADE)"); stmt.executeUpdate(); stmt = con.prepareStatement("CREATE TABLE rol (rol INT NOT NULL , permiso INT, PRIMARY KEY(rol,permiso))"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,100)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,101)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,102)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,103)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,200)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,201)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,202)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,203)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,300)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,301)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,302)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,303)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,400)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,401)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,402)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,403)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,500)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,501)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,502)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,503)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,600)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,601)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,602)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,603)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,700)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,701)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,702)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,703)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,800)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,801)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,802)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,803)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,900)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,901)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,902)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,903)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO empleados (id_empleado , dni, nombre, password, apellidos, rol) VALUES (NULL,'root','Admin','cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e','',1)"); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } //"CLIENTES" table /** * Insert new client in the table */ boolean insertClient(String type, String name, String surname, String dni, String email){ Connection con = null; PreparedStatement stmt = null; boolean res=false; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("INSERT INTO clientes (tipo, nombre, apellidos, nif, email,fecha_alta) VALUES(?,?,?,?,?,UTC_TIMESTAMP());"); stmt.setString(1, type); stmt.setString(2, name); stmt.setString(3, surname); stmt.setString(4, dni); stmt.setString(5, email); res=stmt.execute(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } return res; } /** * Modify client with the params specified */ boolean modifyClient(int id_client, String type, String name, String surname, String dni, String email){ Connection con = null; PreparedStatement stmt = null; boolean res=false; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("UPDATE clientes SET "); boolean first=true; if(!type.equals("")){ query.append("tipo='"); query.append(type); query.append("'"); first=false; } if(!name.equals("")){ if(!first){ query.append(","); } query.append("nombre='"); query.append(name); query.append("'"); first=false; } if(!surname.equals("")){ if(!first){ query.append(","); } query.append("apellidos='"); query.append(surname); query.append("'"); first=false; } if(!dni.equals("")){ if(!first){ query.append(","); } query.append("nif='"); query.append(dni); query.append("'"); first=false; } if(!email.equals("")){ if(!first){ query.append(","); } query.append("email='"); query.append(email); query.append("'"); first=false; } query.append(" WHERE id_cliente="); query.append(id_client); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); res=stmt.execute(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } return res; } /** * Get the data of the client with id specified * @param id_client * @return */ DataClient consultClient(int id_client){ Connection con = null; PreparedStatement stmt = null; TypeClient type=null; String name=null; String surname=null; String nif=null; String email=null; Date date=null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT * FROM clientes WHERE id_cliente='"); query.append(id_client); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs; rs = stmt.executeQuery(); if(rs.next()){ type=TypeClient.valueOf(rs.getString("tipo")); name=rs.getString("nombre"); surname=rs.getString("apellidos"); nif=rs.getString("nif"); email=rs.getString("email"); date=rs.getDate("fecha_alta"); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } return new DataClient(id_client,type,name,surname,nif,email,date); } } public DataBill consultBill(int id_bill){ Connection con = null; PreparedStatement stmt = null; DataBill res=null; int id_client=0; Date date=null; float amount=0; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT * FROM facturas WHERE id_factura="); query.append(id_bill); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs; rs = stmt.executeQuery(); if(rs.next()){ id_client=rs.getInt("id_cliente"); date=rs.getDate("fecha"); query = new StringBuilder("SELECT sum(precio) FROM compras WHERE id_factura='"); query.append(id_bill); query.append("'"); queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); rs=stmt.executeQuery(); if(rs.next()){ amount=rs.getFloat(1); } res=new DataBill(id_bill,id_client,date,amount); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } return res; } } /** * * @param id_client * @return List of bills of the cliente specified by id */ public Vector listBills(int id_client){ Connection con = null; PreparedStatement stmt = null; Vector res=new Vector(); int id_bill; Date date; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT * FROM facturas WHERE id_cliente="); query.append(id_client); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs; rs = stmt.executeQuery(); while (rs.next()) { id_bill=rs.getInt("id_factura"); date=rs.getDate("fecha"); res.addElement(new DataBill(id_bill,id_client,date,0)); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } return res; } } /** * Remove client */ void removeClient(int id_client){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("DELETE FROM clientes WHERE id_cliente='"); query.append(id_client); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } Vector listClients(){ Connection con = null; PreparedStatement stmt = null; int id_client=0; TypeClient type=null; String name=null; String surname=null; String nif=null; String email=null; Date date=null; Vector res=new Vector(); try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("SELECT * FROM clientes"); ResultSet rs; rs = stmt.executeQuery(); while(rs.next()){ id_client=rs.getInt("id_cliente"); type=TypeClient.valueOf(rs.getString("tipo")); name=rs.getString("nombre"); surname=rs.getString("apellidos"); nif=rs.getString("nif"); email=rs.getString("email"); date=rs.getDate("fecha_alta"); res.addElement(new DataClient(id_client,type,name,surname,nif,email,date)); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } return res; } } //"PRODUCTOS" table /** * Insert new product in the table */ void insertProduct(String name, String description, float amount){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("INSERT INTO productos (nombre, descripcion, importe) VALUES(?,?,?);"); stmt.setString(1, name); stmt.setString(2, description); stmt.setFloat(3, amount); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } Vector listProductsforbill(int id_bill){ Connection con = null; PreparedStatement stmt = null; String name=null; String description=null; float amount=0; int id_product=0; int nSold=0; Vector res=new Vector(); try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder sb = new StringBuilder(); sb.append("SELECT * FROM compras,productos WHERE compras.id_factura='"); sb.append(id_bill); sb.append("' AND compras.id_producto=productos.id_producto"); String statement = sb.toString(); stmt = con.prepareStatement(statement); ResultSet rs; rs = stmt.executeQuery(); while(rs.next()){ id_product=rs.getInt("productos.id_producto"); name=rs.getString("nombre"); description=rs.getString("descripcion"); nSold=rs.getInt("ventas"); amount=rs.getFloat("precio"); res.addElement(new DataProduct(id_product,name,description,amount,nSold)); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } return res; } } /** * Modify product */ void modifyProduct(int id_product, String name, String description, float amount){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("UPDATE productos SET "); boolean first=true; if(!name.equals("")){ if(!first){ query.append(","); } query.append("nombre='"); query.append(name); query.append("'"); first=false; } if(!description.equals("")){ if(!first){ query.append(","); } query.append("descripcion='"); query.append(description); query.append("'"); first=false; } if(amount != -1){ if(!first){ query.append(","); } query.append("importe='"); query.append(amount); query.append("'"); first=false; } query.append(" WHERE id_producto="); query.append(id_product); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.execute(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Update the purchases of the product with id specified * @param id_product */ void updatePurchases(int id_product){ } /** * Consult Product * @return Object with the data of a product */ public DataProduct consultProduct(int id_product){ Connection con = null; PreparedStatement stmt = null; String name=null; String description=null; float amount=0; int nSold=0; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT * FROM productos WHERE id_producto="); query.append(id_product); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs; rs = stmt.executeQuery(); if(rs.next()){ name=rs.getString("nombre");; description=rs.getString("descripcion"); amount=rs.getFloat("importe"); nSold=rs.getInt("ventas");; } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } return new DataProduct(id_product,name,description,amount,nSold); } } /** * Remove Product */ void removeProduct(int id_product){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("DELETE FROM productos WHERE id_producto='"); query.append(id_product); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } //"FACTURAS" table /** * Insert new bill in the table */ int insertBill(int id_client){ Connection con = null; PreparedStatement stmt = null; int Id=0; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); String[] returnId = { "BATCHID" }; stmt = con.prepareStatement("INSERT INTO facturas (id_cliente,fecha) VALUES(?,UTC_TIMESTAMP());",returnId); stmt.setInt(1, id_client); stmt.executeUpdate(); try (ResultSet rs = stmt.getGeneratedKeys()) { if (rs.next()) { Id=rs.getInt(1); } rs.close(); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } return Id; } } /** * Modify bill */ void modifyBill(int id_bill,int id_client){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("UPDATE facturas SET id_cliente='"); query.append(id_client); query.append("' WHERE id_factura='"); query.append(id_bill); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.execute(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Remove bill */ void removeBill(int id_bill){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("DELETE FROM facturas WHERE id_factura='"); query.append(id_bill); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } //"COMPRAS" table /** * Insert new purchase in the table */ void insertPurchase(int id_bill, int id_product){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); DataProduct P = consultProduct(id_product); StringBuilder query = new StringBuilder("INSERT INTO compras (id_factura,id_producto,precio) VALUES("); query.append(id_bill); query.append(","); query.append(id_product); query.append(","); query.append(P.amount); query.append(");"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); query = new StringBuilder("UPDATE productos SET ventas=ventas+1 WHERE id_producto='"); query.append(id_product); query.append("'"); queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Erase a product of a purchase */ void removePurchase(int id_bill, int id_product){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("DELETE FROM compras WHERE id_factura='"); query.append(id_bill); query.append("' AND id_producto='"); query.append(id_product); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); query = new StringBuilder("UPDATE productos SET ventas=ventas-1 WHERE id_producto='"); query.append(id_product); query.append("'"); queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } //"SERVIDORES" table /** * Insert new server */ void insertServer(int id_client, String name, String access, String user_ftp, String password_ftp, String user_host, String password_host){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("INSERT INTO servidores (id_cliente, nombre, ruta_de_acceso, usuario_ftp, password_ftp, usuario_host, password_host) VALUES(?,?,?,?,?,?,?);"); stmt.setInt(1, id_client); stmt.setString(2, name); stmt.setString(3, access); stmt.setString(4, user_ftp); stmt.setString(5, encrypt(password_ftp)); stmt.setString(6, user_host); stmt.setString(7, encrypt(password_host)); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Modify server */ void modifyServer(int id_server, String name, String access, String user_ftp, String password_ftp, String user_host, String password_host){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("UPDATE servidores SET "); boolean first=true; if(!name.equals("")){ if(!first){ query.append(","); } query.append("nombre='"); query.append(name); query.append("'"); first=false; } if(!access.equals("")){ if(!first){ query.append(","); } query.append("ruta_de_acceso='"); query.append(access); query.append("'"); first=false; } if(!user_ftp.equals("")){ if(!first){ query.append(","); } query.append("usuario_ftp='"); query.append(user_ftp); query.append("'"); first=false; } if(!password_ftp.equals("")){ if(!first){ query.append(","); } query.append("password_ftp='"); query.append(encrypt(password_ftp)); query.append("'"); first=false; } if(!user_host.equals("")){ if(!first){ query.append(","); } query.append("usuario_host='"); query.append(user_host); query.append("'"); first=false; } if(!password_host.equals("")){ if(!first){ query.append(","); } query.append("password_host='"); query.append(encrypt(password_host)); query.append("'"); first=false; } query.append(" WHERE id_servidor="); query.append(id_server); String queryfinal = new String(query); System.out.println(queryfinal); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * * @param id_client * @return List with the servers for the client with id specified */ public Vector listServers(int id_client){ Connection con = null; PreparedStatement stmt = null; Vector res=new Vector(); int id_server; String name; String ip; String user_ftp; String pass_ftp; String user_host; String pass_host; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT * FROM servidores WHERE id_cliente="); query.append(id_client); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs; rs = stmt.executeQuery(); while (rs.next()){ id_server=rs.getInt("id_servidor"); name=rs.getString("nombre"); ip=rs.getString("ruta_de_acceso"); user_ftp=rs.getString("usuario_ftp"); pass_ftp=decrypt(rs.getString("password_ftp")); user_host=rs.getString("usuario_host"); pass_host=decrypt(rs.getString("password_host")); res.addElement(new DataServer(id_server,id_client,name,ip,user_ftp, pass_ftp,user_host,pass_host)); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } return res; } } /** * * @param id_server * @return server's data with id specified */ public DataServer consultServer(int id_server){ Connection con = null; PreparedStatement stmt = null; DataServer res=null; int id_client=0; String name=null; String ip=null; String user_ftp=null; String pass_ftp=null; String user_host=null; String pass_host=null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT * FROM servidores WHERE id_servidor="); query.append(id_server); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs; rs = stmt.executeQuery(); if(rs.next()){ id_client=rs.getInt("id_cliente"); name=rs.getString("nombre"); ip=rs.getString("ruta_de_acceso"); user_ftp=rs.getString("usuario_ftp"); pass_ftp=decrypt(rs.getString("password_ftp")); user_host=rs.getString("usuario_host"); pass_host=decrypt(rs.getString("password_host")); res=new DataServer(id_server,id_client,name,ip,user_ftp, pass_ftp,user_host,pass_host); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } return res; } } /** * Erase server */ void removeServer(int id_server){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("DELETE FROM servidores WHERE id_servidor='"); query.append(id_server); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } //"EMPLEADOS" table /** * Insert new employee */ void insertEmployee(String dni, String name, String surname, int role){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("INSERT INTO empleados (dni, nombre, apellidos, rol) VALUES(?,?,?,?);"); stmt.setString(1, dni); stmt.setString(2, name); stmt.setString(3, surname); stmt.setInt(4, role); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Modify employee */ void modifyEmployee(int id_employee, String dni, String name, String surname, int role){ Connection con = null; PreparedStatement stmt = null; try{ StringBuilder query = new StringBuilder("UPDATE empleados SET "); boolean first=true; if(!name.equals("")){ if(!first){ query.append(","); } query.append("nombre='"); query.append(name); query.append("'"); first=false; } if(!surname.equals("")){ if(!first){ query.append(","); } query.append("apellidos='"); query.append(surname); query.append("'"); first=false; } if(!dni.equals("")){ if(!first){ query.append(","); } query.append("dni='"); query.append(dni); query.append("'"); first=false; } if(role != -1){ if(!first){ query.append(","); } query.append("rol='"); query.append(role); query.append("'"); first=false; } query.append(" WHERE id_empleado = "); query.append(id_employee); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Erase employee */ void removeEmployee(int id_employee){ } /** * List dni of the employees */ public Vector listDniEmployees(){ Connection con = null; PreparedStatement stmt = null; Vector dni = new Vector(); try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("SELECT dni FROM empleados"); ResultSet rs = stmt.executeQuery(); while(rs.next()){ dni.add(rs.getString("dni")); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } return dni; } /** * List names of the employees */ public Vector listNamesEmployees(){ Connection con = null; PreparedStatement stmt = null; Vector names = new Vector(); try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("SELECT nombre FROM empleados"); ResultSet rs = stmt.executeQuery(); while(rs.next()){ names.add(rs.getString("nombre")); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } return names; } /** * Get employee with dni specified * @param dni * @return */ public DataEmployee consultEmployee(String dni){ Connection con = null; PreparedStatement stmt = null; int id_employee = -1; String name = null; String surname = null; int role = -1; String password = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT * FROM empleados WHERE dni='"); query.append(dni); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs = stmt.executeQuery(); if(rs.next()){ id_employee=rs.getInt("id_empleado"); name=rs.getString("nombre"); surname=rs.getString("apellidos"); role=rs.getInt("rol"); password=rs.getString("password"); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } return new DataEmployee(id_employee, name, dni, password, surname, role); } /** * Get employee with id specified * @param id_employee * @return */ public DataEmployee consultEmployee(int id_employee){ Connection con = null; PreparedStatement stmt = null; String name = null; String surname = null; int role = -1; String password = null; String dni = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT * FROM empleados WHERE id_empleado='"); query.append(id_employee); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs = stmt.executeQuery(); if(rs.next()){ dni=rs.getString("dni"); name=rs.getString("nombre"); surname=rs.getString("apellidos"); role=rs.getInt("rol"); password=rs.getString("password"); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } return new DataEmployee(id_employee, name, dni, password, surname, role); } //"TAREAS" table /** * Insert new task */ void insertTask(String title, String description, Time time_estimated){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("INSERT INTO tareas (titulo, descripcion, horas_estimadas) VALUES(?,?,?);"); stmt.setString(1, title); stmt.setString(2, description); stmt.setTime(3, time_estimated); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Modify task */ void modifyTask(int id_task, String title, String description, Time time_estimated, Date due_date, int id_task_father, int id_employee, StatusTask status){ Connection con = null; PreparedStatement stmt = null; try{ StringBuilder query = new StringBuilder("UPDATE tareas SET "); boolean first=true; if(!title.equals("")){ if(!first){ query.append(","); } query.append("titulo='"); query.append(title); query.append("'"); first=false; } if(!description.equals("")){ if(!first){ query.append(","); } query.append("descripcion='"); query.append(description); query.append("'"); first=false; } if(id_task_father != -1){ if(!first){ query.append(","); } query.append("id_tarea_padre='"); query.append(id_task_father); query.append("'"); first=false; } if(id_employee != -1){ if(!first){ query.append(","); } query.append("empleado_asignado='"); query.append(id_task_father); query.append("'"); first=false; } if(!status.equals("")){ if(!first){ query.append(","); } query.append("estado = '"); query.append(status); query.append("'"); first=false; } if(!time_estimated.equals("")){ if(!first){ query.append(","); } query.append("horas_estimadas = '"); query.append(time_estimated); query.append("'"); first=false; } if(!due_date.equals("")){ if(!first){ query.append(","); } query.append("fecha = '"); query.append(due_date); query.append("'"); first=false; } query.append(" WHERE id_tareas = "); query.append(id_task); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Get the data of the task with id specified * @param id_task * @return */ public DataTask consultTask(int id_task){ Connection con = null; PreparedStatement stmt = null; String title = null; Date due_date = new Date(1,1,1); int id_task_father = -1; Time time_estimated = new Time(1,1,1); int id_employee = -1; StatusTask status = StatusTask.TO_DO; String description = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT * FROM empleados WHERE id_tarea='"); query.append(id_task); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs = stmt.executeQuery(); if(rs.next()){ title=rs.getString("titulo"); due_date=rs.getDate("fecha"); id_task_father=rs.getInt("id_tarea_padre"); time_estimated=rs.getTime("horas_estimadas"); id_employee=rs.getInt("empleado_asignado"); status=StatusTask.valueOf(rs.getString("estado")); description=rs.getString("descripcion"); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } return new DataTask(id_task, title, due_date, id_task_father, time_estimated, id_employee, status, description); } /** * Get the title of all task * @return */ public Vector listTitleTasks(){ Connection con = null; PreparedStatement stmt = null; Vector tasks = new Vector(); try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("SELECT titulo FROM tareas"); ResultSet rs = stmt.executeQuery(); while(rs.next()){ tasks.add(rs.getString("titulo")); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } return tasks; } /** * Erase task */ void eraseTask(int id_task){ } //"REGISTROS" table /** * Insert new register */ void insertRegister(int id_employee, Time time_worked, String description, Date date){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("INSERT INTO registros (id_empleado, horas_trabajadas, descripcion, fecha) VALUES(?,?,?,?);"); stmt.setInt(1, id_employee); stmt.setTime(2, time_worked); stmt.setString(3, description); stmt.setDate(4, date); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Modify register */ void modifyRegister(int id_register, int id_employee, Time time_worked, String description, Date date){ Connection con = null; PreparedStatement stmt = null; try{ StringBuilder query = new StringBuilder("UPDATE registros SET "); boolean first=true; if(id_employee != -1){ if(!first){ query.append(","); } query.append("id_empleado = '"); query.append(id_employee); query.append("'"); first=false; } if(!time_worked.equals("")){ if(!first){ query.append(","); } query.append("horas_trabajadas = '"); query.append(time_worked); query.append("'"); first=false; } if(!description.equals("")){ if(!first){ query.append(","); } query.append("descripcion ='"); query.append(description); query.append("'"); first=false; } if(!date.equals("")){ if(!first){ query.append(","); } query.append("fecha = '"); query.append(date); query.append("'"); first=false; } query.append(" WHERE id_registro = "); query.append(id_register); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Erase register */ void removeRegister(int id_register){ } //"COMENTARIOS" table /** * Insert Comment */ void insertComment(int id_tarea, String comment){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("INSERT INTO comentarios (tarea, texto) VALUES(?,?);"); stmt.setInt(1, id_tarea); stmt.setString(2, comment); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Modify Comment */ void modifyComment(int id_comment, int id_tarea, String comment){ Connection con = null; PreparedStatement stmt = null; try{ StringBuilder query = new StringBuilder("UPDATE comentarios SET "); boolean first=true; if(id_tarea != -1){ if(!first){ query.append(","); } query.append("tarea='"); query.append(id_tarea); query.append("'"); first=false; } if(!comment.equals("")){ if(!first){ query.append(","); } query.append("texto='"); query.append(comment); query.append("'"); first=false; } query.append(" WHERE id_comentario = "); query.append(id_comment); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Erase Comment */ void removeComment(int id_comment){ } // "ROLES" table /** * Insert Role */ void insertRole(int rol, int licence){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("INSERT INTO roles (rol, permiso) VALUES(?,?);"); stmt.setInt(1, rol); stmt.setInt(2, licence); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Modify Role */ void modifyRole(int rol, int licence){ } /** * * @param rol * @return List of licences permitied for this role */ public Vector consultRole(int rol){ Connection con = null; PreparedStatement stmt = null; Vector res=new Vector(); try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT permiso FROM rol WHERE rol = '"); query.append(rol); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs; rs = stmt.executeQuery(); while(rs.next()){ res.addElement(rs.getInt("permiso")); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } return res; } } /** * Erase Role */ void removeRole(int rol){ } //"DOMINIOS" table /** * Insert domain */ void insertDomain(int id_server, String web){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("INSERT INTO dominios (id_servidor, web) VALUES(?,?);"); stmt.setInt(1, id_server); stmt.setString(2, web); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * list domain of the server specified * @param id_server */ Vector listDomains(int id_server){ Connection con = null; PreparedStatement stmt = null; int id_domain=-1; String name=null; Vector res=new Vector(); try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT * FROM dominios WHERE id_servidor='"); query.append(id_server); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs; rs = stmt.executeQuery(); while(rs.next()){ id_domain=rs.getInt("id_dominio"); name=rs.getString("web"); res.addElement(new DataDomain(id_server,id_domain,name)); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } return res; } } /** * Erase domain */ void removeDomain(int id_domain){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("DELETE FROM dominios WHERE id_dominio='"); query.append(id_domain); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * @param id_domain * @return The data of the domain specified by id */ public DataDomain consultDomain(int id_domain){ Connection con = null; PreparedStatement stmt = null; int id_server = 0; String web = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT * FROM dominios WHERE id_dominio='"); query.append(id_domain); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs = stmt.executeQuery(); if(rs.next()){ web=rs.getString("web"); id_server=rs.getInt("id_servidor"); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } return new DataDomain(id_server, id_domain, web); } }
SEKEGEX/src/sekegex/MySQLTools.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package sekegex; import DataType.*; import Utils.TypeClient; import java.sql.Date; import Utils.StatusTask; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.sql.*; import java.util.Arrays; import java.util.Vector; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import org.apache.commons.codec.binary.Base64; /** * * @author Sergio * * Class to work with MySQL */ public class MySQLTools { private static final MySQLTools instance = new MySQLTools(); private static String sDriver = "com.mysql.jdbc.Driver"; private static String sURL = "jdbc:mysql://85.10.205.173:3306/erpseke"; private static String user="sekegex"; private static String pass="sekegex"; //private static String sURL = "jdbc:mysql://85.10.205.173:3306/erpseke"; private MySQLTools(){} public static MySQLTools getInstance(){ return instance; } //Encrypting functions private static String encrypt(String text) { String secretKey = "97f8c8e8a2802a"; //llave para encriptar datos String base64EncryptedString = ""; try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8")); byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); SecretKey key = new SecretKeySpec(keyBytes, "DESede"); Cipher cipher = Cipher.getInstance("DESede"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] plainTextBytes = text.getBytes("utf-8"); byte[] buf = cipher.doFinal(plainTextBytes); byte[] base64Bytes = Base64.encodeBase64(buf); base64EncryptedString = new String(base64Bytes); } catch (Exception ex) { } return base64EncryptedString; } private static String decrypt(String textEncrypted) throws Exception { String secretKey = "97f8c8e8a2802a"; String base64EncryptedString = ""; try { byte[] message = Base64.decodeBase64(textEncrypted.getBytes("utf-8")); MessageDigest md = MessageDigest.getInstance("MD5"); byte[] digestOfPassword = md.digest(secretKey.getBytes("utf-8")); byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); SecretKey key = new SecretKeySpec(keyBytes, "DESede"); Cipher decipher = Cipher.getInstance("DESede"); decipher.init(Cipher.DECRYPT_MODE, key); byte[] plainText = decipher.doFinal(message); base64EncryptedString = new String(plainText, "UTF-8"); } catch (Exception ex) { } return base64EncryptedString; } private static String toHexadecimal(byte[] digest){ String hash = ""; for(byte aux : digest) { int b = aux & 0xff; if (Integer.toHexString(b).length() == 1) hash += "0"; hash += Integer.toHexString(b); } return hash; } public static String encryptSHA(String message){ byte[] digest = null; byte[] buffer = message.getBytes(); try { MessageDigest messageDigest = MessageDigest.getInstance("SHA-512"); messageDigest.reset(); messageDigest.update(buffer); digest = messageDigest.digest(); } catch (NoSuchAlgorithmException ex) { System.out.println("Error creando Digest"); } return toHexadecimal(digest); } //END Encrypting functions public static void install(){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("CREATE TABLE clientes (id_cliente INT NOT NULL PRIMARY KEY AUTO_INCREMENT, tipo ENUM('FREELANCE', 'BUSINESS'),nombre TEXT, apellidos TEXT, nif varchar(10) UNIQUE , email TEXT, fecha_alta DATETIME)"); stmt.executeUpdate(); stmt = con.prepareStatement("CREATE TABLE productos (id_producto INT NOT NULL PRIMARY KEY AUTO_INCREMENT, nombre TEXT, descripcion TEXT, importe FLOAT, ventas INT DEFAULT 0)"); stmt.executeUpdate(); stmt = con.prepareStatement("CREATE TABLE facturas (id_factura INT NOT NULL PRIMARY KEY AUTO_INCREMENT, fecha DATETIME,id_cliente INT, FOREIGN KEY (id_cliente) REFERENCES clientes(id_cliente) ON DELETE CASCADE)"); stmt.executeUpdate(); stmt = con.prepareStatement("CREATE TABLE compras (id_producto INT, id_factura INT,precio FLOAT, PRIMARY KEY(id_producto,id_factura),FOREIGN KEY (id_factura) REFERENCES facturas (id_factura) ON DELETE CASCADE)"); stmt.executeUpdate(); stmt = con.prepareStatement("CREATE TABLE servidores (id_servidor INT NOT NULL PRIMARY KEY AUTO_INCREMENT, id_cliente INT, nombre TEXT, ruta_de_acceso TEXT, usuario_ftp TEXT, password_ftp TEXT, usuario_host TEXT, password_host TEXT, FOREIGN KEY (id_cliente) REFERENCES clientes (id_cliente) ON DELETE CASCADE)"); stmt.executeUpdate(); stmt = con.prepareStatement("CREATE TABLE dominios (id_dominio INT NOT NULL PRIMARY KEY AUTO_INCREMENT, id_servidor INT, web TEXT,FOREIGN KEY (id_servidor) REFERENCES servidores (id_servidor) ON DELETE CASCADE)"); stmt.executeUpdate(); stmt = con.prepareStatement("CREATE TABLE empleados (id_empleado INT NOT NULL PRIMARY KEY AUTO_INCREMENT, dni varchar(9) UNIQUE NOT NULL, nombre TEXT, password TEXT, apellidos TEXT, rol INT)"); stmt.executeUpdate(); stmt = con.prepareStatement("CREATE TABLE tareas (id_tarea INT NOT NULL PRIMARY KEY AUTO_INCREMENT,titulo TEXT, fecha DATE, id_tarea_padre INT, horas_estimadas TIME, empleado_asignado INT, estado ENUM('TO_DO', 'DEVELOPMENT', 'DONE'), descripcion TEXT,FOREIGN KEY (empleado_asignado) REFERENCES empleados (id_empleado) ON DELETE CASCADE)"); stmt.executeUpdate(); stmt = con.prepareStatement("CREATE TABLE registros (id_registro INT NOT NULL PRIMARY KEY AUTO_INCREMENT,id_tarea INT, horas_trabajadas TIME, descripcion TEXT, fecha DATE,FOREIGN KEY (id_tarea) REFERENCES tareas (id_tarea) ON DELETE CASCADE"); stmt.executeUpdate(); stmt = con.prepareStatement("CREATE TABLE comentarios (id_comentario INT NOT NULL PRIMARY KEY AUTO_INCREMENT, texto TEXT, tarea INT,FOREIGN KEY (tarea) REFERENCES tareas (id_tarea) ON DELETE CASCADE)"); stmt.executeUpdate(); stmt = con.prepareStatement("CREATE TABLE rol (rol INT NOT NULL , permiso INT, PRIMARY KEY(rol,permiso))"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,100)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,101)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,102)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,103)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,200)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,201)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,202)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,203)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,300)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,301)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,302)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,303)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,400)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,401)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,402)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,403)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,500)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,501)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,502)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,503)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,600)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,601)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,602)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,603)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,700)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,701)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,702)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,703)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,800)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,801)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,802)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,803)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,900)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,901)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,902)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO rol (rol, permiso) VALUES(1,903)"); stmt.executeUpdate(); stmt = con.prepareStatement("INSERT INTO empleados (id_empleado , dni, nombre, password, apellidos, rol) VALUES (NULL,'root','Admin','cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e','',1)"); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } //"CLIENTES" table /** * Insert new client in the table */ boolean insertClient(String type, String name, String surname, String dni, String email){ Connection con = null; PreparedStatement stmt = null; boolean res=false; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("INSERT INTO clientes (tipo, nombre, apellidos, nif, email,fecha_alta) VALUES(?,?,?,?,?,UTC_TIMESTAMP());"); stmt.setString(1, type); stmt.setString(2, name); stmt.setString(3, surname); stmt.setString(4, dni); stmt.setString(5, email); res=stmt.execute(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } return res; } /** * Modify client with the params specified */ boolean modifyClient(int id_client, String type, String name, String surname, String dni, String email){ Connection con = null; PreparedStatement stmt = null; boolean res=false; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("UPDATE clientes SET "); boolean first=true; if(!type.equals("")){ query.append("tipo='"); query.append(type); query.append("'"); first=false; } if(!name.equals("")){ if(!first){ query.append(","); } query.append("nombre='"); query.append(name); query.append("'"); first=false; } if(!surname.equals("")){ if(!first){ query.append(","); } query.append("apellido='"); query.append(surname); query.append("'"); first=false; } if(!dni.equals("")){ if(!first){ query.append(","); } query.append("nif='"); query.append(dni); query.append("'"); first=false; } if(!email.equals("")){ if(!first){ query.append(","); } query.append("email='"); query.append(email); query.append("'"); first=false; } query.append(" WHERE id_cliente="); query.append(id_client); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); res=stmt.execute(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } return res; } /** * Get the data of the client with id specified * @param id_client * @return */ DataClient consultClient(int id_client){ Connection con = null; PreparedStatement stmt = null; TypeClient type=null; String name=null; String surname=null; String nif=null; String email=null; Date date=null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT * FROM clientes WHERE id_cliente='"); query.append(id_client); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs; rs = stmt.executeQuery(); if(rs.next()){ type=TypeClient.valueOf(rs.getString("tipo")); name=rs.getString("nombre"); surname=rs.getString("apellidos"); nif=rs.getString("nif"); email=rs.getString("email"); date=rs.getDate("fecha_alta"); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } return new DataClient(id_client,type,name,surname,nif,email,date); } } public DataBill consultBill(int id_bill){ Connection con = null; PreparedStatement stmt = null; DataBill res=null; int id_client=0; Date date=null; float amount=0; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT * FROM facturas WHERE id_factura="); query.append(id_bill); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs; rs = stmt.executeQuery(); if(rs.next()){ id_client=rs.getInt("id_cliente"); date=rs.getDate("fecha"); query = new StringBuilder("SELECT sum(precio) FROM compras WHERE id_factura='"); query.append(id_bill); query.append("'"); queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); rs=stmt.executeQuery(); if(rs.next()){ amount=rs.getFloat(1); } res=new DataBill(id_bill,id_client,date,amount); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } return res; } } /** * * @param id_client * @return List of bills of the cliente specified by id */ public Vector listBills(int id_client){ Connection con = null; PreparedStatement stmt = null; Vector res=new Vector(); int id_bill; Date date; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT * FROM facturas WHERE id_cliente="); query.append(id_client); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs; rs = stmt.executeQuery(); while (rs.next()) { id_bill=rs.getInt("id_factura"); date=rs.getDate("fecha"); res.addElement(new DataBill(id_bill,id_client,date,0)); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } return res; } } /** * Remove client */ void removeClient(int id_client){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("DELETE FROM clientes WHERE id_cliente='"); query.append(id_client); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } Vector listClients(){ Connection con = null; PreparedStatement stmt = null; int id_client=0; TypeClient type=null; String name=null; String surname=null; String nif=null; String email=null; Date date=null; Vector res=new Vector(); try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("SELECT * FROM clientes"); ResultSet rs; rs = stmt.executeQuery(); while(rs.next()){ id_client=rs.getInt("id_cliente"); type=TypeClient.valueOf(rs.getString("tipo")); name=rs.getString("nombre"); surname=rs.getString("apellidos"); nif=rs.getString("nif"); email=rs.getString("email"); date=rs.getDate("fecha_alta"); res.addElement(new DataClient(id_client,type,name,surname,nif,email,date)); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } return res; } } //"PRODUCTOS" table /** * Insert new product in the table */ void insertProduct(String name, String description, float amount){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("INSERT INTO productos (nombre, descripcion, importe) VALUES(?,?,?);"); stmt.setString(1, name); stmt.setString(2, description); stmt.setFloat(3, amount); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } Vector listProductsforbill(int id_bill){ Connection con = null; PreparedStatement stmt = null; String name=null; String description=null; float amount=0; int id_product=0; int nSold=0; Vector res=new Vector(); try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder sb = new StringBuilder(); sb.append("SELECT * FROM compras,productos WHERE compras.id_factura='"); sb.append(id_bill); sb.append("' AND compras.id_producto=productos.id_producto"); String statement = sb.toString(); stmt = con.prepareStatement(statement); ResultSet rs; rs = stmt.executeQuery(); while(rs.next()){ id_product=rs.getInt("productos.id_producto"); name=rs.getString("nombre"); description=rs.getString("descripcion"); nSold=rs.getInt("ventas"); amount=rs.getFloat("precio"); res.addElement(new DataProduct(id_product,name,description,amount,nSold)); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } return res; } } /** * Modify product */ void modifyProduct(int id_product, String name, String description, float amount){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("UPDATE productos SET "); boolean first=true; if(!name.equals("")){ if(!first){ query.append(","); } query.append("nombre='"); query.append(name); query.append("'"); first=false; } if(!description.equals("")){ if(!first){ query.append(","); } query.append("descripcion='"); query.append(description); query.append("'"); first=false; } if(amount != -1){ if(!first){ query.append(","); } query.append("importe='"); query.append(amount); query.append("'"); first=false; } query.append(" WHERE id_producto="); query.append(id_product); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.execute(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Update the purchases of the product with id specified * @param id_product */ void updatePurchases(int id_product){ } /** * Consult Product * @return Object with the data of a product */ public DataProduct consultProduct(int id_product){ Connection con = null; PreparedStatement stmt = null; String name=null; String description=null; float amount=0; int nSold=0; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT * FROM productos WHERE id_producto="); query.append(id_product); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs; rs = stmt.executeQuery(); if(rs.next()){ name=rs.getString("nombre");; description=rs.getString("descripcion"); amount=rs.getFloat("importe"); nSold=rs.getInt("ventas");; } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } return new DataProduct(id_product,name,description,amount,nSold); } } /** * Remove Product */ void removeProduct(int id_product){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("DELETE FROM productos WHERE id_producto='"); query.append(id_product); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } //"FACTURAS" table /** * Insert new bill in the table */ int insertBill(int id_client){ Connection con = null; PreparedStatement stmt = null; int Id=0; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); String[] returnId = { "BATCHID" }; stmt = con.prepareStatement("INSERT INTO facturas (id_cliente,fecha) VALUES(?,UTC_TIMESTAMP());",returnId); stmt.setInt(1, id_client); stmt.executeUpdate(); try (ResultSet rs = stmt.getGeneratedKeys()) { if (rs.next()) { Id=rs.getInt(1); } rs.close(); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } return Id; } } /** * Modify bill */ void modifyBill(int id_bill,int id_client){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("UPDATE facturas SET id_cliente='"); query.append(id_client); query.append("' WHERE id_factura='"); query.append(id_bill); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.execute(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Remove bill */ void removeBill(int id_bill){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("DELETE FROM facturas WHERE id_factura='"); query.append(id_bill); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } //"COMPRAS" table /** * Insert new purchase in the table */ void insertPurchase(int id_bill, int id_product){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); DataProduct P = consultProduct(id_product); StringBuilder query = new StringBuilder("INSERT INTO compras (id_factura,id_producto,precio) VALUES("); query.append(id_bill); query.append(","); query.append(id_product); query.append(","); query.append(P.amount); query.append(");"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); query = new StringBuilder("UPDATE productos SET ventas=ventas+1 WHERE id_producto='"); query.append(id_product); query.append("'"); queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Erase a product of a purchase */ void removePurchase(int id_bill, int id_product){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("DELETE FROM compras WHERE id_factura='"); query.append(id_bill); query.append("' AND id_producto='"); query.append(id_product); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); query = new StringBuilder("UPDATE productos SET ventas=ventas-1 WHERE id_producto='"); query.append(id_product); query.append("'"); queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } //"SERVIDORES" table /** * Insert new server */ void insertServer(int id_client, String name, String access, String user_ftp, String password_ftp, String user_host, String password_host){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("INSERT INTO servidores (id_cliente, nombre, ruta_de_acceso, usuario_ftp, password_ftp, usuario_host, password_host) VALUES(?,?,?,?,?,?,?);"); stmt.setInt(1, id_client); stmt.setString(2, name); stmt.setString(3, access); stmt.setString(4, user_ftp); stmt.setString(5, encrypt(password_ftp)); stmt.setString(6, user_host); stmt.setString(7, encrypt(password_host)); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Modify server */ void modifyServer(int id_server, String name, String access, String user_ftp, String password_ftp, String user_host, String password_host){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("UPDATE servidores SET "); boolean first=true; if(!name.equals("")){ if(!first){ query.append(","); } query.append("nombre='"); query.append(name); query.append("'"); first=false; } if(!access.equals("")){ if(!first){ query.append(","); } query.append("ruta_de_acceso='"); query.append(access); query.append("'"); first=false; } if(!user_ftp.equals("")){ if(!first){ query.append(","); } query.append("usuario_ftp='"); query.append(user_ftp); query.append("'"); first=false; } if(!password_ftp.equals("")){ if(!first){ query.append(","); } query.append("password_ftp='"); query.append(encrypt(password_ftp)); query.append("'"); first=false; } if(!user_host.equals("")){ if(!first){ query.append(","); } query.append("usuario_host='"); query.append(user_host); query.append("'"); first=false; } if(!password_host.equals("")){ if(!first){ query.append(","); } query.append("password_host='"); query.append(encrypt(password_host)); query.append("'"); first=false; } query.append(" WHERE id_servidor="); query.append(id_server); String queryfinal = new String(query); System.out.println(queryfinal); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * * @param id_client * @return List with the servers for the client with id specified */ public Vector listServers(int id_client){ Connection con = null; PreparedStatement stmt = null; Vector res=new Vector(); int id_server; String name; String ip; String user_ftp; String pass_ftp; String user_host; String pass_host; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT * FROM servidores WHERE id_cliente="); query.append(id_client); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs; rs = stmt.executeQuery(); while (rs.next()){ id_server=rs.getInt("id_servidor"); name=rs.getString("nombre"); ip=rs.getString("ruta_de_acceso"); user_ftp=rs.getString("usuario_ftp"); pass_ftp=decrypt(rs.getString("password_ftp")); user_host=rs.getString("usuario_host"); pass_host=decrypt(rs.getString("password_host")); res.addElement(new DataServer(id_server,id_client,name,ip,user_ftp, pass_ftp,user_host,pass_host)); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } return res; } } /** * * @param id_server * @return server's data with id specified */ public DataServer consultServer(int id_server){ Connection con = null; PreparedStatement stmt = null; DataServer res=null; int id_client=0; String name=null; String ip=null; String user_ftp=null; String pass_ftp=null; String user_host=null; String pass_host=null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT * FROM servidores WHERE id_servidor="); query.append(id_server); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs; rs = stmt.executeQuery(); if(rs.next()){ id_client=rs.getInt("id_cliente"); name=rs.getString("nombre"); ip=rs.getString("ruta_de_acceso"); user_ftp=rs.getString("usuario_ftp"); pass_ftp=decrypt(rs.getString("password_ftp")); user_host=rs.getString("usuario_host"); pass_host=decrypt(rs.getString("password_host")); res=new DataServer(id_server,id_client,name,ip,user_ftp, pass_ftp,user_host,pass_host); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } return res; } } /** * Erase server */ void removeServer(int id_server){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("DELETE FROM servidores WHERE id_servidor='"); query.append(id_server); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } //"EMPLEADOS" table /** * Insert new employee */ void insertEmployee(String dni, String name, String surname, int role){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("INSERT INTO empleados (dni, nombre, apellidos, rol) VALUES(?,?,?,?);"); stmt.setString(1, dni); stmt.setString(2, name); stmt.setString(3, surname); stmt.setInt(4, role); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Modify employee */ void modifyEmployee(int id_employee, String dni, String name, String surname, int role){ Connection con = null; PreparedStatement stmt = null; try{ StringBuilder query = new StringBuilder("UPDATE empleados SET "); boolean first=true; if(!name.equals("")){ if(!first){ query.append(","); } query.append("nombre='"); query.append(name); query.append("'"); first=false; } if(!surname.equals("")){ if(!first){ query.append(","); } query.append("apellidos='"); query.append(surname); query.append("'"); first=false; } if(!dni.equals("")){ if(!first){ query.append(","); } query.append("dni='"); query.append(dni); query.append("'"); first=false; } if(role != -1){ if(!first){ query.append(","); } query.append("rol='"); query.append(role); query.append("'"); first=false; } query.append(" WHERE id_empleado = "); query.append(id_employee); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Erase employee */ void removeEmployee(int id_employee){ } /** * List dni of the employees */ public Vector listDniEmployees(){ Connection con = null; PreparedStatement stmt = null; Vector dni = new Vector(); try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("SELECT dni FROM empleados"); ResultSet rs = stmt.executeQuery(); while(rs.next()){ dni.add(rs.getString("dni")); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } return dni; } /** * List names of the employees */ public Vector listNamesEmployees(){ Connection con = null; PreparedStatement stmt = null; Vector names = new Vector(); try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("SELECT nombre FROM empleados"); ResultSet rs = stmt.executeQuery(); while(rs.next()){ names.add(rs.getString("nombre")); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } return names; } /** * Get employee with dni specified * @param dni * @return */ public DataEmployee consultEmployee(String dni){ Connection con = null; PreparedStatement stmt = null; int id_employee = -1; String name = null; String surname = null; int role = -1; String password = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT * FROM empleados WHERE dni='"); query.append(dni); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs = stmt.executeQuery(); if(rs.next()){ id_employee=rs.getInt("id_empleado"); name=rs.getString("nombre"); surname=rs.getString("apellidos"); role=rs.getInt("rol"); password=rs.getString("password"); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } return new DataEmployee(id_employee, name, dni, password, surname, role); } /** * Get employee with id specified * @param id_employee * @return */ public DataEmployee consultEmployee(int id_employee){ Connection con = null; PreparedStatement stmt = null; String name = null; String surname = null; int role = -1; String password = null; String dni = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT * FROM empleados WHERE id_empleado='"); query.append(id_employee); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs = stmt.executeQuery(); if(rs.next()){ dni=rs.getString("dni"); name=rs.getString("nombre"); surname=rs.getString("apellidos"); role=rs.getInt("rol"); password=rs.getString("password"); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } return new DataEmployee(id_employee, name, dni, password, surname, role); } //"TAREAS" table /** * Insert new task */ void insertTask(String title, String description, Time time_estimated){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("INSERT INTO tareas (titulo, descripcion, horas_estimadas) VALUES(?,?,?);"); stmt.setString(1, title); stmt.setString(2, description); stmt.setTime(3, time_estimated); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Modify task */ void modifyTask(int id_task, String title, String description, Time time_estimated, Date due_date, int id_task_father, int id_employee, StatusTask status){ Connection con = null; PreparedStatement stmt = null; try{ StringBuilder query = new StringBuilder("UPDATE tareas SET "); boolean first=true; if(!title.equals("")){ if(!first){ query.append(","); } query.append("titulo='"); query.append(title); query.append("'"); first=false; } if(!description.equals("")){ if(!first){ query.append(","); } query.append("descripcion='"); query.append(description); query.append("'"); first=false; } if(id_task_father != -1){ if(!first){ query.append(","); } query.append("id_tarea_padre='"); query.append(id_task_father); query.append("'"); first=false; } if(id_employee != -1){ if(!first){ query.append(","); } query.append("empleado_asignado='"); query.append(id_task_father); query.append("'"); first=false; } if(!status.equals("")){ if(!first){ query.append(","); } query.append("estado = '"); query.append(status); query.append("'"); first=false; } if(!time_estimated.equals("")){ if(!first){ query.append(","); } query.append("horas_estimadas = '"); query.append(time_estimated); query.append("'"); first=false; } if(!due_date.equals("")){ if(!first){ query.append(","); } query.append("fecha = '"); query.append(due_date); query.append("'"); first=false; } query.append(" WHERE id_tareas = "); query.append(id_task); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Get the data of the task with id specified * @param id_task * @return */ public DataTask consultTask(int id_task){ Connection con = null; PreparedStatement stmt = null; String title = null; Date due_date = new Date(1,1,1); int id_task_father = -1; Time time_estimated = new Time(1,1,1); int id_employee = -1; StatusTask status = StatusTask.TO_DO; String description = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT * FROM empleados WHERE id_tarea='"); query.append(id_task); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs = stmt.executeQuery(); if(rs.next()){ title=rs.getString("titulo"); due_date=rs.getDate("fecha"); id_task_father=rs.getInt("id_tarea_padre"); time_estimated=rs.getTime("horas_estimadas"); id_employee=rs.getInt("empleado_asignado"); status=StatusTask.valueOf(rs.getString("estado")); description=rs.getString("descripcion"); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } return new DataTask(id_task, title, due_date, id_task_father, time_estimated, id_employee, status, description); } /** * Get the title of all task * @return */ public Vector listTitleTasks(){ Connection con = null; PreparedStatement stmt = null; Vector tasks = new Vector(); try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("SELECT titulo FROM tareas"); ResultSet rs = stmt.executeQuery(); while(rs.next()){ tasks.add(rs.getString("titulo")); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } return tasks; } /** * Erase task */ void eraseTask(int id_task){ } //"REGISTROS" table /** * Insert new register */ void insertRegister(int id_employee, Time time_worked, String description, Date date){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("INSERT INTO registros (id_empleado, horas_trabajadas, descripcion, fecha) VALUES(?,?,?,?);"); stmt.setInt(1, id_employee); stmt.setTime(2, time_worked); stmt.setString(3, description); stmt.setDate(4, date); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Modify register */ void modifyRegister(int id_register, int id_employee, Time time_worked, String description, Date date){ Connection con = null; PreparedStatement stmt = null; try{ StringBuilder query = new StringBuilder("UPDATE registros SET "); boolean first=true; if(id_employee != -1){ if(!first){ query.append(","); } query.append("id_empleado = '"); query.append(id_employee); query.append("'"); first=false; } if(!time_worked.equals("")){ if(!first){ query.append(","); } query.append("horas_trabajadas = '"); query.append(time_worked); query.append("'"); first=false; } if(!description.equals("")){ if(!first){ query.append(","); } query.append("descripcion ='"); query.append(description); query.append("'"); first=false; } if(!date.equals("")){ if(!first){ query.append(","); } query.append("fecha = '"); query.append(date); query.append("'"); first=false; } query.append(" WHERE id_registro = "); query.append(id_register); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Erase register */ void removeRegister(int id_register){ } //"COMENTARIOS" table /** * Insert Comment */ void insertComment(int id_tarea, String comment){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("INSERT INTO comentarios (tarea, texto) VALUES(?,?);"); stmt.setInt(1, id_tarea); stmt.setString(2, comment); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Modify Comment */ void modifyComment(int id_comment, int id_tarea, String comment){ Connection con = null; PreparedStatement stmt = null; try{ StringBuilder query = new StringBuilder("UPDATE comentarios SET "); boolean first=true; if(id_tarea != -1){ if(!first){ query.append(","); } query.append("tarea='"); query.append(id_tarea); query.append("'"); first=false; } if(!comment.equals("")){ if(!first){ query.append(","); } query.append("texto='"); query.append(comment); query.append("'"); first=false; } query.append(" WHERE id_comentario = "); query.append(id_comment); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Erase Comment */ void removeComment(int id_comment){ } // "ROLES" table /** * Insert Role */ void insertRole(int rol, int licence){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("INSERT INTO roles (rol, permiso) VALUES(?,?);"); stmt.setInt(1, rol); stmt.setInt(2, licence); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * Modify Role */ void modifyRole(int rol, int licence){ } /** * * @param rol * @return List of licences permitied for this role */ public Vector consultRole(int rol){ Connection con = null; PreparedStatement stmt = null; Vector res=new Vector(); try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT permiso FROM rol WHERE rol = '"); query.append(rol); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs; rs = stmt.executeQuery(); while(rs.next()){ res.addElement(rs.getInt("permiso")); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } return res; } } /** * Erase Role */ void removeRole(int rol){ } //"DOMINIOS" table /** * Insert domain */ void insertDomain(int id_server, String web){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); stmt = con.prepareStatement("INSERT INTO dominios (id_servidor, web) VALUES(?,?);"); stmt.setInt(1, id_server); stmt.setString(2, web); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * list domain of the server specified * @param id_server */ Vector listDomains(int id_server){ Connection con = null; PreparedStatement stmt = null; int id_domain=-1; String name=null; Vector res=new Vector(); try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT * FROM dominios WHERE id_servidor='"); query.append(id_server); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs; rs = stmt.executeQuery(); while(rs.next()){ id_domain=rs.getInt("id_dominio"); name=rs.getString("web"); res.addElement(new DataDomain(id_server,id_domain,name)); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } return res; } } /** * Erase domain */ void removeDomain(int id_domain){ Connection con = null; PreparedStatement stmt = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("DELETE FROM dominios WHERE id_dominio='"); query.append(id_domain); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); stmt.executeUpdate(); } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } } /** * @param id_domain * @return The data of the domain specified by id */ public DataDomain consultDomain(int id_domain){ Connection con = null; PreparedStatement stmt = null; int id_server = 0; String web = null; try{ Class.forName(sDriver).newInstance(); con = DriverManager.getConnection(sURL,user,pass); StringBuilder query = new StringBuilder("SELECT * FROM dominios WHERE id_dominio='"); query.append(id_domain); query.append("'"); String queryfinal = new String(query); stmt = con.prepareStatement(queryfinal); ResultSet rs = stmt.executeQuery(); if(rs.next()){ web=rs.getString("web"); id_server=rs.getInt("id_servidor"); } } catch (SQLException sqle){ System.out.println("SQLState: " + sqle.getSQLState()); System.out.println("SQLErrorCode: " + sqle.getErrorCode()); sqle.printStackTrace(); } catch (Exception e){ e.printStackTrace(); } finally { if (con != null) { try{ stmt.close(); con.close(); } catch(Exception e){ e.printStackTrace(); } } } return new DataDomain(id_server, id_domain, web); } }
Corregido error en 'apellido'
SEKEGEX/src/sekegex/MySQLTools.java
Corregido error en 'apellido'
<ide><path>EKEGEX/src/sekegex/MySQLTools.java <ide> if(!first){ <ide> query.append(","); <ide> } <del> query.append("apellido='"); <add> query.append("apellidos='"); <ide> query.append(surname); <ide> query.append("'"); <ide>
Java
apache-2.0
3d714fa2384f93dab0ed1f7cc5b0184281a1a07b
0
benchdoos/WeblocOpener,benchdoos/WeblocOpener,benchdoos/WeblocOpener
package com.doos.settings_manager; import java.io.File; /** * Created by Eugene Zrazhevsky on 30.10.2016. */ public interface ApplicationConstants { String APP_NAME = "WeblocOpener"; String APP_VERSION = "1.2.3"; String APP_LOG_FOLDER_PATH = System.getProperty("java.io.tmpdir") + APP_NAME + File.separator + "Log"; String APP_LOG_PROPERTY = "WeblocOpener.log.folder"; String UPDATE_PATH_FILE = System.getProperty("java.io.tmpdir") + APP_NAME + File.separator; String UPDATE_WEB_URL = "https://github.com/benchdoos/WeblocOpener/"; boolean IS_APP_AUTO_UPDATE_DEFAULT_VALUE = true; String APP_ID = "{F1300E10-BBB2-4695-AC2F-3D58DC0BC0A6}_is1"; String APP_INSTALL_SILENT_KEY = " /VERYSILENT"; String UPDATE_SILENT_ARGUMENT = "-s"; String UPDATE_DELETE_TEMP_FILE_ARGUMENT = "-clean"; String OPENER_EDIT_ARGUMENT = "-edit"; String OPENER_SETTINGS_ARGUMENT = "-settings"; }
SettingsManager/src/com/doos/settings_manager/ApplicationConstants.java
package com.doos.settings_manager; import java.io.File; /** * Created by Eugene Zrazhevsky on 30.10.2016. */ public interface ApplicationConstants { String APP_NAME = "WeblocOpener"; String APP_VERSION = "1.2.2"; String APP_LOG_FOLDER_PATH = System.getProperty("java.io.tmpdir") + APP_NAME + File.separator + "Log"; String APP_LOG_PROPERTY = "WeblocOpener.log.folder"; String UPDATE_PATH_FILE = System.getProperty("java.io.tmpdir") + APP_NAME + File.separator; String UPDATE_WEB_URL = "https://github.com/benchdoos/WeblocOpener/"; boolean IS_APP_AUTO_UPDATE_DEFAULT_VALUE = true; String APP_ID = "{F1300E10-BBB2-4695-AC2F-3D58DC0BC0A6}_is1"; String APP_INSTALL_SILENT_KEY = " /VERYSILENT"; String UPDATE_SILENT_ARGUMENT = "-s"; String UPDATE_DELETE_TEMP_FILE_ARGUMENT = "-clean"; String OPENER_EDIT_ARGUMENT = "-edit"; String OPENER_SETTINGS_ARGUMENT = "-settings"; }
Updated version
SettingsManager/src/com/doos/settings_manager/ApplicationConstants.java
Updated version
<ide><path>ettingsManager/src/com/doos/settings_manager/ApplicationConstants.java <ide> */ <ide> public interface ApplicationConstants { <ide> String APP_NAME = "WeblocOpener"; <del> String APP_VERSION = "1.2.2"; <add> String APP_VERSION = "1.2.3"; <ide> String APP_LOG_FOLDER_PATH = System.getProperty("java.io.tmpdir") + APP_NAME + File.separator + "Log"; <ide> String APP_LOG_PROPERTY = "WeblocOpener.log.folder"; <ide> String UPDATE_PATH_FILE = System.getProperty("java.io.tmpdir") + APP_NAME + File.separator;
Java
apache-2.0
99d79397d93b5e1ae780d216256124d66dfa10ab
0
ringdna/jitsi,gpolitis/jitsi,459below/jitsi,bebo/jitsi,dkcreinoso/jitsi,dkcreinoso/jitsi,gpolitis/jitsi,pplatek/jitsi,mckayclarey/jitsi,procandi/jitsi,laborautonomo/jitsi,iant-gmbh/jitsi,gpolitis/jitsi,cobratbq/jitsi,level7systems/jitsi,ibauersachs/jitsi,cobratbq/jitsi,pplatek/jitsi,jitsi/jitsi,damencho/jitsi,jitsi/jitsi,jibaro/jitsi,ringdna/jitsi,iant-gmbh/jitsi,ringdna/jitsi,pplatek/jitsi,HelioGuilherme66/jitsi,level7systems/jitsi,bhatvv/jitsi,dkcreinoso/jitsi,ringdna/jitsi,damencho/jitsi,level7systems/jitsi,HelioGuilherme66/jitsi,bhatvv/jitsi,jibaro/jitsi,pplatek/jitsi,459below/jitsi,procandi/jitsi,HelioGuilherme66/jitsi,mckayclarey/jitsi,459below/jitsi,ringdna/jitsi,ibauersachs/jitsi,jitsi/jitsi,pplatek/jitsi,marclaporte/jitsi,bhatvv/jitsi,procandi/jitsi,marclaporte/jitsi,Metaswitch/jitsi,damencho/jitsi,procandi/jitsi,mckayclarey/jitsi,bhatvv/jitsi,ibauersachs/jitsi,iant-gmbh/jitsi,marclaporte/jitsi,tuijldert/jitsi,bebo/jitsi,gpolitis/jitsi,laborautonomo/jitsi,laborautonomo/jitsi,jitsi/jitsi,iant-gmbh/jitsi,damencho/jitsi,tuijldert/jitsi,jibaro/jitsi,procandi/jitsi,dkcreinoso/jitsi,jibaro/jitsi,HelioGuilherme66/jitsi,martin7890/jitsi,bhatvv/jitsi,damencho/jitsi,martin7890/jitsi,bebo/jitsi,level7systems/jitsi,marclaporte/jitsi,459below/jitsi,mckayclarey/jitsi,jitsi/jitsi,mckayclarey/jitsi,iant-gmbh/jitsi,laborautonomo/jitsi,Metaswitch/jitsi,bebo/jitsi,459below/jitsi,tuijldert/jitsi,dkcreinoso/jitsi,martin7890/jitsi,HelioGuilherme66/jitsi,ibauersachs/jitsi,bebo/jitsi,gpolitis/jitsi,tuijldert/jitsi,cobratbq/jitsi,ibauersachs/jitsi,level7systems/jitsi,marclaporte/jitsi,tuijldert/jitsi,laborautonomo/jitsi,martin7890/jitsi,martin7890/jitsi,cobratbq/jitsi,cobratbq/jitsi,Metaswitch/jitsi,Metaswitch/jitsi,jibaro/jitsi
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.media; //~--- non-JDK imports -------------------------------------------------------- import net.java.sip.communicator.util.*; //~--- JDK imports ------------------------------------------------------------ import javax.media.*; /** * A utility class that provides utility functions when working with processors. * * @author Emil Ivov * @author Ken Larson */ public class ProcessorUtility implements ControllerListener { private Logger logger = Logger.getLogger(ProcessorUtility.class); /** * The object that we use for syncing when waiting for a processor * to enter a specific state. */ private Object stateLock = new Object(); private boolean failed = false; /** * Default constructor, creates an instance of the of the Processor utility. */ public ProcessorUtility() {} /** * Returns the object that we use for syncing when waiting for a processor * to enter a specific state. * @return Integer */ private Object getStateLock() { return stateLock; } /** * Specifies whether the wait operation has failed or completed with * success. * * @param failed true if waiting has failed and false otherwise. */ private void setFailed(boolean failed) { this.failed = failed; } /** * This method is called when an event is generated by a * <code>Controller</code> that this listener is registered with. We use * the event to notify all waiting on our lock and record success or * failure. * * @param ce The event generated. */ public void controllerUpdate(ControllerEvent ce) { // If there was an error during configure or // realize, the processor will be closed if (ce instanceof ControllerClosedEvent) { if (ce instanceof ControllerErrorEvent) { logger.warn("ControllerErrorEvent: " + ce); } else { logger.debug("ControllerClosedEvent: " + ce); } setFailed(true); // All controller events, send a notification // to the waiting thread in waitForState method. } if (ce instanceof ControllerEvent) { synchronized (getStateLock()) { getStateLock().notifyAll(); } } } /** * Waits until <tt>processor</tt> enters state and returns a boolean * indicating success or failure of the operation. * * @param processor Processor * @param state one of the Processor.XXXed sate vars * @return boolean true if the state has been reached and false otherwise */ public synchronized boolean waitForState(Processor processor, int state) { processor.addControllerListener(this); setFailed(false); // Call the required method on the processor if (state == Processor.Configured) { processor.configure(); } else if (state == Processor.Realized) { processor.realize(); } // Wait until we get an event that confirms the // success of the method, or a failure event. // See StateListener inner class while ((processor.getState() < state) &&!failed) { synchronized (getStateLock()) { try { getStateLock().wait(); } catch (InterruptedException ie) { return false; } } } return !failed; } } //~ Formatted by Jindent --- http://www.jindent.com
src/net/java/sip/communicator/impl/media/ProcessorUtility.java
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.media; //~--- non-JDK imports -------------------------------------------------------- import net.java.sip.communicator.util.*; //~--- JDK imports ------------------------------------------------------------ import javax.media.*; /** * A utility class that provides utility functions when working with processors. * * @author Emil Ivov * @author Ken Larson */ public class ProcessorUtility implements ControllerListener { private Logger logger = Logger.getLogger(ProcessorUtility.class); /** * The object that we use for syncing when waiting for a processor * to enter a specific state. */ private Object stateLock = new Object(); private boolean failed = false; /** * Default constructor, creates an instance of the of the Processor utility. */ public ProcessorUtility() {} /** * Returns the object that we use for syncing when waiting for a processor * to enter a specific state. * @return Integer */ private Object getStateLock() { return stateLock; } /** * Specifies whether the wait operation has failed or completed with * success. * * @param failed true if waiting has failed and false otherwise. */ private void setFailed(boolean failed) { this.failed = failed; } /** * This method is called when an event is generated by a * <code>Controller</code> that this listener is registered with. We use * the event to notify all waiting on our lock and record success or * failure. * * @param ce The event generated. */ public void controllerUpdate(ControllerEvent ce) { // If there was an error during configure or // realize, the processor will be closed if (ce instanceof ControllerClosedEvent) { if (ce instanceof ControllerErrorEvent) { logger.warn("ControllerErrorEvent: " + ce); } else { logger.debug("ControllerClosedEvent: " + ce); } setFailed(true); // All controller events, send a notification // to the waiting thread in waitForState method. } if (ce instanceof ControllerEvent) { synchronized (getStateLock()) { getStateLock().notifyAll(); } } } /** * Waits until <tt>processor</tt> enters state and returns a boolean * indicating success or failure of the operation. * * @param processor Processor * @param state one of the Processor.XXXed sate vars * @return boolean true if the state has been reached and false otherwise */ public synchronized boolean waitForState(Processor processor, int state) { System.out.println("d1"); processor.addControllerListener(this); setFailed(false); // Call the required method on the processor if (state == Processor.Configured) { processor.configure(); } else if (state == Processor.Realized) { processor.realize(); } // Wait until we get an event that confirms the // success of the method, or a failure event. // See StateListener inner class while ((processor.getState() < state) &&!failed) { synchronized (getStateLock()) { try { getStateLock().wait(); } catch (InterruptedException ie) { return false; } } } return !failed; } } //~ Formatted by Jindent --- http://www.jindent.com
Removes a mistakenly committed System.out.println()
src/net/java/sip/communicator/impl/media/ProcessorUtility.java
Removes a mistakenly committed System.out.println()
<ide><path>rc/net/java/sip/communicator/impl/media/ProcessorUtility.java <ide> */ <ide> public synchronized boolean waitForState(Processor processor, int state) <ide> { <del> System.out.println("d1"); <ide> processor.addControllerListener(this); <ide> setFailed(false); <ide>
JavaScript
apache-2.0
edf776e0cba4769cf89c79de547566bec2a76150
0
zitang/actionhero,BoLaMN/actionhero,mboudreau/actionhero,gcoonrod/actionhero,witem/actionhero,BoLaMN/actionhero,supamii/actionhero,BoLaMN/actionhero,supamii/actionhero,gcoonrod/actionhero,insfere/actionhero,insfere/actionhero,actionhero/actionhero,gcoonrod/actionhero,witem/actionhero,jahraphael/actionhero,anjuncc/actionhero,GoranDimchevski/actionhero,crrobinson14/actionhero,GoranDimchevski/actionhero,zarnold/actionhero,kediacorporation/actionhero,crrobinson14/actionhero,dangerdespain/actionhero,jahraphael/actionhero,zitang/actionhero,kodypeterson/actionhero,S3bb1/actionhero,zarnold/actionhero,dangerdespain/actionhero,zitang/actionhero,dangerdespain/actionhero,jahraphael/actionhero,dangerdespain/actionhero,witem/actionhero,insfere/actionhero,actionhero/actionhero,witem/actionhero,chimmelb/actionhero,GoranDimchevski/actionhero,S3bb1/actionhero,supamii/actionhero,katopz/actionhero,katopz/actionhero,zarnold/actionhero,katopz/actionhero,vkarampinis/actionhero,actionhero/actionhero,supamii/actionhero,crrobinson14/actionhero,gcoonrod/actionhero,kediacorporation/actionhero,mboudreau/actionhero,S3bb1/actionhero,kodypeterson/actionhero,kodypeterson/actionhero,vkarampinis/actionhero,chimmelb/actionhero,chimmelb/actionhero,vkarampinis/actionhero,mboudreau/actionhero,anjuncc/actionhero,actionhero/actionhero,anjuncc/actionhero
var fs = require('fs'); var routes = function(api, next){ api.routes = {}; api.routes.routes = {}; api.routes.routesFile = api.project_root + '/routes.js'; //////////////////////////////////////////////////////////////////////////// // route processing for web clients api.routes.processRoute = function(connection){ if(connection.params['action'] == null || typeof api.actions.actions[connection.params['action']] === 'undefined'){ var method = connection.rawConnection.method.toLowerCase(); for(var i in api.routes.routes[method]){ var route = api.routes.routes[method][i]; var match = api.routes.matchURL(connection.rawConnection.parsedURL.pathname, route.path); if(match.match === true){ for(var param in match.params){ var decodedName = decodeURIComponent(param.replace(/\+/g, ' ')); var decodedValue = decodeURIComponent(match.params[param].replace(/\+/g, ' ')); connection.params[decodedName] = decodedValue; } connection.params['action'] = route.action; break; } } } } api.routes.matchURL = function(url, match){ var response = {match: false, params: {} } var urlParts = url.split('/'); var matchParts = match.split('/'); var regexp = ''; var variable = ''; if(urlParts[0] == ''){ urlParts.splice(0, 1) } if(matchParts[0] == ''){ matchParts.splice(0, 1) } if(urlParts[(urlParts.length - 1)] == ''){ urlParts.pop() } if(matchParts[(matchParts.length - 1)] == ''){ matchParts.pop() } if(urlParts[0] == api.config.servers.web.urlPathForActions){ urlParts.splice(0, 1) } for(var i in matchParts){ var part = matchParts[i]; if(!urlParts[i]){ return response; } else if(part[0] === ':' && part.indexOf('(') < 0){ variable = part.replace(':', ''); response.params[variable] = urlParts[i]; } else if(part[0] === ':' && part.indexOf('(') >= 0){ variable = part.replace(':', '').split('(')[0]; regexp = part.split('(')[1]; var matches = urlParts[i].match(new RegExp(regexp.substring(0, regexp.length - 1), 'g')); if(matches != null){ response.params[variable] = urlParts[i]; } else { return response; } } else { if(urlParts[i] == null || urlParts[i].toLowerCase() != matchParts[i].toLowerCase()){ return response; } } } response.match = true; return response; } // load in the routes file api.routes.loadRoutes = function(rawRoutes){ var counter = 0; api.routes.routes = { 'get': [], 'post': [], 'put': [], 'delete': [] }; if(rawRoutes == null){ if(fs.existsSync(api.routes.routesFile)){ delete require.cache[require.resolve(api.routes.routesFile)]; rawRoutes = require(api.routes.routesFile).routes; } else { api.log('no routes file found, skipping', 'debug'); return; } } for(var i in rawRoutes){ var method = i.toLowerCase(); for(var j in rawRoutes[i]){ var route = rawRoutes[i][j]; if(method == 'all'){ ['get', 'post', 'put', 'delete'].forEach(function(verb){ api.routes.routes[verb].push({ path: route.path, action: route.action }); }); } else { api.routes.routes[method].push({ path: route.path, action: route.action }); } var words = route.path.split('/'); words.forEach(function(word){ if(word[0] === ':'){ var cleanedWord = word.replace(':', ''); api.params.postVariables.push(cleanedWord); } }); counter++; } } api.params.postVariables = api.utils.arrayUniqueify(api.params.postVariables) api.log(counter + ' routes loaded from ' + api.routes.routesFile, 'debug', api.routes.routes); }; api.watchFileAndAct(api.routes.routesFile, function(){ api.routes.loadRoutes(); }); api.routes.loadRoutes(); next(); } ///////////////////////////////////////////////////////////////////// // exports exports.routes = routes;
initializers/routes.js
var fs = require('fs'); var routes = function(api, next){ api.routes = {}; api.routes.routes = {}; api.routes.routesFile = api.project_root + '/routes.js'; //////////////////////////////////////////////////////////////////////////// // route processing for web clients api.routes.processRoute = function(connection){ if(connection.params['action'] == null || typeof api.actions.actions[connection.params['action']] === 'undefined'){ var method = connection.rawConnection.method.toLowerCase(); for(var i in api.routes.routes[method]){ var route = api.routes.routes[method][i]; var match = api.routes.matchURL(connection.rawConnection.parsedURL.pathname, route.path); if(match.match === true){ for(var param in match.params){ connection.params[param] = match.params[param]; } connection.params['action'] = route.action; break; } } } } api.routes.matchURL = function(url, match){ var response = {match: false, params: {} } var urlParts = url.split('/'); var matchParts = match.split('/'); var regexp = ''; var variable = ''; if(urlParts[0] == ''){ urlParts.splice(0, 1) } if(matchParts[0] == ''){ matchParts.splice(0, 1) } if(urlParts[(urlParts.length - 1)] == ''){ urlParts.pop() } if(matchParts[(matchParts.length - 1)] == ''){ matchParts.pop() } if(urlParts[0] == api.config.servers.web.urlPathForActions){ urlParts.splice(0, 1) } for(var i in matchParts){ var part = matchParts[i]; if(!urlParts[i]){ return response; } else if(part[0] === ':' && part.indexOf('(') < 0){ variable = part.replace(':', ''); response.params[variable] = urlParts[i]; } else if(part[0] === ':' && part.indexOf('(') >= 0){ variable = part.replace(':', '').split('(')[0]; regexp = part.split('(')[1]; var matches = urlParts[i].match(new RegExp(regexp.substring(0, regexp.length - 1), 'g')); if(matches != null){ response.params[variable] = urlParts[i]; } else { return response; } } else { if(urlParts[i] == null || urlParts[i].toLowerCase() != matchParts[i].toLowerCase()){ return response; } } } response.match = true; return response; } // load in the routes file api.routes.loadRoutes = function(rawRoutes){ var counter = 0; api.routes.routes = { 'get': [], 'post': [], 'put': [], 'delete': [] }; if(rawRoutes == null){ if(fs.existsSync(api.routes.routesFile)){ delete require.cache[require.resolve(api.routes.routesFile)]; rawRoutes = require(api.routes.routesFile).routes; } else { api.log('no routes file found, skipping', 'debug'); return; } } for(var i in rawRoutes){ var method = i.toLowerCase(); for(var j in rawRoutes[i]){ var route = rawRoutes[i][j]; if(method == 'all'){ ['get', 'post', 'put', 'delete'].forEach(function(verb){ api.routes.routes[verb].push({ path: route.path, action: route.action }); }); } else { api.routes.routes[method].push({ path: route.path, action: route.action }); } var words = route.path.split('/'); words.forEach(function(word){ if(word[0] === ':'){ var cleanedWord = word.replace(':', ''); api.params.postVariables.push(cleanedWord); } }); counter++; } } api.params.postVariables = api.utils.arrayUniqueify(api.params.postVariables) api.log(counter + ' routes loaded from ' + api.routes.routesFile, 'debug', api.routes.routes); }; api.watchFileAndAct(api.routes.routesFile, function(){ api.routes.loadRoutes(); }); api.routes.loadRoutes(); next(); } ///////////////////////////////////////////////////////////////////// // exports exports.routes = routes;
decoding parameters
initializers/routes.js
decoding parameters
<ide><path>nitializers/routes.js <ide> var match = api.routes.matchURL(connection.rawConnection.parsedURL.pathname, route.path); <ide> if(match.match === true){ <ide> for(var param in match.params){ <del> connection.params[param] = match.params[param]; <add> var decodedName = decodeURIComponent(param.replace(/\+/g, ' ')); <add> var decodedValue = decodeURIComponent(match.params[param].replace(/\+/g, ' ')); <add> connection.params[decodedName] = decodedValue; <ide> } <ide> connection.params['action'] = route.action; <ide> break;
Java
mit
c7cedde18ac11dd718c47964825d5cf9c4d44c1a
0
iseki-masaya/spongycastle,sergeypayu/bc-java,iseki-masaya/spongycastle,onessimofalconi/bc-java,lesstif/spongycastle,sergeypayu/bc-java,savichris/spongycastle,sonork/spongycastle,isghe/bc-java,lesstif/spongycastle,savichris/spongycastle,open-keychain/spongycastle,savichris/spongycastle,bcgit/bc-java,partheinstein/bc-java,open-keychain/spongycastle,FAU-Inf2/spongycastle,partheinstein/bc-java,onessimofalconi/bc-java,sonork/spongycastle,iseki-masaya/spongycastle,Skywalker-11/spongycastle,partheinstein/bc-java,Skywalker-11/spongycastle,Skywalker-11/spongycastle,sonork/spongycastle,bcgit/bc-java,onessimofalconi/bc-java,sergeypayu/bc-java,FAU-Inf2/spongycastle,isghe/bc-java,open-keychain/spongycastle,lesstif/spongycastle,FAU-Inf2/spongycastle,isghe/bc-java,bcgit/bc-java
package org.bouncycastle.math.ec; import java.math.BigInteger; import java.util.Random; import org.bouncycastle.util.BigIntegers; public abstract class ECFieldElement implements ECConstants { public abstract BigInteger toBigInteger(); public abstract String getFieldName(); public abstract int getFieldSize(); public abstract ECFieldElement add(ECFieldElement b); public abstract ECFieldElement subtract(ECFieldElement b); public abstract ECFieldElement multiply(ECFieldElement b); public abstract ECFieldElement divide(ECFieldElement b); public abstract ECFieldElement negate(); public abstract ECFieldElement square(); public abstract ECFieldElement invert(); public abstract ECFieldElement sqrt(); public int bitLength() { return toBigInteger().bitLength(); } public boolean isZero() { return 0 == toBigInteger().signum(); } public boolean testBitZero() { return toBigInteger().testBit(0); } public String toString() { return this.toBigInteger().toString(16); } public byte[] getEncoded() { return BigIntegers.asUnsignedByteArray((getFieldSize() + 7) / 8, toBigInteger()); } public static class Fp extends ECFieldElement { BigInteger q, r, x; // static int[] calculateNaf(BigInteger p) // { // int[] naf = WNafUtil.generateCompactNaf(p); // // int bit = 0; // for (int i = 0; i < naf.length; ++i) // { // int ni = naf[i]; // int digit = ni >> 16, zeroes = ni & 0xFFFF; // // bit += zeroes; // naf[i] = digit < 0 ? ~bit : bit; // ++bit; // } // // int last = naf.length - 1; // if (last > 0 && last <= 16) // { // int top = naf[last], top2 = naf[last - 1]; // if (top2 < 0) // { // top2 = ~top2; // } // if (top - top2 >= 64) // { // return naf; // } // } // // return null; // } static BigInteger calculateResidue(BigInteger p) { int bitLength = p.bitLength(); if (bitLength > 128) { BigInteger firstWord = p.shiftRight(bitLength - 64); if (firstWord.longValue() == -1L) { return ONE.shiftLeft(bitLength).subtract(p); } } return null; } /** * @deprecated Use ECCurve.fromBigInteger to construct field elements */ public Fp(BigInteger q, BigInteger x) { this(q, calculateResidue(q), x); } Fp(BigInteger q, BigInteger r, BigInteger x) { if (x == null || x.signum() < 0 || x.compareTo(q) >= 0) { throw new IllegalArgumentException("x value invalid in Fp field element"); } this.q = q; this.r = r; this.x = x; } public BigInteger toBigInteger() { return x; } /** * return the field name for this field. * * @return the string "Fp". */ public String getFieldName() { return "Fp"; } public int getFieldSize() { return q.bitLength(); } public BigInteger getQ() { return q; } public ECFieldElement add(ECFieldElement b) { return new Fp(q, r, modAdd(x, b.toBigInteger())); } public ECFieldElement subtract(ECFieldElement b) { BigInteger x2 = b.toBigInteger(); BigInteger x3 = x.subtract(x2); if (x3.signum() < 0) { x3 = x3.add(q); } return new Fp(q, r, x3); } public ECFieldElement multiply(ECFieldElement b) { return new Fp(q, r, modMult(x, b.toBigInteger())); } public ECFieldElement divide(ECFieldElement b) { return new Fp(q, modMult(x, b.toBigInteger().modInverse(q))); } public ECFieldElement negate() { BigInteger x2; if (x.signum() == 0) { x2 = x; } else if (ONE.equals(r)) { x2 = q.xor(x); } else { x2 = q.subtract(x); } return new Fp(q, r, x2); } public ECFieldElement square() { return new Fp(q, r, modMult(x, x)); } public ECFieldElement invert() { // TODO Modular inversion can be faster for a (Generalized) Mersenne Prime. return new Fp(q, r, x.modInverse(q)); } // D.1.4 91 /** * return a sqrt root - the routine verifies that the calculation * returns the right value - if none exists it returns null. */ public ECFieldElement sqrt() { if (!q.testBit(0)) { throw new RuntimeException("not done yet"); } // note: even though this class implements ECConstants don't be tempted to // remove the explicit declaration, some J2ME environments don't cope. // p mod 4 == 3 if (q.testBit(1)) { // z = g^(u+1) + p, p = 4u + 3 ECFieldElement z = new Fp(q, r, x.modPow(q.shiftRight(2).add(ECConstants.ONE), q)); return z.square().equals(this) ? z : null; } // p mod 4 == 1 BigInteger qMinusOne = q.subtract(ECConstants.ONE); BigInteger legendreExponent = qMinusOne.shiftRight(1); if (!(x.modPow(legendreExponent, q).equals(ECConstants.ONE))) { return null; } BigInteger u = qMinusOne.shiftRight(2); BigInteger k = u.shiftLeft(1).add(ECConstants.ONE); BigInteger Q = this.x; BigInteger fourQ = modDouble(modDouble(Q)); BigInteger U, V; Random rand = new Random(); do { BigInteger P; do { P = new BigInteger(q.bitLength(), rand); } while (P.compareTo(q) >= 0 || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, q).equals(qMinusOne))); BigInteger[] result = lucasSequence(P, Q, k); U = result[0]; V = result[1]; if (modMult(V, V).equals(fourQ)) { // Integer division by 2, mod q if (V.testBit(0)) { V = V.add(q); } V = V.shiftRight(1); //assert V.multiply(V).mod(q).equals(x); return new ECFieldElement.Fp(q, r, V); } } while (U.equals(ECConstants.ONE) || U.equals(qMinusOne)); return null; // BigInteger qMinusOne = q.subtract(ECConstants.ONE); // BigInteger legendreExponent = qMinusOne.shiftRight(1); //divide(ECConstants.TWO); // if (!(x.modPow(legendreExponent, q).equals(ECConstants.ONE))) // { // return null; // } // // Random rand = new Random(); // BigInteger fourX = x.shiftLeft(2); // // BigInteger r; // do // { // r = new BigInteger(q.bitLength(), rand); // } // while (r.compareTo(q) >= 0 // || !(r.multiply(r).subtract(fourX).modPow(legendreExponent, q).equals(qMinusOne))); // // BigInteger n1 = qMinusOne.shiftRight(2); //.divide(ECConstants.FOUR); // BigInteger n2 = n1.add(ECConstants.ONE); //q.add(ECConstants.THREE).divide(ECConstants.FOUR); // // BigInteger wOne = WOne(r, x, q); // BigInteger wSum = W(n1, wOne, q).add(W(n2, wOne, q)).mod(q); // BigInteger twoR = r.shiftLeft(1); //ECConstants.TWO.multiply(r); // // BigInteger root = twoR.modPow(q.subtract(ECConstants.TWO), q) // .multiply(x).mod(q) // .multiply(wSum).mod(q); // // return new Fp(q, root); } // private static BigInteger W(BigInteger n, BigInteger wOne, BigInteger p) // { // if (n.equals(ECConstants.ONE)) // { // return wOne; // } // boolean isEven = !n.testBit(0); // n = n.shiftRight(1);//divide(ECConstants.TWO); // if (isEven) // { // BigInteger w = W(n, wOne, p); // return w.multiply(w).subtract(ECConstants.TWO).mod(p); // } // BigInteger w1 = W(n.add(ECConstants.ONE), wOne, p); // BigInteger w2 = W(n, wOne, p); // return w1.multiply(w2).subtract(wOne).mod(p); // } // // private BigInteger WOne(BigInteger r, BigInteger x, BigInteger p) // { // return r.multiply(r).multiply(x.modPow(q.subtract(ECConstants.TWO), q)).subtract(ECConstants.TWO).mod(p); // } private BigInteger[] lucasSequence( BigInteger P, BigInteger Q, BigInteger k) { int n = k.bitLength(); int s = k.getLowestSetBit(); BigInteger Uh = ECConstants.ONE; BigInteger Vl = ECConstants.TWO; BigInteger Vh = P; BigInteger Ql = ECConstants.ONE; BigInteger Qh = ECConstants.ONE; for (int j = n - 1; j >= s + 1; --j) { Ql = modMult(Ql, Qh); if (k.testBit(j)) { Qh = modMult(Ql, Q); Uh = modMult(Uh, Vh); Vl = modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); Vh = modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1))); } else { Qh = Ql; Uh = modReduce(Uh.multiply(Vl).subtract(Ql)); Vh = modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); Vl = modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); } } Ql = modMult(Ql, Qh); Qh = modMult(Ql, Q); Uh = modReduce(Uh.multiply(Vl).subtract(Ql)); Vl = modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); Ql = modMult(Ql, Qh); for (int j = 1; j <= s; ++j) { Uh = modMult(Uh, Vl); Vl = modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); Ql = modMult(Ql, Ql); } return new BigInteger[]{ Uh, Vl }; } protected BigInteger modAdd(BigInteger x1, BigInteger x2) { BigInteger x3 = x1.add(x2); if (x3.compareTo(q) >= 0) { x3 = x3.subtract(q); } return x3; } protected BigInteger modDouble(BigInteger x) { BigInteger _2x = x.shiftLeft(1); if (_2x.compareTo(q) >= 0) { _2x = _2x.subtract(q); } return _2x; } protected BigInteger modMult(BigInteger x1, BigInteger x2) { return modReduce(x1.multiply(x2)); } protected BigInteger modReduce(BigInteger x) { // if (naf != null) // { // int last = naf.length - 1; // int bits = naf[last]; // while (x.bitLength() > (bits + 1)) // { // BigInteger u = x.shiftRight(bits); // BigInteger v = x.subtract(u.shiftLeft(bits)); // // x = v; // // for (int i = 0; i < last; ++i) // { // int ni = naf[i]; // if (ni < 0) // { // x = x.add(u.shiftLeft(~ni)); // } // else // { // x = x.subtract(u.shiftLeft(ni)); // } // } // } // while (x.compareTo(q) >= 0) // { // x = x.subtract(q); // } // } // else if (r != null) { int qLen = q.bitLength(); while (x.bitLength() > (qLen + 1)) { BigInteger u = x.shiftRight(qLen); BigInteger v = x.subtract(u.shiftLeft(qLen)); if (!r.equals(ONE)) { u = u.multiply(r); } x = u.add(v); } while (x.compareTo(q) >= 0) { x = x.subtract(q); } } else { x = x.mod(q); } return x; } public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof ECFieldElement.Fp)) { return false; } ECFieldElement.Fp o = (ECFieldElement.Fp)other; return q.equals(o.q) && x.equals(o.x); } public int hashCode() { return q.hashCode() ^ x.hashCode(); } } // /** // * Class representing the Elements of the finite field // * <code>F<sub>2<sup>m</sup></sub></code> in polynomial basis (PB) // * representation. Both trinomial (TPB) and pentanomial (PPB) polynomial // * basis representations are supported. Gaussian normal basis (GNB) // * representation is not supported. // */ // public static class F2m extends ECFieldElement // { // BigInteger x; // // /** // * Indicates gaussian normal basis representation (GNB). Number chosen // * according to X9.62. GNB is not implemented at present. // */ // public static final int GNB = 1; // // /** // * Indicates trinomial basis representation (TPB). Number chosen // * according to X9.62. // */ // public static final int TPB = 2; // // /** // * Indicates pentanomial basis representation (PPB). Number chosen // * according to X9.62. // */ // public static final int PPB = 3; // // /** // * TPB or PPB. // */ // private int representation; // // /** // * The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>. // */ // private int m; // // /** // * TPB: The integer <code>k</code> where <code>x<sup>m</sup> + // * x<sup>k</sup> + 1</code> represents the reduction polynomial // * <code>f(z)</code>.<br> // * PPB: The integer <code>k1</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br> // */ // private int k1; // // /** // * TPB: Always set to <code>0</code><br> // * PPB: The integer <code>k2</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br> // */ // private int k2; // // /** // * TPB: Always set to <code>0</code><br> // * PPB: The integer <code>k3</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br> // */ // private int k3; // // /** // * Constructor for PPB. // * @param m The exponent <code>m</code> of // * <code>F<sub>2<sup>m</sup></sub></code>. // * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>. // * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>. // * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>. // * @param x The BigInteger representing the value of the field element. // */ // public F2m( // int m, // int k1, // int k2, // int k3, // BigInteger x) // { //// super(x); // this.x = x; // // if ((k2 == 0) && (k3 == 0)) // { // this.representation = TPB; // } // else // { // if (k2 >= k3) // { // throw new IllegalArgumentException( // "k2 must be smaller than k3"); // } // if (k2 <= 0) // { // throw new IllegalArgumentException( // "k2 must be larger than 0"); // } // this.representation = PPB; // } // // if (x.signum() < 0) // { // throw new IllegalArgumentException("x value cannot be negative"); // } // // this.m = m; // this.k1 = k1; // this.k2 = k2; // this.k3 = k3; // } // // /** // * Constructor for TPB. // * @param m The exponent <code>m</code> of // * <code>F<sub>2<sup>m</sup></sub></code>. // * @param k The integer <code>k</code> where <code>x<sup>m</sup> + // * x<sup>k</sup> + 1</code> represents the reduction // * polynomial <code>f(z)</code>. // * @param x The BigInteger representing the value of the field element. // */ // public F2m(int m, int k, BigInteger x) // { // // Set k1 to k, and set k2 and k3 to 0 // this(m, k, 0, 0, x); // } // // public BigInteger toBigInteger() // { // return x; // } // // public String getFieldName() // { // return "F2m"; // } // // public int getFieldSize() // { // return m; // } // // /** // * Checks, if the ECFieldElements <code>a</code> and <code>b</code> // * are elements of the same field <code>F<sub>2<sup>m</sup></sub></code> // * (having the same representation). // * @param a field element. // * @param b field element to be compared. // * @throws IllegalArgumentException if <code>a</code> and <code>b</code> // * are not elements of the same field // * <code>F<sub>2<sup>m</sup></sub></code> (having the same // * representation). // */ // public static void checkFieldElements( // ECFieldElement a, // ECFieldElement b) // { // if ((!(a instanceof F2m)) || (!(b instanceof F2m))) // { // throw new IllegalArgumentException("Field elements are not " // + "both instances of ECFieldElement.F2m"); // } // // if ((a.toBigInteger().signum() < 0) || (b.toBigInteger().signum() < 0)) // { // throw new IllegalArgumentException( // "x value may not be negative"); // } // // ECFieldElement.F2m aF2m = (ECFieldElement.F2m)a; // ECFieldElement.F2m bF2m = (ECFieldElement.F2m)b; // // if ((aF2m.m != bF2m.m) || (aF2m.k1 != bF2m.k1) // || (aF2m.k2 != bF2m.k2) || (aF2m.k3 != bF2m.k3)) // { // throw new IllegalArgumentException("Field elements are not " // + "elements of the same field F2m"); // } // // if (aF2m.representation != bF2m.representation) // { // // Should never occur // throw new IllegalArgumentException( // "One of the field " // + "elements are not elements has incorrect representation"); // } // } // // /** // * Computes <code>z * a(z) mod f(z)</code>, where <code>f(z)</code> is // * the reduction polynomial of <code>this</code>. // * @param a The polynomial <code>a(z)</code> to be multiplied by // * <code>z mod f(z)</code>. // * @return <code>z * a(z) mod f(z)</code> // */ // private BigInteger multZModF(final BigInteger a) // { // // Left-shift of a(z) // BigInteger az = a.shiftLeft(1); // if (az.testBit(this.m)) // { // // If the coefficient of z^m in a(z) equals 1, reduction // // modulo f(z) is performed: Add f(z) to to a(z): // // Step 1: Unset mth coeffient of a(z) // az = az.clearBit(this.m); // // // Step 2: Add r(z) to a(z), where r(z) is defined as // // f(z) = z^m + r(z), and k1, k2, k3 are the positions of // // the non-zero coefficients in r(z) // az = az.flipBit(0); // az = az.flipBit(this.k1); // if (this.representation == PPB) // { // az = az.flipBit(this.k2); // az = az.flipBit(this.k3); // } // } // return az; // } // // public ECFieldElement add(final ECFieldElement b) // { // // No check performed here for performance reasons. Instead the // // elements involved are checked in ECPoint.F2m // // checkFieldElements(this, b); // if (b.toBigInteger().signum() == 0) // { // return this; // } // // return new F2m(this.m, this.k1, this.k2, this.k3, this.x.xor(b.toBigInteger())); // } // // public ECFieldElement subtract(final ECFieldElement b) // { // // Addition and subtraction are the same in F2m // return add(b); // } // // // public ECFieldElement multiply(final ECFieldElement b) // { // // Left-to-right shift-and-add field multiplication in F2m // // Input: Binary polynomials a(z) and b(z) of degree at most m-1 // // Output: c(z) = a(z) * b(z) mod f(z) // // // No check performed here for performance reasons. Instead the // // elements involved are checked in ECPoint.F2m // // checkFieldElements(this, b); // final BigInteger az = this.x; // BigInteger bz = b.toBigInteger(); // BigInteger cz; // // // Compute c(z) = a(z) * b(z) mod f(z) // if (az.testBit(0)) // { // cz = bz; // } // else // { // cz = ECConstants.ZERO; // } // // for (int i = 1; i < this.m; i++) // { // // b(z) := z * b(z) mod f(z) // bz = multZModF(bz); // // if (az.testBit(i)) // { // // If the coefficient of x^i in a(z) equals 1, b(z) is added // // to c(z) // cz = cz.xor(bz); // } // } // return new ECFieldElement.F2m(m, this.k1, this.k2, this.k3, cz); // } // // // public ECFieldElement divide(final ECFieldElement b) // { // // There may be more efficient implementations // ECFieldElement bInv = b.invert(); // return multiply(bInv); // } // // public ECFieldElement negate() // { // // -x == x holds for all x in F2m // return this; // } // // public ECFieldElement square() // { // // Naive implementation, can probably be speeded up using modular // // reduction // return multiply(this); // } // // public ECFieldElement invert() // { // // Inversion in F2m using the extended Euclidean algorithm // // Input: A nonzero polynomial a(z) of degree at most m-1 // // Output: a(z)^(-1) mod f(z) // // // u(z) := a(z) // BigInteger uz = this.x; // if (uz.signum() <= 0) // { // throw new ArithmeticException("x is zero or negative, " + // "inversion is impossible"); // } // // // v(z) := f(z) // BigInteger vz = ECConstants.ZERO.setBit(m); // vz = vz.setBit(0); // vz = vz.setBit(this.k1); // if (this.representation == PPB) // { // vz = vz.setBit(this.k2); // vz = vz.setBit(this.k3); // } // // // g1(z) := 1, g2(z) := 0 // BigInteger g1z = ECConstants.ONE; // BigInteger g2z = ECConstants.ZERO; // // // while u != 1 // while (!(uz.equals(ECConstants.ZERO))) // { // // j := deg(u(z)) - deg(v(z)) // int j = uz.bitLength() - vz.bitLength(); // // // If j < 0 then: u(z) <-> v(z), g1(z) <-> g2(z), j := -j // if (j < 0) // { // final BigInteger uzCopy = uz; // uz = vz; // vz = uzCopy; // // final BigInteger g1zCopy = g1z; // g1z = g2z; // g2z = g1zCopy; // // j = -j; // } // // // u(z) := u(z) + z^j * v(z) // // Note, that no reduction modulo f(z) is required, because // // deg(u(z) + z^j * v(z)) <= max(deg(u(z)), j + deg(v(z))) // // = max(deg(u(z)), deg(u(z)) - deg(v(z)) + deg(v(z)) // // = deg(u(z)) // uz = uz.xor(vz.shiftLeft(j)); // // // g1(z) := g1(z) + z^j * g2(z) // g1z = g1z.xor(g2z.shiftLeft(j)); //// if (g1z.bitLength() > this.m) { //// throw new ArithmeticException( //// "deg(g1z) >= m, g1z = " + g1z.toString(16)); //// } // } // return new ECFieldElement.F2m( // this.m, this.k1, this.k2, this.k3, g2z); // } // // public ECFieldElement sqrt() // { // throw new RuntimeException("Not implemented"); // } // // /** // * @return the representation of the field // * <code>F<sub>2<sup>m</sup></sub></code>, either of // * TPB (trinomial // * basis representation) or // * PPB (pentanomial // * basis representation). // */ // public int getRepresentation() // { // return this.representation; // } // // /** // * @return the degree <code>m</code> of the reduction polynomial // * <code>f(z)</code>. // */ // public int getM() // { // return this.m; // } // // /** // * @return TPB: The integer <code>k</code> where <code>x<sup>m</sup> + // * x<sup>k</sup> + 1</code> represents the reduction polynomial // * <code>f(z)</code>.<br> // * PPB: The integer <code>k1</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br> // */ // public int getK1() // { // return this.k1; // } // // /** // * @return TPB: Always returns <code>0</code><br> // * PPB: The integer <code>k2</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br> // */ // public int getK2() // { // return this.k2; // } // // /** // * @return TPB: Always set to <code>0</code><br> // * PPB: The integer <code>k3</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br> // */ // public int getK3() // { // return this.k3; // } // // public boolean equals(Object anObject) // { // if (anObject == this) // { // return true; // } // // if (!(anObject instanceof ECFieldElement.F2m)) // { // return false; // } // // ECFieldElement.F2m b = (ECFieldElement.F2m)anObject; // // return ((this.m == b.m) && (this.k1 == b.k1) && (this.k2 == b.k2) // && (this.k3 == b.k3) // && (this.representation == b.representation) // && (this.x.equals(b.x))); // } // // public int hashCode() // { // return x.hashCode() ^ m ^ k1 ^ k2 ^ k3; // } // } /** * Class representing the Elements of the finite field * <code>F<sub>2<sup>m</sup></sub></code> in polynomial basis (PB) * representation. Both trinomial (TPB) and pentanomial (PPB) polynomial * basis representations are supported. Gaussian normal basis (GNB) * representation is not supported. */ public static class F2m extends ECFieldElement { /** * Indicates gaussian normal basis representation (GNB). Number chosen * according to X9.62. GNB is not implemented at present. */ public static final int GNB = 1; /** * Indicates trinomial basis representation (TPB). Number chosen * according to X9.62. */ public static final int TPB = 2; /** * Indicates pentanomial basis representation (PPB). Number chosen * according to X9.62. */ public static final int PPB = 3; /** * TPB or PPB. */ private int representation; /** * The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>. */ private int m; /** * TPB: The integer <code>k</code> where <code>x<sup>m</sup> + * x<sup>k</sup> + 1</code> represents the reduction polynomial * <code>f(z)</code>.<br> * PPB: The integer <code>k1</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ private int k1; /** * TPB: Always set to <code>0</code><br> * PPB: The integer <code>k2</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ private int k2; /** * TPB: Always set to <code>0</code><br> * PPB: The integer <code>k3</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ private int k3; /** * The number of <code>int</code>s required to hold <code>m</code> bits. */ private int t; /** * The <code>IntArray</code> holding the bits. */ private IntArray x; /** * Constructor for PPB. * @param m The exponent <code>m</code> of * <code>F<sub>2<sup>m</sup></sub></code>. * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>. * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>. * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>. * @param x The BigInteger representing the value of the field element. * @deprecated Use ECCurve.fromBigInteger to construct field elements */ public F2m( int m, int k1, int k2, int k3, BigInteger x) { if (x == null || x.signum() < 0) { throw new IllegalArgumentException("x value invalid in F2m field element"); } if ((k2 == 0) && (k3 == 0)) { this.representation = TPB; } else { if (k2 >= k3) { throw new IllegalArgumentException( "k2 must be smaller than k3"); } if (k2 <= 0) { throw new IllegalArgumentException( "k2 must be larger than 0"); } this.representation = PPB; } this.m = m; this.k1 = k1; this.k2 = k2; this.k3 = k3; // t = m / 32 rounded up to the next integer this.t = (m + 31) >> 5; this.x = new IntArray(x, t); } /** * Constructor for TPB. * @param m The exponent <code>m</code> of * <code>F<sub>2<sup>m</sup></sub></code>. * @param k The integer <code>k</code> where <code>x<sup>m</sup> + * x<sup>k</sup> + 1</code> represents the reduction * polynomial <code>f(z)</code>. * @param x The BigInteger representing the value of the field element. * @deprecated Use ECCurve.fromBigInteger to construct field elements */ public F2m(int m, int k, BigInteger x) { // Set k1 to k, and set k2 and k3 to 0 this(m, k, 0, 0, x); } private F2m(int m, int k1, int k2, int k3, IntArray x) { t = (m + 31) >> 5; this.x = x; this.m = m; this.k1 = k1; this.k2 = k2; this.k3 = k3; if ((k2 == 0) && (k3 == 0)) { this.representation = TPB; } else { this.representation = PPB; } } public int bitLength() { return x.bitLength(); } public boolean isZero() { return x.isZero(); } public boolean testBitZero() { return !x.isZero() && x.testBit(0); } public BigInteger toBigInteger() { return x.toBigInteger(); } public String getFieldName() { return "F2m"; } public int getFieldSize() { return m; } /** * Checks, if the ECFieldElements <code>a</code> and <code>b</code> * are elements of the same field <code>F<sub>2<sup>m</sup></sub></code> * (having the same representation). * @param a field element. * @param b field element to be compared. * @throws IllegalArgumentException if <code>a</code> and <code>b</code> * are not elements of the same field * <code>F<sub>2<sup>m</sup></sub></code> (having the same * representation). */ public static void checkFieldElements( ECFieldElement a, ECFieldElement b) { if ((!(a instanceof F2m)) || (!(b instanceof F2m))) { throw new IllegalArgumentException("Field elements are not " + "both instances of ECFieldElement.F2m"); } ECFieldElement.F2m aF2m = (ECFieldElement.F2m)a; ECFieldElement.F2m bF2m = (ECFieldElement.F2m)b; if ((aF2m.m != bF2m.m) || (aF2m.k1 != bF2m.k1) || (aF2m.k2 != bF2m.k2) || (aF2m.k3 != bF2m.k3)) { throw new IllegalArgumentException("Field elements are not " + "elements of the same field F2m"); } if (aF2m.representation != bF2m.representation) { // Should never occur throw new IllegalArgumentException( "One of the field " + "elements are not elements has incorrect representation"); } } public ECFieldElement add(final ECFieldElement b) { // No check performed here for performance reasons. Instead the // elements involved are checked in ECPoint.F2m // checkFieldElements(this, b); IntArray iarrClone = (IntArray)this.x.clone(); F2m bF2m = (F2m)b; iarrClone.addShifted(bF2m.x, 0); return new F2m(m, k1, k2, k3, iarrClone); } public ECFieldElement subtract(final ECFieldElement b) { // Addition and subtraction are the same in F2m return add(b); } public ECFieldElement multiply(final ECFieldElement b) { // Right-to-left comb multiplication in the IntArray // Input: Binary polynomials a(z) and b(z) of degree at most m-1 // Output: c(z) = a(z) * b(z) mod f(z) // No check performed here for performance reasons. Instead the // elements involved are checked in ECPoint.F2m // checkFieldElements(this, b); F2m bF2m = (F2m)b; IntArray mult = x.multiply(bF2m.x, m); mult.reduce(m, new int[]{k1, k2, k3}); return new F2m(m, k1, k2, k3, mult); } public ECFieldElement divide(final ECFieldElement b) { // There may be more efficient implementations ECFieldElement bInv = b.invert(); return multiply(bInv); } public ECFieldElement negate() { // -x == x holds for all x in F2m return this; } public ECFieldElement square() { IntArray squared = x.square(m); squared.reduce(m, new int[]{k1, k2, k3}); return new F2m(m, k1, k2, k3, squared); } public ECFieldElement invert() { // Inversion in F2m using the extended Euclidean algorithm // Input: A nonzero polynomial a(z) of degree at most m-1 // Output: a(z)^(-1) mod f(z) // u(z) := a(z) IntArray uz = (IntArray)this.x.clone(); // v(z) := f(z) IntArray vz = new IntArray(t); vz.setBit(m); vz.setBit(0); vz.setBit(this.k1); if (this.representation == PPB) { vz.setBit(this.k2); vz.setBit(this.k3); } // g1(z) := 1, g2(z) := 0 IntArray g1z = new IntArray(t); g1z.setBit(0); IntArray g2z = new IntArray(t); // while u != 0 while (!uz.isZero()) // while (uz.getUsedLength() > 0) // while (uz.bitLength() > 1) { // j := deg(u(z)) - deg(v(z)) int j = uz.bitLength() - vz.bitLength(); // If j < 0 then: u(z) <-> v(z), g1(z) <-> g2(z), j := -j if (j < 0) { final IntArray uzCopy = uz; uz = vz; vz = uzCopy; final IntArray g1zCopy = g1z; g1z = g2z; g2z = g1zCopy; j = -j; } // u(z) := u(z) + z^j * v(z) // Note, that no reduction modulo f(z) is required, because // deg(u(z) + z^j * v(z)) <= max(deg(u(z)), j + deg(v(z))) // = max(deg(u(z)), deg(u(z)) - deg(v(z)) + deg(v(z)) // = deg(u(z)) // uz = uz.xor(vz.shiftLeft(j)); // jInt = n / 32 int jInt = j >> 5; // jInt = n % 32 int jBit = j & 0x1F; IntArray vzShift = vz.shiftLeft(jBit); uz.addShifted(vzShift, jInt); // g1(z) := g1(z) + z^j * g2(z) // g1z = g1z.xor(g2z.shiftLeft(j)); IntArray g2zShift = g2z.shiftLeft(jBit); g1z.addShifted(g2zShift, jInt); } return new ECFieldElement.F2m( this.m, this.k1, this.k2, this.k3, g2z); } public ECFieldElement sqrt() { throw new RuntimeException("Not implemented"); } /** * @return the representation of the field * <code>F<sub>2<sup>m</sup></sub></code>, either of * TPB (trinomial * basis representation) or * PPB (pentanomial * basis representation). */ public int getRepresentation() { return this.representation; } /** * @return the degree <code>m</code> of the reduction polynomial * <code>f(z)</code>. */ public int getM() { return this.m; } /** * @return TPB: The integer <code>k</code> where <code>x<sup>m</sup> + * x<sup>k</sup> + 1</code> represents the reduction polynomial * <code>f(z)</code>.<br> * PPB: The integer <code>k1</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ public int getK1() { return this.k1; } /** * @return TPB: Always returns <code>0</code><br> * PPB: The integer <code>k2</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ public int getK2() { return this.k2; } /** * @return TPB: Always set to <code>0</code><br> * PPB: The integer <code>k3</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ public int getK3() { return this.k3; } public boolean equals(Object anObject) { if (anObject == this) { return true; } if (!(anObject instanceof ECFieldElement.F2m)) { return false; } ECFieldElement.F2m b = (ECFieldElement.F2m)anObject; return ((this.m == b.m) && (this.k1 == b.k1) && (this.k2 == b.k2) && (this.k3 == b.k3) && (this.representation == b.representation) && (this.x.equals(b.x))); } public int hashCode() { return x.hashCode() ^ m ^ k1 ^ k2 ^ k3; } } }
core/src/main/java/org/bouncycastle/math/ec/ECFieldElement.java
package org.bouncycastle.math.ec; import java.math.BigInteger; import java.util.Random; public abstract class ECFieldElement implements ECConstants { public abstract BigInteger toBigInteger(); public abstract String getFieldName(); public abstract int getFieldSize(); public abstract ECFieldElement add(ECFieldElement b); public abstract ECFieldElement subtract(ECFieldElement b); public abstract ECFieldElement multiply(ECFieldElement b); public abstract ECFieldElement divide(ECFieldElement b); public abstract ECFieldElement negate(); public abstract ECFieldElement square(); public abstract ECFieldElement invert(); public abstract ECFieldElement sqrt(); public int bitLength() { return toBigInteger().bitLength(); } public boolean isZero() { return 0 == toBigInteger().signum(); } public boolean testBitZero() { return toBigInteger().testBit(0); } public String toString() { return this.toBigInteger().toString(16); } public static class Fp extends ECFieldElement { BigInteger q, r, x; // static int[] calculateNaf(BigInteger p) // { // int[] naf = WNafUtil.generateCompactNaf(p); // // int bit = 0; // for (int i = 0; i < naf.length; ++i) // { // int ni = naf[i]; // int digit = ni >> 16, zeroes = ni & 0xFFFF; // // bit += zeroes; // naf[i] = digit < 0 ? ~bit : bit; // ++bit; // } // // int last = naf.length - 1; // if (last > 0 && last <= 16) // { // int top = naf[last], top2 = naf[last - 1]; // if (top2 < 0) // { // top2 = ~top2; // } // if (top - top2 >= 64) // { // return naf; // } // } // // return null; // } static BigInteger calculateResidue(BigInteger p) { int bitLength = p.bitLength(); if (bitLength > 128) { BigInteger firstWord = p.shiftRight(bitLength - 64); if (firstWord.longValue() == -1L) { return ONE.shiftLeft(bitLength).subtract(p); } } return null; } /** * @deprecated Use ECCurve.fromBigInteger to construct field elements */ public Fp(BigInteger q, BigInteger x) { this(q, calculateResidue(q), x); } Fp(BigInteger q, BigInteger r, BigInteger x) { if (x == null || x.signum() < 0 || x.compareTo(q) >= 0) { throw new IllegalArgumentException("x value invalid in Fp field element"); } this.q = q; this.r = r; this.x = x; } public BigInteger toBigInteger() { return x; } /** * return the field name for this field. * * @return the string "Fp". */ public String getFieldName() { return "Fp"; } public int getFieldSize() { return q.bitLength(); } public BigInteger getQ() { return q; } public ECFieldElement add(ECFieldElement b) { return new Fp(q, r, modAdd(x, b.toBigInteger())); } public ECFieldElement subtract(ECFieldElement b) { BigInteger x2 = b.toBigInteger(); BigInteger x3 = x.subtract(x2); if (x3.signum() < 0) { x3 = x3.add(q); } return new Fp(q, r, x3); } public ECFieldElement multiply(ECFieldElement b) { return new Fp(q, r, modMult(x, b.toBigInteger())); } public ECFieldElement divide(ECFieldElement b) { return new Fp(q, modMult(x, b.toBigInteger().modInverse(q))); } public ECFieldElement negate() { BigInteger x2; if (x.signum() == 0) { x2 = x; } else if (ONE.equals(r)) { x2 = q.xor(x); } else { x2 = q.subtract(x); } return new Fp(q, r, x2); } public ECFieldElement square() { return new Fp(q, r, modMult(x, x)); } public ECFieldElement invert() { // TODO Modular inversion can be faster for a (Generalized) Mersenne Prime. return new Fp(q, r, x.modInverse(q)); } // D.1.4 91 /** * return a sqrt root - the routine verifies that the calculation * returns the right value - if none exists it returns null. */ public ECFieldElement sqrt() { if (!q.testBit(0)) { throw new RuntimeException("not done yet"); } // note: even though this class implements ECConstants don't be tempted to // remove the explicit declaration, some J2ME environments don't cope. // p mod 4 == 3 if (q.testBit(1)) { // z = g^(u+1) + p, p = 4u + 3 ECFieldElement z = new Fp(q, r, x.modPow(q.shiftRight(2).add(ECConstants.ONE), q)); return z.square().equals(this) ? z : null; } // p mod 4 == 1 BigInteger qMinusOne = q.subtract(ECConstants.ONE); BigInteger legendreExponent = qMinusOne.shiftRight(1); if (!(x.modPow(legendreExponent, q).equals(ECConstants.ONE))) { return null; } BigInteger u = qMinusOne.shiftRight(2); BigInteger k = u.shiftLeft(1).add(ECConstants.ONE); BigInteger Q = this.x; BigInteger fourQ = modDouble(modDouble(Q)); BigInteger U, V; Random rand = new Random(); do { BigInteger P; do { P = new BigInteger(q.bitLength(), rand); } while (P.compareTo(q) >= 0 || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, q).equals(qMinusOne))); BigInteger[] result = lucasSequence(P, Q, k); U = result[0]; V = result[1]; if (modMult(V, V).equals(fourQ)) { // Integer division by 2, mod q if (V.testBit(0)) { V = V.add(q); } V = V.shiftRight(1); //assert V.multiply(V).mod(q).equals(x); return new ECFieldElement.Fp(q, r, V); } } while (U.equals(ECConstants.ONE) || U.equals(qMinusOne)); return null; // BigInteger qMinusOne = q.subtract(ECConstants.ONE); // BigInteger legendreExponent = qMinusOne.shiftRight(1); //divide(ECConstants.TWO); // if (!(x.modPow(legendreExponent, q).equals(ECConstants.ONE))) // { // return null; // } // // Random rand = new Random(); // BigInteger fourX = x.shiftLeft(2); // // BigInteger r; // do // { // r = new BigInteger(q.bitLength(), rand); // } // while (r.compareTo(q) >= 0 // || !(r.multiply(r).subtract(fourX).modPow(legendreExponent, q).equals(qMinusOne))); // // BigInteger n1 = qMinusOne.shiftRight(2); //.divide(ECConstants.FOUR); // BigInteger n2 = n1.add(ECConstants.ONE); //q.add(ECConstants.THREE).divide(ECConstants.FOUR); // // BigInteger wOne = WOne(r, x, q); // BigInteger wSum = W(n1, wOne, q).add(W(n2, wOne, q)).mod(q); // BigInteger twoR = r.shiftLeft(1); //ECConstants.TWO.multiply(r); // // BigInteger root = twoR.modPow(q.subtract(ECConstants.TWO), q) // .multiply(x).mod(q) // .multiply(wSum).mod(q); // // return new Fp(q, root); } // private static BigInteger W(BigInteger n, BigInteger wOne, BigInteger p) // { // if (n.equals(ECConstants.ONE)) // { // return wOne; // } // boolean isEven = !n.testBit(0); // n = n.shiftRight(1);//divide(ECConstants.TWO); // if (isEven) // { // BigInteger w = W(n, wOne, p); // return w.multiply(w).subtract(ECConstants.TWO).mod(p); // } // BigInteger w1 = W(n.add(ECConstants.ONE), wOne, p); // BigInteger w2 = W(n, wOne, p); // return w1.multiply(w2).subtract(wOne).mod(p); // } // // private BigInteger WOne(BigInteger r, BigInteger x, BigInteger p) // { // return r.multiply(r).multiply(x.modPow(q.subtract(ECConstants.TWO), q)).subtract(ECConstants.TWO).mod(p); // } private BigInteger[] lucasSequence( BigInteger P, BigInteger Q, BigInteger k) { int n = k.bitLength(); int s = k.getLowestSetBit(); BigInteger Uh = ECConstants.ONE; BigInteger Vl = ECConstants.TWO; BigInteger Vh = P; BigInteger Ql = ECConstants.ONE; BigInteger Qh = ECConstants.ONE; for (int j = n - 1; j >= s + 1; --j) { Ql = modMult(Ql, Qh); if (k.testBit(j)) { Qh = modMult(Ql, Q); Uh = modMult(Uh, Vh); Vl = modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); Vh = modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1))); } else { Qh = Ql; Uh = modReduce(Uh.multiply(Vl).subtract(Ql)); Vh = modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); Vl = modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); } } Ql = modMult(Ql, Qh); Qh = modMult(Ql, Q); Uh = modReduce(Uh.multiply(Vl).subtract(Ql)); Vl = modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql))); Ql = modMult(Ql, Qh); for (int j = 1; j <= s; ++j) { Uh = modMult(Uh, Vl); Vl = modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1))); Ql = modMult(Ql, Ql); } return new BigInteger[]{ Uh, Vl }; } protected BigInteger modAdd(BigInteger x1, BigInteger x2) { BigInteger x3 = x1.add(x2); if (x3.compareTo(q) >= 0) { x3 = x3.subtract(q); } return x3; } protected BigInteger modDouble(BigInteger x) { BigInteger _2x = x.shiftLeft(1); if (_2x.compareTo(q) >= 0) { _2x = _2x.subtract(q); } return _2x; } protected BigInteger modMult(BigInteger x1, BigInteger x2) { return modReduce(x1.multiply(x2)); } protected BigInteger modReduce(BigInteger x) { // if (naf != null) // { // int last = naf.length - 1; // int bits = naf[last]; // while (x.bitLength() > (bits + 1)) // { // BigInteger u = x.shiftRight(bits); // BigInteger v = x.subtract(u.shiftLeft(bits)); // // x = v; // // for (int i = 0; i < last; ++i) // { // int ni = naf[i]; // if (ni < 0) // { // x = x.add(u.shiftLeft(~ni)); // } // else // { // x = x.subtract(u.shiftLeft(ni)); // } // } // } // while (x.compareTo(q) >= 0) // { // x = x.subtract(q); // } // } // else if (r != null) { int qLen = q.bitLength(); while (x.bitLength() > (qLen + 1)) { BigInteger u = x.shiftRight(qLen); BigInteger v = x.subtract(u.shiftLeft(qLen)); if (!r.equals(ONE)) { u = u.multiply(r); } x = u.add(v); } while (x.compareTo(q) >= 0) { x = x.subtract(q); } } else { x = x.mod(q); } return x; } public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof ECFieldElement.Fp)) { return false; } ECFieldElement.Fp o = (ECFieldElement.Fp)other; return q.equals(o.q) && x.equals(o.x); } public int hashCode() { return q.hashCode() ^ x.hashCode(); } } // /** // * Class representing the Elements of the finite field // * <code>F<sub>2<sup>m</sup></sub></code> in polynomial basis (PB) // * representation. Both trinomial (TPB) and pentanomial (PPB) polynomial // * basis representations are supported. Gaussian normal basis (GNB) // * representation is not supported. // */ // public static class F2m extends ECFieldElement // { // BigInteger x; // // /** // * Indicates gaussian normal basis representation (GNB). Number chosen // * according to X9.62. GNB is not implemented at present. // */ // public static final int GNB = 1; // // /** // * Indicates trinomial basis representation (TPB). Number chosen // * according to X9.62. // */ // public static final int TPB = 2; // // /** // * Indicates pentanomial basis representation (PPB). Number chosen // * according to X9.62. // */ // public static final int PPB = 3; // // /** // * TPB or PPB. // */ // private int representation; // // /** // * The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>. // */ // private int m; // // /** // * TPB: The integer <code>k</code> where <code>x<sup>m</sup> + // * x<sup>k</sup> + 1</code> represents the reduction polynomial // * <code>f(z)</code>.<br> // * PPB: The integer <code>k1</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br> // */ // private int k1; // // /** // * TPB: Always set to <code>0</code><br> // * PPB: The integer <code>k2</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br> // */ // private int k2; // // /** // * TPB: Always set to <code>0</code><br> // * PPB: The integer <code>k3</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br> // */ // private int k3; // // /** // * Constructor for PPB. // * @param m The exponent <code>m</code> of // * <code>F<sub>2<sup>m</sup></sub></code>. // * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>. // * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>. // * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>. // * @param x The BigInteger representing the value of the field element. // */ // public F2m( // int m, // int k1, // int k2, // int k3, // BigInteger x) // { //// super(x); // this.x = x; // // if ((k2 == 0) && (k3 == 0)) // { // this.representation = TPB; // } // else // { // if (k2 >= k3) // { // throw new IllegalArgumentException( // "k2 must be smaller than k3"); // } // if (k2 <= 0) // { // throw new IllegalArgumentException( // "k2 must be larger than 0"); // } // this.representation = PPB; // } // // if (x.signum() < 0) // { // throw new IllegalArgumentException("x value cannot be negative"); // } // // this.m = m; // this.k1 = k1; // this.k2 = k2; // this.k3 = k3; // } // // /** // * Constructor for TPB. // * @param m The exponent <code>m</code> of // * <code>F<sub>2<sup>m</sup></sub></code>. // * @param k The integer <code>k</code> where <code>x<sup>m</sup> + // * x<sup>k</sup> + 1</code> represents the reduction // * polynomial <code>f(z)</code>. // * @param x The BigInteger representing the value of the field element. // */ // public F2m(int m, int k, BigInteger x) // { // // Set k1 to k, and set k2 and k3 to 0 // this(m, k, 0, 0, x); // } // // public BigInteger toBigInteger() // { // return x; // } // // public String getFieldName() // { // return "F2m"; // } // // public int getFieldSize() // { // return m; // } // // /** // * Checks, if the ECFieldElements <code>a</code> and <code>b</code> // * are elements of the same field <code>F<sub>2<sup>m</sup></sub></code> // * (having the same representation). // * @param a field element. // * @param b field element to be compared. // * @throws IllegalArgumentException if <code>a</code> and <code>b</code> // * are not elements of the same field // * <code>F<sub>2<sup>m</sup></sub></code> (having the same // * representation). // */ // public static void checkFieldElements( // ECFieldElement a, // ECFieldElement b) // { // if ((!(a instanceof F2m)) || (!(b instanceof F2m))) // { // throw new IllegalArgumentException("Field elements are not " // + "both instances of ECFieldElement.F2m"); // } // // if ((a.toBigInteger().signum() < 0) || (b.toBigInteger().signum() < 0)) // { // throw new IllegalArgumentException( // "x value may not be negative"); // } // // ECFieldElement.F2m aF2m = (ECFieldElement.F2m)a; // ECFieldElement.F2m bF2m = (ECFieldElement.F2m)b; // // if ((aF2m.m != bF2m.m) || (aF2m.k1 != bF2m.k1) // || (aF2m.k2 != bF2m.k2) || (aF2m.k3 != bF2m.k3)) // { // throw new IllegalArgumentException("Field elements are not " // + "elements of the same field F2m"); // } // // if (aF2m.representation != bF2m.representation) // { // // Should never occur // throw new IllegalArgumentException( // "One of the field " // + "elements are not elements has incorrect representation"); // } // } // // /** // * Computes <code>z * a(z) mod f(z)</code>, where <code>f(z)</code> is // * the reduction polynomial of <code>this</code>. // * @param a The polynomial <code>a(z)</code> to be multiplied by // * <code>z mod f(z)</code>. // * @return <code>z * a(z) mod f(z)</code> // */ // private BigInteger multZModF(final BigInteger a) // { // // Left-shift of a(z) // BigInteger az = a.shiftLeft(1); // if (az.testBit(this.m)) // { // // If the coefficient of z^m in a(z) equals 1, reduction // // modulo f(z) is performed: Add f(z) to to a(z): // // Step 1: Unset mth coeffient of a(z) // az = az.clearBit(this.m); // // // Step 2: Add r(z) to a(z), where r(z) is defined as // // f(z) = z^m + r(z), and k1, k2, k3 are the positions of // // the non-zero coefficients in r(z) // az = az.flipBit(0); // az = az.flipBit(this.k1); // if (this.representation == PPB) // { // az = az.flipBit(this.k2); // az = az.flipBit(this.k3); // } // } // return az; // } // // public ECFieldElement add(final ECFieldElement b) // { // // No check performed here for performance reasons. Instead the // // elements involved are checked in ECPoint.F2m // // checkFieldElements(this, b); // if (b.toBigInteger().signum() == 0) // { // return this; // } // // return new F2m(this.m, this.k1, this.k2, this.k3, this.x.xor(b.toBigInteger())); // } // // public ECFieldElement subtract(final ECFieldElement b) // { // // Addition and subtraction are the same in F2m // return add(b); // } // // // public ECFieldElement multiply(final ECFieldElement b) // { // // Left-to-right shift-and-add field multiplication in F2m // // Input: Binary polynomials a(z) and b(z) of degree at most m-1 // // Output: c(z) = a(z) * b(z) mod f(z) // // // No check performed here for performance reasons. Instead the // // elements involved are checked in ECPoint.F2m // // checkFieldElements(this, b); // final BigInteger az = this.x; // BigInteger bz = b.toBigInteger(); // BigInteger cz; // // // Compute c(z) = a(z) * b(z) mod f(z) // if (az.testBit(0)) // { // cz = bz; // } // else // { // cz = ECConstants.ZERO; // } // // for (int i = 1; i < this.m; i++) // { // // b(z) := z * b(z) mod f(z) // bz = multZModF(bz); // // if (az.testBit(i)) // { // // If the coefficient of x^i in a(z) equals 1, b(z) is added // // to c(z) // cz = cz.xor(bz); // } // } // return new ECFieldElement.F2m(m, this.k1, this.k2, this.k3, cz); // } // // // public ECFieldElement divide(final ECFieldElement b) // { // // There may be more efficient implementations // ECFieldElement bInv = b.invert(); // return multiply(bInv); // } // // public ECFieldElement negate() // { // // -x == x holds for all x in F2m // return this; // } // // public ECFieldElement square() // { // // Naive implementation, can probably be speeded up using modular // // reduction // return multiply(this); // } // // public ECFieldElement invert() // { // // Inversion in F2m using the extended Euclidean algorithm // // Input: A nonzero polynomial a(z) of degree at most m-1 // // Output: a(z)^(-1) mod f(z) // // // u(z) := a(z) // BigInteger uz = this.x; // if (uz.signum() <= 0) // { // throw new ArithmeticException("x is zero or negative, " + // "inversion is impossible"); // } // // // v(z) := f(z) // BigInteger vz = ECConstants.ZERO.setBit(m); // vz = vz.setBit(0); // vz = vz.setBit(this.k1); // if (this.representation == PPB) // { // vz = vz.setBit(this.k2); // vz = vz.setBit(this.k3); // } // // // g1(z) := 1, g2(z) := 0 // BigInteger g1z = ECConstants.ONE; // BigInteger g2z = ECConstants.ZERO; // // // while u != 1 // while (!(uz.equals(ECConstants.ZERO))) // { // // j := deg(u(z)) - deg(v(z)) // int j = uz.bitLength() - vz.bitLength(); // // // If j < 0 then: u(z) <-> v(z), g1(z) <-> g2(z), j := -j // if (j < 0) // { // final BigInteger uzCopy = uz; // uz = vz; // vz = uzCopy; // // final BigInteger g1zCopy = g1z; // g1z = g2z; // g2z = g1zCopy; // // j = -j; // } // // // u(z) := u(z) + z^j * v(z) // // Note, that no reduction modulo f(z) is required, because // // deg(u(z) + z^j * v(z)) <= max(deg(u(z)), j + deg(v(z))) // // = max(deg(u(z)), deg(u(z)) - deg(v(z)) + deg(v(z)) // // = deg(u(z)) // uz = uz.xor(vz.shiftLeft(j)); // // // g1(z) := g1(z) + z^j * g2(z) // g1z = g1z.xor(g2z.shiftLeft(j)); //// if (g1z.bitLength() > this.m) { //// throw new ArithmeticException( //// "deg(g1z) >= m, g1z = " + g1z.toString(16)); //// } // } // return new ECFieldElement.F2m( // this.m, this.k1, this.k2, this.k3, g2z); // } // // public ECFieldElement sqrt() // { // throw new RuntimeException("Not implemented"); // } // // /** // * @return the representation of the field // * <code>F<sub>2<sup>m</sup></sub></code>, either of // * TPB (trinomial // * basis representation) or // * PPB (pentanomial // * basis representation). // */ // public int getRepresentation() // { // return this.representation; // } // // /** // * @return the degree <code>m</code> of the reduction polynomial // * <code>f(z)</code>. // */ // public int getM() // { // return this.m; // } // // /** // * @return TPB: The integer <code>k</code> where <code>x<sup>m</sup> + // * x<sup>k</sup> + 1</code> represents the reduction polynomial // * <code>f(z)</code>.<br> // * PPB: The integer <code>k1</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br> // */ // public int getK1() // { // return this.k1; // } // // /** // * @return TPB: Always returns <code>0</code><br> // * PPB: The integer <code>k2</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br> // */ // public int getK2() // { // return this.k2; // } // // /** // * @return TPB: Always set to <code>0</code><br> // * PPB: The integer <code>k3</code> where <code>x<sup>m</sup> + // * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> // * represents the reduction polynomial <code>f(z)</code>.<br> // */ // public int getK3() // { // return this.k3; // } // // public boolean equals(Object anObject) // { // if (anObject == this) // { // return true; // } // // if (!(anObject instanceof ECFieldElement.F2m)) // { // return false; // } // // ECFieldElement.F2m b = (ECFieldElement.F2m)anObject; // // return ((this.m == b.m) && (this.k1 == b.k1) && (this.k2 == b.k2) // && (this.k3 == b.k3) // && (this.representation == b.representation) // && (this.x.equals(b.x))); // } // // public int hashCode() // { // return x.hashCode() ^ m ^ k1 ^ k2 ^ k3; // } // } /** * Class representing the Elements of the finite field * <code>F<sub>2<sup>m</sup></sub></code> in polynomial basis (PB) * representation. Both trinomial (TPB) and pentanomial (PPB) polynomial * basis representations are supported. Gaussian normal basis (GNB) * representation is not supported. */ public static class F2m extends ECFieldElement { /** * Indicates gaussian normal basis representation (GNB). Number chosen * according to X9.62. GNB is not implemented at present. */ public static final int GNB = 1; /** * Indicates trinomial basis representation (TPB). Number chosen * according to X9.62. */ public static final int TPB = 2; /** * Indicates pentanomial basis representation (PPB). Number chosen * according to X9.62. */ public static final int PPB = 3; /** * TPB or PPB. */ private int representation; /** * The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>. */ private int m; /** * TPB: The integer <code>k</code> where <code>x<sup>m</sup> + * x<sup>k</sup> + 1</code> represents the reduction polynomial * <code>f(z)</code>.<br> * PPB: The integer <code>k1</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ private int k1; /** * TPB: Always set to <code>0</code><br> * PPB: The integer <code>k2</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ private int k2; /** * TPB: Always set to <code>0</code><br> * PPB: The integer <code>k3</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ private int k3; /** * The number of <code>int</code>s required to hold <code>m</code> bits. */ private int t; /** * The <code>IntArray</code> holding the bits. */ private IntArray x; /** * Constructor for PPB. * @param m The exponent <code>m</code> of * <code>F<sub>2<sup>m</sup></sub></code>. * @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>. * @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>. * @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>. * @param x The BigInteger representing the value of the field element. * @deprecated Use ECCurve.fromBigInteger to construct field elements */ public F2m( int m, int k1, int k2, int k3, BigInteger x) { if (x == null || x.signum() < 0) { throw new IllegalArgumentException("x value invalid in F2m field element"); } if ((k2 == 0) && (k3 == 0)) { this.representation = TPB; } else { if (k2 >= k3) { throw new IllegalArgumentException( "k2 must be smaller than k3"); } if (k2 <= 0) { throw new IllegalArgumentException( "k2 must be larger than 0"); } this.representation = PPB; } this.m = m; this.k1 = k1; this.k2 = k2; this.k3 = k3; // t = m / 32 rounded up to the next integer this.t = (m + 31) >> 5; this.x = new IntArray(x, t); } /** * Constructor for TPB. * @param m The exponent <code>m</code> of * <code>F<sub>2<sup>m</sup></sub></code>. * @param k The integer <code>k</code> where <code>x<sup>m</sup> + * x<sup>k</sup> + 1</code> represents the reduction * polynomial <code>f(z)</code>. * @param x The BigInteger representing the value of the field element. * @deprecated Use ECCurve.fromBigInteger to construct field elements */ public F2m(int m, int k, BigInteger x) { // Set k1 to k, and set k2 and k3 to 0 this(m, k, 0, 0, x); } private F2m(int m, int k1, int k2, int k3, IntArray x) { t = (m + 31) >> 5; this.x = x; this.m = m; this.k1 = k1; this.k2 = k2; this.k3 = k3; if ((k2 == 0) && (k3 == 0)) { this.representation = TPB; } else { this.representation = PPB; } } public int bitLength() { return x.bitLength(); } public boolean isZero() { return x.isZero(); } public boolean testBitZero() { return !x.isZero() && x.testBit(0); } public BigInteger toBigInteger() { return x.toBigInteger(); } public String getFieldName() { return "F2m"; } public int getFieldSize() { return m; } /** * Checks, if the ECFieldElements <code>a</code> and <code>b</code> * are elements of the same field <code>F<sub>2<sup>m</sup></sub></code> * (having the same representation). * @param a field element. * @param b field element to be compared. * @throws IllegalArgumentException if <code>a</code> and <code>b</code> * are not elements of the same field * <code>F<sub>2<sup>m</sup></sub></code> (having the same * representation). */ public static void checkFieldElements( ECFieldElement a, ECFieldElement b) { if ((!(a instanceof F2m)) || (!(b instanceof F2m))) { throw new IllegalArgumentException("Field elements are not " + "both instances of ECFieldElement.F2m"); } ECFieldElement.F2m aF2m = (ECFieldElement.F2m)a; ECFieldElement.F2m bF2m = (ECFieldElement.F2m)b; if ((aF2m.m != bF2m.m) || (aF2m.k1 != bF2m.k1) || (aF2m.k2 != bF2m.k2) || (aF2m.k3 != bF2m.k3)) { throw new IllegalArgumentException("Field elements are not " + "elements of the same field F2m"); } if (aF2m.representation != bF2m.representation) { // Should never occur throw new IllegalArgumentException( "One of the field " + "elements are not elements has incorrect representation"); } } public ECFieldElement add(final ECFieldElement b) { // No check performed here for performance reasons. Instead the // elements involved are checked in ECPoint.F2m // checkFieldElements(this, b); IntArray iarrClone = (IntArray)this.x.clone(); F2m bF2m = (F2m)b; iarrClone.addShifted(bF2m.x, 0); return new F2m(m, k1, k2, k3, iarrClone); } public ECFieldElement subtract(final ECFieldElement b) { // Addition and subtraction are the same in F2m return add(b); } public ECFieldElement multiply(final ECFieldElement b) { // Right-to-left comb multiplication in the IntArray // Input: Binary polynomials a(z) and b(z) of degree at most m-1 // Output: c(z) = a(z) * b(z) mod f(z) // No check performed here for performance reasons. Instead the // elements involved are checked in ECPoint.F2m // checkFieldElements(this, b); F2m bF2m = (F2m)b; IntArray mult = x.multiply(bF2m.x, m); mult.reduce(m, new int[]{k1, k2, k3}); return new F2m(m, k1, k2, k3, mult); } public ECFieldElement divide(final ECFieldElement b) { // There may be more efficient implementations ECFieldElement bInv = b.invert(); return multiply(bInv); } public ECFieldElement negate() { // -x == x holds for all x in F2m return this; } public ECFieldElement square() { IntArray squared = x.square(m); squared.reduce(m, new int[]{k1, k2, k3}); return new F2m(m, k1, k2, k3, squared); } public ECFieldElement invert() { // Inversion in F2m using the extended Euclidean algorithm // Input: A nonzero polynomial a(z) of degree at most m-1 // Output: a(z)^(-1) mod f(z) // u(z) := a(z) IntArray uz = (IntArray)this.x.clone(); // v(z) := f(z) IntArray vz = new IntArray(t); vz.setBit(m); vz.setBit(0); vz.setBit(this.k1); if (this.representation == PPB) { vz.setBit(this.k2); vz.setBit(this.k3); } // g1(z) := 1, g2(z) := 0 IntArray g1z = new IntArray(t); g1z.setBit(0); IntArray g2z = new IntArray(t); // while u != 0 while (!uz.isZero()) // while (uz.getUsedLength() > 0) // while (uz.bitLength() > 1) { // j := deg(u(z)) - deg(v(z)) int j = uz.bitLength() - vz.bitLength(); // If j < 0 then: u(z) <-> v(z), g1(z) <-> g2(z), j := -j if (j < 0) { final IntArray uzCopy = uz; uz = vz; vz = uzCopy; final IntArray g1zCopy = g1z; g1z = g2z; g2z = g1zCopy; j = -j; } // u(z) := u(z) + z^j * v(z) // Note, that no reduction modulo f(z) is required, because // deg(u(z) + z^j * v(z)) <= max(deg(u(z)), j + deg(v(z))) // = max(deg(u(z)), deg(u(z)) - deg(v(z)) + deg(v(z)) // = deg(u(z)) // uz = uz.xor(vz.shiftLeft(j)); // jInt = n / 32 int jInt = j >> 5; // jInt = n % 32 int jBit = j & 0x1F; IntArray vzShift = vz.shiftLeft(jBit); uz.addShifted(vzShift, jInt); // g1(z) := g1(z) + z^j * g2(z) // g1z = g1z.xor(g2z.shiftLeft(j)); IntArray g2zShift = g2z.shiftLeft(jBit); g1z.addShifted(g2zShift, jInt); } return new ECFieldElement.F2m( this.m, this.k1, this.k2, this.k3, g2z); } public ECFieldElement sqrt() { throw new RuntimeException("Not implemented"); } /** * @return the representation of the field * <code>F<sub>2<sup>m</sup></sub></code>, either of * TPB (trinomial * basis representation) or * PPB (pentanomial * basis representation). */ public int getRepresentation() { return this.representation; } /** * @return the degree <code>m</code> of the reduction polynomial * <code>f(z)</code>. */ public int getM() { return this.m; } /** * @return TPB: The integer <code>k</code> where <code>x<sup>m</sup> + * x<sup>k</sup> + 1</code> represents the reduction polynomial * <code>f(z)</code>.<br> * PPB: The integer <code>k1</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ public int getK1() { return this.k1; } /** * @return TPB: Always returns <code>0</code><br> * PPB: The integer <code>k2</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ public int getK2() { return this.k2; } /** * @return TPB: Always set to <code>0</code><br> * PPB: The integer <code>k3</code> where <code>x<sup>m</sup> + * x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code> * represents the reduction polynomial <code>f(z)</code>.<br> */ public int getK3() { return this.k3; } public boolean equals(Object anObject) { if (anObject == this) { return true; } if (!(anObject instanceof ECFieldElement.F2m)) { return false; } ECFieldElement.F2m b = (ECFieldElement.F2m)anObject; return ((this.m == b.m) && (this.k1 == b.k1) && (this.k2 == b.k2) && (this.k3 == b.k3) && (this.representation == b.representation) && (this.x.equals(b.x))); } public int hashCode() { return x.hashCode() ^ m ^ k1 ^ k2 ^ k3; } } }
Add getEncoded method to ECFieldElement
core/src/main/java/org/bouncycastle/math/ec/ECFieldElement.java
Add getEncoded method to ECFieldElement
<ide><path>ore/src/main/java/org/bouncycastle/math/ec/ECFieldElement.java <ide> <ide> import java.math.BigInteger; <ide> import java.util.Random; <add> <add>import org.bouncycastle.util.BigIntegers; <ide> <ide> public abstract class ECFieldElement <ide> implements ECConstants <ide> public String toString() <ide> { <ide> return this.toBigInteger().toString(16); <add> } <add> <add> public byte[] getEncoded() <add> { <add> return BigIntegers.asUnsignedByteArray((getFieldSize() + 7) / 8, toBigInteger()); <ide> } <ide> <ide> public static class Fp extends ECFieldElement
Java
mit
0c2ed7739243df7679e88a625f7d29c284984403
0
ONSdigital/tredegar,ONSdigital/babbage,ONSdigital/babbage,ONSdigital/tredegar,ONSdigital/tredegar,ONSdigital/tredegar,ONSdigital/babbage,ONSdigital/babbage
package com.github.onsdigital.generator.data; import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang3.StringUtils; import com.github.onsdigital.json.timeseries.Timeseries; import com.github.onsdigital.json.timeseries.TimeseriesValue; /** * Handles the non-CDID data in the {@value #resourceName} spreadsheet. * <p> * This class and its members are package private (default visibility) because * the API doesn't need to be exposed to the rest of the application. * * @author david * */ class NonCdidCSV { static final String resourceName = "/data/Data for non-CDID hero series.xlsx"; static Set<String> timeseries = new HashSet<>(); static void parse() throws IOException { Csv csv = new Csv(resourceName); csv.read(); // Skip the first worksheet: for (int sheetIndex = 1; sheetIndex < csv.sheetCount(); sheetIndex++) { csv.read(sheetIndex); String[] cdidsRow = csv.row(6); for (int column = 1; column < cdidsRow.length; column++) { String cdid = cdidsRow[column]; // Check whether we have a CDID in this column. // Sometimes more columns are detected than there are CDIDs. if (StringUtils.isEmpty(cdid)) { continue; } // Get the timeseries object for this CDID: Timeseries timeseries = Data.timeseries(cdid); if (timeseries == null) { // System.out.println("Sheet " + sheetIndex + ", column " + // c + " - new timeseries " + cdid); timeseries = Data.addTimeseries(cdid); timeseries.data = new ArrayList<>(); // Clear the note1 and note2 fields timeseries.note1 = null; timeseries.note2 = null; } // Read the values from this column: data: for (int r = 0; r < csv.size(); r++) { String[] row = csv.row(r); if (row.length >= column) { String date = StringUtils.trim(row[0]); String figure = StringUtils.trim(row[column]); if (StringUtils.equalsIgnoreCase("Note", date)) { // End of data, there may be a note: timeseries.note1 = StringUtils.trim(row[1]); break data; } else if (StringUtils.isNotEmpty(date) && StringUtils.isNotEmpty(figure)) { TimeseriesValue timeseriesValue = new TimeseriesValue(); // Prevent decimal points on the date for years, // e.g. 2014.0. // This is due to the way numbers come out of // Excel. if (date != null && date.matches("\\d+[\\.\\d+]?")) { date = String.valueOf((long) Double.parseDouble(date)); } // Sanity-check that the figure really is a number: try { Double.parseDouble(figure); } catch (NumberFormatException e) { System.out.println(" ! The figure for " + cdid + " is " + figure); } // Give the figure a sensible format. // This is due to the way numbers come out of // Excel. String figureUpdated = figure; if (StringUtils.isNotBlank(figure) && figure.contains("E") && figure.contains(".")) { DecimalFormat format = new DecimalFormat("###,###,###,##0.00"); figureUpdated = format.format(Double.parseDouble(figure)); if (figureUpdated.endsWith(".00")) { figureUpdated = figureUpdated.substring(0, figureUpdated.length() - 3); } } // if (!StringUtils.equals(figure, figureUpdated)) { // System.out.println("Updated: " + figure + " -> " // + figureUpdated); // } timeseriesValue.date = date; timeseriesValue.value = figure; timeseries.data.add(timeseriesValue); } } } NonCdidCSV.timeseries.add(cdid); } } } }
src/main/java/com/github/onsdigital/generator/data/NonCdidCSV.java
package com.github.onsdigital.generator.data; import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang3.StringUtils; import com.github.onsdigital.json.timeseries.Timeseries; import com.github.onsdigital.json.timeseries.TimeseriesValue; /** * Handles the non-CDID data in the {@value #resourceName} spreadsheet. * <p> * This class and its members are package private (default visibility) because * the API doesn't need to be exposed to the rest of the application. * * @author david * */ class NonCdidCSV { static final String resourceName = "/data/Data for non-CDID hero series.xlsx"; static Set<String> timeseries = new HashSet<>(); static void parse() throws IOException { Csv csv = new Csv(resourceName); csv.read(); // Skip the first worksheet: for (int sheetIndex = 1; sheetIndex < csv.sheetCount(); sheetIndex++) { csv.read(sheetIndex); String[] cdidsRow = csv.row(6); for (int column = 1; column < cdidsRow.length; column++) { String cdid = cdidsRow[column]; // Check whether we have a CDID in this column. // Sometimes more columns are detected than there are CDIDs. if (StringUtils.isEmpty(cdid)) { continue; } // Get the timeseries object for this CDID: Timeseries timeseries = Data.timeseries(cdid); if (timeseries == null) { // System.out.println("Sheet " + sheetIndex + ", column " + // c + " - new timeseries " + cdid); timeseries = Data.addTimeseries(cdid); timeseries.data = new ArrayList<>(); // Clear the note1 and note2 fields timeseries.note1 = null; timeseries.note2 = null; } // Read the values from this column: data: for (int r = 0; r < csv.size(); r++) { String[] row = csv.row(r); if (row.length >= column) { String date = StringUtils.trim(row[0]); String figure = StringUtils.trim(row[column]); if (StringUtils.equalsIgnoreCase("Note", date)) { // End of data, there may be a note: timeseries.note1 = StringUtils.trim(row[1]); break data; } else if (StringUtils.isNotEmpty(date) && StringUtils.isNotEmpty(figure)) { TimeseriesValue timeseriesValue = new TimeseriesValue(); // Prevent decimal points on the date for years, // e.g. 2014.0. // This is due to the way numbers come out of // Excel. if (date != null && date.matches("\\d+[\\.\\d+]?")) { date = String.valueOf((long) Double.parseDouble(date)); } // Sanity-check that the figure really is a number: try { Double.parseDouble(figure); } catch (NumberFormatException e) { System.out.println(" ! The figure for " + cdid + " is " + figure); } // Give the figure a sensible format. // This is due to the way numbers come out of // Excel. String figureUpdated = figure; if (StringUtils.isNotBlank(figure) && figure.contains("E") && figure.contains(".")) { DecimalFormat format = new DecimalFormat("###,###,###,##0.00"); figureUpdated = format.format(Double.parseDouble(figure)); if (figureUpdated.endsWith(".00")) { figureUpdated = figureUpdated.substring(0, figureUpdated.length() - 3); } } if (!StringUtils.equals(figure, figureUpdated)) { System.out.println("Updated: " + figure + " -> " + figureUpdated); } timeseriesValue.date = date; timeseriesValue.value = figure; timeseries.data.add(timeseriesValue); } } } NonCdidCSV.timeseries.add(cdid); } } } }
Quietened down console mesasges.
src/main/java/com/github/onsdigital/generator/data/NonCdidCSV.java
Quietened down console mesasges.
<ide><path>rc/main/java/com/github/onsdigital/generator/data/NonCdidCSV.java <ide> figureUpdated = figureUpdated.substring(0, figureUpdated.length() - 3); <ide> } <ide> } <del> if (!StringUtils.equals(figure, figureUpdated)) { <del> System.out.println("Updated: " + figure + " -> " + figureUpdated); <del> } <add> // if (!StringUtils.equals(figure, figureUpdated)) { <add> // System.out.println("Updated: " + figure + " -> " <add> // + figureUpdated); <add> // } <ide> <ide> timeseriesValue.date = date; <ide> timeseriesValue.value = figure;
Java
apache-2.0
78f616c3211779352ee94a05ff419e79c5f49973
0
sindicate/solidstack.old,sindicate/solidstack.old,sindicate/solidstack.old,sindicate/solidstack.old
/*-- * Copyright 2012 Ren M. de Bloois * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package solidstack.cache; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import solidbase.core.SystemException; import solidstack.cache.ReadThroughCache.CacheEntry.STATE; /** * A read-through cache. * * @author Ren de Bloois * @since 2012 */ public class ReadThroughCache { static private final Logger log = LoggerFactory.getLogger( ReadThroughCache.class ); /** * Default cache expiration 10 minutes. */ static public final int DEFAULT_EXPIRATION_MILLIS = 600000; /** * Default wait timeout 1 minute. */ static public final int DEFAULT_WAIT_TIMEOUT_MILLIS = 60000; /** * Default purge interval 1 hour. */ static public final int DEFAULT_PURGE_INTERVAL_MILLIS = 3600000; /** * Default purge age 1 hour. */ static public final int DEFAULT_PURGE_AGE_MILLIS = 3600000; /** * The default global cache. */ static private final ReadThroughCache defaultCache = new ReadThroughCache(); /** * The cache. */ private Map<String, CacheEntry> cache = new HashMap<String, CacheEntry>(); /** * Current expiration interval. */ private int expirationMillis; /** * Current wait timeout. */ private int waitTimeoutMillis; /** * Current purge interval. */ private int purgePeriodMillis; /** * Current purge age. */ private int purgeAgeMillis; /** * The next purge moment. */ private long nextPurgeMillis; private boolean nonBlocking = true; /** * Gets the default global cache. * * @return The default global cache. */ static public ReadThroughCache getCache() { return defaultCache; } /** * Constructor. */ public ReadThroughCache() { // Set default properties this.expirationMillis = DEFAULT_EXPIRATION_MILLIS; this.purgePeriodMillis = DEFAULT_PURGE_INTERVAL_MILLIS; this.purgeAgeMillis = DEFAULT_PURGE_AGE_MILLIS; this.waitTimeoutMillis = DEFAULT_WAIT_TIMEOUT_MILLIS; this.nextPurgeMillis = getTime() + this.purgePeriodMillis; } /** * Returns the wait timeout. The wait timeout limits the time that one thread waits for another thread to reload the data into the cache. * * @return The wait timeout. */ public int getWaitTimeoutMillis() { return this.waitTimeoutMillis; } /** * Sets the wait timeout. The wait timeout limits the time that one thread waits for another thread to reload the data into the cache. * * @param waitTimeoutMillis The wait timeout. */ public void setWaitTimeoutMillis( int waitTimeoutMillis ) { if( waitTimeoutMillis < 0 ) throw new IllegalArgumentException( "waitTimeoutMillis can't be negative" ); this.waitTimeoutMillis = waitTimeoutMillis; } /** * Returns the number of milliseconds before a cache entry expires. * * @return the number of milliseconds before a cache entry expires. */ public int getExpirationMillis() { return this.expirationMillis; } /** * Sets the number of milliseconds before a cache entry expires. * * @param expirationMillis the number of milliseconds before a cache entry expires. */ public void setExpirationMillis( int expirationMillis ) { if( expirationMillis < 0 ) throw new IllegalArgumentException( "expirationMillis can't be negative" ); this.expirationMillis = expirationMillis; } /** * Returns the purge period, which defines the purge frequency. * * @return The purge period, which defines the purge frequency. */ public int getPurgePeriodMillis() { return this.purgePeriodMillis; } /** * Sets the purge period, which defines the purge frequency. * * @param purgePeriod The purge period, which defines the purge frequency. */ public void setPurgePeriodMillis( int purgePeriod ) { if( purgePeriod < 0 ) throw new IllegalArgumentException( "purgePeriod can't be negative" ); this.purgePeriodMillis = purgePeriod; } /** * Returns the age of expired cache entries before they will be purged. * * @return The age of expired cache entries before they will be purged. */ public int getPurgeAgeMillis() { return this.purgeAgeMillis; } /** * Sets the age of expired cache entries before they will be purged. * * @param purgeAge The age of expired cache entries before they will be purged. */ public void setPurgeAgeMillis( int purgeAge ) { if( purgeAge < 0 ) throw new IllegalArgumentException( "purgeAge can't be negative" ); this.purgeAgeMillis = purgeAge; } /** * Returns the current time in milliseconds. This method could be overridden in a subclass to simulate time in a unit test. * * @return The current time in milliseconds. */ protected long getTime() { return System.currentTimeMillis(); } // ! No logging inside synchronized blocks ! /** * Get a value from the cache. If the value is not found or the value is expired, the loader is called to get a new * value to store in the cache. During load, other threads that are trying to get the same value are blocked until * loading is finished. * * @param loader The loader to load values. * @param key The key into the cache. * @return The value belonging to the key. */ // LOADED -> RELOADING protected by locking this.cache public <T> T get( final Loader loader, Object... key ) { final String keyString = buildKey( key ); CacheEntry result; boolean load = false; boolean reload = false; synchronized( this.cache ) { long now = getTime(); // Get the time after entering the synchronized block if( now >= this.nextPurgeMillis ) // A long is not thread safe! So we need to do this in the same synchronized block. { // A CHANCE TO PURGE EVERY SO OFTEN this.nextPurgeMillis = now + this.purgePeriodMillis; purge( now ); } result = this.cache.get( keyString ); if( result == null ) { result = new CacheEntry( STATE.LOADING ); this.cache.put( keyString, result ); load = true; } else { switch( result.getState() ) { case LOADED: if( now > result.getExpirationTime() ) { result.reloading(); load = reload = true; } else { log.debug( "hit [" + keyString + "]" ); // TODO No logging inside synchronized block return extractValue( result ); } break; case RELOADING: if( this.nonBlocking ) return extractValue( result ); break; case FAILED: return extractValue( result ); case LOADING: } } } // 1. result now contains a CacheEntry // 2. load indicates that we need to load if( load ) { if( this.nonBlocking && reload ) { final CacheEntry _result = result; new Thread() { @Override public void run() { load( _result, keyString, loader ); } }.start(); return extractValue( result ); } return load( result, keyString, loader ); } log.debug( "waiting [" + keyString + "]" ); synchronized( result ) { // Don't wait if loading has finished already, we won't get a signal then if( result.getState() == STATE.LOADING || result.getState() == STATE.RELOADING ) { try { wait( result, this.waitTimeoutMillis ); } catch( InterruptedException e ) { throw new CacheTimeoutException( "Interrupted during waiting for the cache entry to be reloaded [" + keyString + "]" ); } if( result.getState() == STATE.LOADING || result.getState() == STATE.RELOADING ) throw new CacheTimeoutException( "Timed out waiting for the cache entry to be reloaded [" + keyString + "]" ); } return extractValue( result ); } } // LOADING/RELOADING -> LOADED/FAILED protected by lock on CacheEntry <T> T load( CacheEntry entry, String key, Loader loader ) { T value = null; Throwable throwable = null; try { try { // TODO Needs to be protected if( entry.getState() == STATE.LOADING ) log.debug( "miss:loading [" + key + "]" ); else log.debug( "expired:reloading [" + key+ "]" ); value = (T)loader.load(); } catch( Throwable t ) { throwable = t; } } finally { // First notify all synchronized( entry ) { entry.notifyAll(); long now = getTime(); if( throwable != null ) entry.failed( throwable, now, now + this.expirationMillis ); else entry.loaded( value, now, now + this.expirationMillis ); } if( throwable != null ) { log.debug( "failed [" + key + "]" ); if( throwable instanceof RuntimeException ) throw (RuntimeException)throwable; if( throwable instanceof Error ) throw (Error)throwable; throw new SystemException( throwable ); } log.debug( "loaded [" + key + "]" ); } return value; } static private <T> T extractValue( CacheEntry entry ) { if( entry.getState() == STATE.FAILED ) { Throwable t = (Throwable)entry.getValue(); if( t instanceof RuntimeException ) throw (RuntimeException)t; if( t instanceof Error ) throw (Error)t; throw new SystemException( t ); } if( entry.getState() == STATE.LOADING ) throw new IllegalStateException( "CacheEntry is still loading" ); return (T)entry.getValue(); } // Pure technical wait implementation private void wait( CacheEntry entry, int timeout ) throws InterruptedException { if( timeout <= 0 ) { do entry.wait(); while( entry.getState() == STATE.LOADING ); } else { long now = getTime(); long stop = now + timeout; do { entry.wait( stop - now ); now = getTime(); } while( entry.getState() == STATE.LOADING && now < stop ); } } /** * Purges entries from the cache which are expired. * * @param now The now. */ private void purge( long now ) { log.debug( "Purging..." ); long then = now - this.purgeAgeMillis; boolean debug = log.isDebugEnabled(); List<String> keys = new ArrayList<String>(); for( Iterator<Map.Entry<String, CacheEntry>> iter = this.cache.entrySet().iterator(); iter.hasNext(); ) { Entry<String, CacheEntry> entry = iter.next(); if( entry.getValue().getExpirationTime() < then ) { iter.remove(); if( debug ) keys.add( entry.getKey() ); } } for( String key : keys ) log.debug( "purged [" + key + "]" ); } /** * Transform an array of objects to a key. * * @param objects The array of objects. * @return The resulting key. */ static public String buildKey( Object... objects ) { StringBuilder result = new StringBuilder(); for( Object object : objects ) { if( result.length() > 0 ) result.append( ';' ); if( object == null ) result.append( "<null>" ); else result.append( object ); } return result.toString(); } /** * A tuple of a value and an expiration time used to store the value in the cache. */ static public class CacheEntry { static enum STATE { LOADING, RELOADING, LOADED, FAILED } private long stored, expire; private Object value; private STATE state; protected CacheEntry( STATE state ) { this.state = state; } public void reloading() { this.state = STATE.RELOADING; } // /** // * Constructor. // * // * @param value The value. // * @param stored When was the cache entry stored. // * @param expire When does the cache entry expire. // */ // protected CacheEntry( Object value, long stored, long expire ) // { // loaded( value, stored, expire ); // } void setExpirationTime( long expire ) { this.expire = expire; } public STATE getState() { return this.state; } public void loaded( Object value, long stored, long expire ) { this.stored = stored; this.expire = expire; this.value = value; this.state = STATE.LOADED; } public void failed( Throwable throwable, long stored, long expire ) { this.stored = stored; this.expire = expire; this.value = throwable; this.state = STATE.FAILED; } /** * Returns the value stored in this cache entry. The value can be null. * * @return The value stored in this cache entry. */ public Object getValue() { return this.value; } // /** // * Returns the time when the value was stored in the cache. // * // * @return The time when the value was stored in the cache. // */ // public long getStoredTime() // { // return this.stored; // } /** * Returns the time when the value will expire. * * @return The time when the value will expire. */ public long getExpirationTime() { return this.expire; } } static public interface Loader { Object load(); } }
src/solidstack/cache/ReadThroughCache.java
/*-- * Copyright 2012 Ren M. de Bloois * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package solidstack.cache; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import solidbase.core.SystemException; import solidstack.cache.ReadThroughCache.CacheEntry.STATE; /** * A read-through cache. * * @author Ren de Bloois * @since 2012 */ public class ReadThroughCache { static private final Logger log = LoggerFactory.getLogger( ReadThroughCache.class ); /** * Default cache expiration 10 minutes. */ static public final int DEFAULT_EXPIRATION_MILLIS = 600000; /** * Default wait timeout 1 minute. */ static public final int DEFAULT_WAIT_TIMEOUT_MILLIS = 60000; /** * Default purge interval 1 hour. */ static public final int DEFAULT_PURGE_INTERVAL_MILLIS = 3600000; /** * Default purge age 1 hour. */ static public final int DEFAULT_PURGE_AGE_MILLIS = 3600000; /** * The default global cache. */ static private final ReadThroughCache defaultCache = new ReadThroughCache(); /** * The cache. */ private Map<String, CacheEntry> cache = new HashMap<String, CacheEntry>(); /** * Current expiration interval. */ private int expirationMillis; /** * Current wait timeout. */ private int waitTimeoutMillis; /** * Current purge interval. */ private int purgePeriodMillis; /** * Current purge age. */ private int purgeAgeMillis; /** * The next purge moment. */ private long nextPurgeMillis; private boolean nonBlocking; /** * Gets the default global cache. * * @return The default global cache. */ static public ReadThroughCache getCache() { return defaultCache; } /** * Constructor. */ public ReadThroughCache() { // Set default properties this.expirationMillis = DEFAULT_EXPIRATION_MILLIS; this.purgePeriodMillis = DEFAULT_PURGE_INTERVAL_MILLIS; this.purgeAgeMillis = DEFAULT_PURGE_AGE_MILLIS; this.waitTimeoutMillis = DEFAULT_WAIT_TIMEOUT_MILLIS; this.nextPurgeMillis = getTime() + this.purgePeriodMillis; } /** * Returns the wait timeout. The wait timeout limits the time that one thread waits for another thread to reload the data into the cache. * * @return The wait timeout. */ public int getWaitTimeoutMillis() { return this.waitTimeoutMillis; } /** * Sets the wait timeout. The wait timeout limits the time that one thread waits for another thread to reload the data into the cache. * * @param waitTimeoutMillis The wait timeout. */ public void setWaitTimeoutMillis( int waitTimeoutMillis ) { if( waitTimeoutMillis < 0 ) throw new IllegalArgumentException( "waitTimeoutMillis can't be negative" ); this.waitTimeoutMillis = waitTimeoutMillis; } /** * Returns the number of milliseconds before a cache entry expires. * * @return the number of milliseconds before a cache entry expires. */ public int getExpirationMillis() { return this.expirationMillis; } /** * Sets the number of milliseconds before a cache entry expires. * * @param expirationMillis the number of milliseconds before a cache entry expires. */ public void setExpirationMillis( int expirationMillis ) { if( expirationMillis < 0 ) throw new IllegalArgumentException( "expirationMillis can't be negative" ); this.expirationMillis = expirationMillis; } /** * Returns the purge period, which defines the purge frequency. * * @return The purge period, which defines the purge frequency. */ public int getPurgePeriodMillis() { return this.purgePeriodMillis; } /** * Sets the purge period, which defines the purge frequency. * * @param purgePeriod The purge period, which defines the purge frequency. */ public void setPurgePeriodMillis( int purgePeriod ) { if( purgePeriod < 0 ) throw new IllegalArgumentException( "purgePeriod can't be negative" ); this.purgePeriodMillis = purgePeriod; } /** * Returns the age of expired cache entries before they will be purged. * * @return The age of expired cache entries before they will be purged. */ public int getPurgeAgeMillis() { return this.purgeAgeMillis; } /** * Sets the age of expired cache entries before they will be purged. * * @param purgeAge The age of expired cache entries before they will be purged. */ public void setPurgeAgeMillis( int purgeAge ) { if( purgeAge < 0 ) throw new IllegalArgumentException( "purgeAge can't be negative" ); this.purgeAgeMillis = purgeAge; } /** * Returns the current time in milliseconds. This method could be overridden in a subclass to simulate time in a unit test. * * @return The current time in milliseconds. */ protected long getTime() { return System.currentTimeMillis(); } // ! No logging inside synchronized blocks ! /** * Get a value from the cache. If the value is not found or the value is expired, the loader is called to get a new * value to store in the cache. During load, other threads that are trying to get the same value are blocked until * loading is finished. * * @param loader The loader to load values. * @param key The key into the cache. * @return The value belonging to the key. */ // LOADED -> RELOADING protected by locking this.cache public <T> T get( Loader loader, Object... key ) { String keyString = buildKey( key ); CacheEntry result; boolean load = false; synchronized( this.cache ) { long now = getTime(); // Get the time after entering the synchronized block if( now >= this.nextPurgeMillis ) // A long is not thread safe! So we need to do this in the same synchronized block. { // A CHANCE TO PURGE EVERY SO OFTEN this.nextPurgeMillis = now + this.purgePeriodMillis; purge( now ); } result = this.cache.get( keyString ); if( result == null ) { result = new CacheEntry( STATE.LOADING ); this.cache.put( keyString, result ); load = true; } else if( result.getState() == STATE.LOADED ) { if( now > result.getExpirationTime() ) { result.reloading(); load = true; } else { log.debug( "hit [" + keyString + "]" ); // TODO No logging inside synchronized block return extractValue( result ); } } } // 1. result now contains a CacheEntry // 2. load indicates that we need to load if( load ) return load( result, keyString, loader ); log.debug( "waiting [" + keyString + "]" ); synchronized( result ) { // Don't wait if loading has finished already, we won't get a signal then if( result.getState() == STATE.LOADING || result.getState() == STATE.RELOADING ) { try { wait( result, this.waitTimeoutMillis ); } catch( InterruptedException e ) { throw new CacheTimeoutException( "Interrupted during waiting for the cache entry to be reloaded [" + keyString + "]" ); } if( result.getState() == STATE.LOADING || result.getState() == STATE.RELOADING ) throw new CacheTimeoutException( "Timed out waiting for the cache entry to be reloaded [" + keyString + "]" ); } return extractValue( result ); } } // LOADING/RELOADING -> LOADED/FAILED protected by lock on CacheEntry private <T> T load( CacheEntry entry, String key, Loader loader ) { T value = null; Throwable throwable = null; try { try { // TODO Needs to be protected if( entry.getState() == STATE.LOADING ) log.debug( "miss:loading [" + key + "]" ); else log.debug( "expired:reloading [" + key+ "]" ); value = (T)loader.load(); } catch( Throwable t ) { throwable = t; } } finally { // First notify all synchronized( entry ) { entry.notifyAll(); long now = getTime(); if( throwable != null ) entry.failed( throwable, now, now + this.expirationMillis ); else entry.loaded( value, now, now + this.expirationMillis ); } if( throwable != null ) { log.debug( "failed [" + key + "]" ); if( throwable instanceof RuntimeException ) throw (RuntimeException)throwable; if( throwable instanceof Error ) throw (Error)throwable; throw new SystemException( throwable ); } log.debug( "loaded [" + key + "]" ); } return value; } static private <T> T extractValue( CacheEntry entry ) { if( entry.getState() == STATE.FAILED ) { Throwable t = (Throwable)entry.getValue(); if( t instanceof RuntimeException ) throw (RuntimeException)t; if( t instanceof Error ) throw (Error)t; throw new SystemException( t ); } if( entry.getState() != STATE.LOADED ) throw new IllegalStateException( "CacheEntry should be LOADED, but is " + entry.getState() ); return (T)entry.getValue(); } // Pure technical wait implementation private void wait( CacheEntry entry, int timeout ) throws InterruptedException { if( timeout <= 0 ) { do entry.wait(); while( entry.getState() == STATE.LOADING ); } else { long now = getTime(); long stop = now + timeout; do { entry.wait( stop - now ); now = getTime(); } while( entry.getState() == STATE.LOADING && now < stop ); } } /** * Purges entries from the cache which are expired. * * @param now The now. */ private void purge( long now ) { log.debug( "Purging..." ); long then = now - this.purgeAgeMillis; boolean debug = log.isDebugEnabled(); List<String> keys = new ArrayList<String>(); for( Iterator<Map.Entry<String, CacheEntry>> iter = this.cache.entrySet().iterator(); iter.hasNext(); ) { Entry<String, CacheEntry> entry = iter.next(); if( entry.getValue().getExpirationTime() < then ) { iter.remove(); if( debug ) keys.add( entry.getKey() ); } } for( String key : keys ) log.debug( "purged [" + key + "]" ); } /** * Transform an array of objects to a key. * * @param objects The array of objects. * @return The resulting key. */ static public String buildKey( Object... objects ) { StringBuilder result = new StringBuilder(); for( Object object : objects ) { if( result.length() > 0 ) result.append( ';' ); if( object == null ) result.append( "<null>" ); else result.append( object ); } return result.toString(); } /** * A tuple of a value and an expiration time used to store the value in the cache. */ static public class CacheEntry { static enum STATE { LOADING, RELOADING, LOADED, FAILED } private long stored, expire; private Object value; private STATE state; protected CacheEntry( STATE state ) { this.state = state; } public void reloading() { this.state = STATE.RELOADING; } // /** // * Constructor. // * // * @param value The value. // * @param stored When was the cache entry stored. // * @param expire When does the cache entry expire. // */ // protected CacheEntry( Object value, long stored, long expire ) // { // loaded( value, stored, expire ); // } void setExpirationTime( long expire ) { this.expire = expire; } public STATE getState() { return this.state; } public void loaded( Object value, long stored, long expire ) { this.stored = stored; this.expire = expire; this.value = value; this.state = STATE.LOADED; } public void failed( Throwable throwable, long stored, long expire ) { this.stored = stored; this.expire = expire; this.value = throwable; this.state = STATE.FAILED; } /** * Returns the value stored in this cache entry. The value can be null. * * @return The value stored in this cache entry. */ public Object getValue() { return this.value; } // /** // * Returns the time when the value was stored in the cache. // * // * @return The time when the value was stored in the cache. // */ // public long getStoredTime() // { // return this.stored; // } /** * Returns the time when the value will expire. * * @return The time when the value will expire. */ public long getExpirationTime() { return this.expire; } } static public interface Loader { Object load(); } }
Added nonblocking.
src/solidstack/cache/ReadThroughCache.java
Added nonblocking.
<ide><path>rc/solidstack/cache/ReadThroughCache.java <ide> */ <ide> private long nextPurgeMillis; <ide> <del> private boolean nonBlocking; <add> private boolean nonBlocking = true; <ide> <ide> <ide> /** <ide> * @return The value belonging to the key. <ide> */ <ide> // LOADED -> RELOADING protected by locking this.cache <del> public <T> T get( Loader loader, Object... key ) <del> { <del> String keyString = buildKey( key ); <add> public <T> T get( final Loader loader, Object... key ) <add> { <add> final String keyString = buildKey( key ); <ide> <ide> CacheEntry result; <ide> boolean load = false; <add> boolean reload = false; <ide> <ide> synchronized( this.cache ) <ide> { <ide> this.cache.put( keyString, result ); <ide> load = true; <ide> } <del> else if( result.getState() == STATE.LOADED ) <del> { <del> if( now > result.getExpirationTime() ) <add> else <add> { <add> switch( result.getState() ) <ide> { <del> result.reloading(); <del> load = true; <del> } <del> else <del> { <del> log.debug( "hit [" + keyString + "]" ); // TODO No logging inside synchronized block <del> return extractValue( result ); <add> case LOADED: <add> if( now > result.getExpirationTime() ) <add> { <add> result.reloading(); <add> load = reload = true; <add> } <add> else <add> { <add> log.debug( "hit [" + keyString + "]" ); // TODO No logging inside synchronized block <add> return extractValue( result ); <add> } <add> break; <add> <add> case RELOADING: <add> if( this.nonBlocking ) <add> return extractValue( result ); <add> break; <add> <add> case FAILED: <add> return extractValue( result ); <add> <add> case LOADING: <ide> } <ide> } <ide> } <ide> // 2. load indicates that we need to load <ide> <ide> if( load ) <add> { <add> if( this.nonBlocking && reload ) <add> { <add> final CacheEntry _result = result; <add> new Thread() <add> { <add> @Override <add> public void run() <add> { <add> load( _result, keyString, loader ); <add> } <add> }.start(); <add> return extractValue( result ); <add> } <ide> return load( result, keyString, loader ); <add> } <ide> <ide> log.debug( "waiting [" + keyString + "]" ); <ide> synchronized( result ) <ide> } <ide> <ide> // LOADING/RELOADING -> LOADED/FAILED protected by lock on CacheEntry <del> private <T> T load( CacheEntry entry, String key, Loader loader ) <add> <T> T load( CacheEntry entry, String key, Loader loader ) <ide> { <ide> T value = null; <ide> Throwable throwable = null; <ide> throw new SystemException( t ); <ide> } <ide> <del> if( entry.getState() != STATE.LOADED ) <del> throw new IllegalStateException( "CacheEntry should be LOADED, but is " + entry.getState() ); <add> if( entry.getState() == STATE.LOADING ) <add> throw new IllegalStateException( "CacheEntry is still loading" ); <ide> <ide> return (T)entry.getValue(); <ide> }
Java
apache-2.0
ed2e071202a2cb39e51d814cac5ca1ccbf7ce40f
0
artemnikitin/SeriesGuide,UweTrottmann/SeriesGuide,0359xiaodong/SeriesGuide,r00t-user/SeriesGuide,hoanganhx86/SeriesGuide,epiphany27/SeriesGuide,UweTrottmann/SeriesGuide
/* * Copyright 2012 Uwe Trottmann * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.battlelancer.seriesguide.ui; import android.annotation.TargetApi; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.BaseColumns; import android.support.v4.app.FragmentManager; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.text.format.DateUtils; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.battlelancer.seriesguide.provider.SeriesContract.ListItemTypes; import com.battlelancer.seriesguide.provider.SeriesContract.Shows; import com.battlelancer.seriesguide.settings.AdvancedSettings; import com.battlelancer.seriesguide.settings.ShowsDistillationSettings; import com.battlelancer.seriesguide.sync.SgSyncAdapter; import com.battlelancer.seriesguide.ui.dialogs.CheckInDialogFragment; import com.battlelancer.seriesguide.ui.dialogs.ConfirmDeleteDialogFragment; import com.battlelancer.seriesguide.ui.dialogs.ListsDialogFragment; import com.battlelancer.seriesguide.util.DBUtils; import com.battlelancer.seriesguide.util.FlagTask.FlagTaskCompletedEvent; import com.battlelancer.seriesguide.util.ImageProvider; import com.battlelancer.seriesguide.util.Utils; import com.google.analytics.tracking.android.EasyTracker; import com.uwetrottmann.seriesguide.R; import de.greenrobot.event.EventBus; /** * Displays the list of shows in a users local library with sorting and filtering abilities. The * main view of the app. */ public class ShowsFragment extends SherlockFragment implements LoaderManager.LoaderCallbacks<Cursor>, OnItemClickListener, OnClickListener { private static final String TAG = "Shows"; public static final int LOADER_ID = R.layout.shows_fragment; // context menu items private static final int CONTEXT_DELETE_ID = 200; private static final int CONTEXT_UPDATE_ID = 201; private static final int CONTEXT_FLAG_NEXT_ID = 202; private static final int CONTEXT_FAVORITE_ID = 203; private static final int CONTEXT_UNFAVORITE_ID = 204; private static final int CONTEXT_HIDE_ID = 205; private static final int CONTEXT_UNHIDE_ID = 206; private static final int CONTEXT_MANAGE_LISTS_ID = 207; private static final int CONTEXT_CHECKIN_ID = 208; private SlowAdapter mAdapter; private GridView mGrid; private int mSortOrderId; private boolean mIsSortFavoritesFirst; private boolean mIsFilterFavorites; private boolean mIsFilterUnwatched; private boolean mIsFilterUpcoming; private boolean mIsFilterHidden; public static ShowsFragment newInstance() { ShowsFragment f = new ShowsFragment(); return f; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.shows_fragment, container, false); v.findViewById(R.id.emptyViewShows).setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(getActivity(), AddActivity.class)); } }); v.findViewById(R.id.emptyViewShowsFilter).setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mIsFilterFavorites = mIsFilterUnwatched = mIsFilterUpcoming = mIsFilterHidden = false; // already start loading, do not need to wait on saving prefs getLoaderManager().restartLoader(ShowsFragment.LOADER_ID, null, ShowsFragment.this); PreferenceManager.getDefaultSharedPreferences(getActivity()).edit() .putBoolean(ShowsDistillationSettings.KEY_FILTER_FAVORITES, false) .putBoolean(ShowsDistillationSettings.KEY_FILTER_UNWATCHED, false) .putBoolean(ShowsDistillationSettings.KEY_FILTER_UPCOMING, false) .putBoolean(ShowsDistillationSettings.KEY_FILTER_HIDDEN, false) .commit(); // refresh filter menu check box states getActivity().supportInvalidateOptionsMenu(); } }); return v; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // get settings getSortAndFilterSettings(); // prepare view adapter int resIdStar = Utils.resolveAttributeToResourceId(getSherlockActivity().getTheme(), R.attr.drawableStar); int resIdStarZero = Utils.resolveAttributeToResourceId(getSherlockActivity().getTheme(), R.attr.drawableStar0); mAdapter = new SlowAdapter(getActivity(), null, 0, resIdStar, resIdStarZero, this); // setup grid view mGrid = (GridView) getView().findViewById(R.id.gridViewShows); mGrid.setAdapter(mAdapter); mGrid.setOnItemClickListener(this); registerForContextMenu(mGrid); // start loading data getLoaderManager().initLoader(LOADER_ID, null, this); // listen for some settings changes PreferenceManager .getDefaultSharedPreferences(getActivity()) .registerOnSharedPreferenceChangeListener(mPrefsListener); setHasOptionsMenu(true); } private void getSortAndFilterSettings() { mIsFilterFavorites = ShowsDistillationSettings.isFilteringFavorites(getActivity()); mIsFilterUnwatched = ShowsDistillationSettings.isFilteringUnwatched(getActivity()); mIsFilterUpcoming = ShowsDistillationSettings.isFilteringUpcoming(getActivity()); mIsFilterHidden = ShowsDistillationSettings.isFilteringHidden(getActivity()); mSortOrderId = ShowsDistillationSettings.getSortOrderId(getActivity()); mIsSortFavoritesFirst = ShowsDistillationSettings.isSortFavoritesFirst(getActivity()); } private void updateEmptyView() { View oldEmptyView = mGrid.getEmptyView(); View emptyView = null; if (mIsFilterFavorites || mIsFilterUnwatched || mIsFilterUpcoming || mIsFilterHidden) { emptyView = getView().findViewById(R.id.emptyViewShowsFilter); } else { emptyView = getView().findViewById(R.id.emptyViewShows); } if (oldEmptyView != null) { oldEmptyView.setVisibility(View.GONE); } if (emptyView != null) { mGrid.setEmptyView(emptyView); } } @Override public void onResume() { super.onResume(); EventBus.getDefault().register(this); } @Override public void onPause() { super.onPause(); EventBus.getDefault().unregister(this); } @Override public void onDestroy() { super.onDestroy(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); prefs.unregisterOnSharedPreferenceChangeListener(mPrefsListener); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menuInfo.toString(); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; final Cursor show = getActivity().getContentResolver().query( Shows.buildShowUri(String.valueOf(info.id)), new String[] { Shows.FAVORITE, Shows.HIDDEN }, null, null, null); show.moveToFirst(); if (show.getInt(0) == 0) { menu.add(0, CONTEXT_FAVORITE_ID, 2, R.string.context_favorite); } else { menu.add(0, CONTEXT_UNFAVORITE_ID, 2, R.string.context_unfavorite); } if (show.getInt(1) == 0) { menu.add(0, CONTEXT_HIDE_ID, 3, R.string.context_hide); } else { menu.add(0, CONTEXT_UNHIDE_ID, 3, R.string.context_unhide); } show.close(); menu.add(0, CONTEXT_CHECKIN_ID, 0, R.string.checkin); menu.add(0, CONTEXT_FLAG_NEXT_ID, 1, R.string.context_marknext); menu.add(0, CONTEXT_MANAGE_LISTS_ID, 4, R.string.list_item_manage); menu.add(0, CONTEXT_UPDATE_ID, 5, R.string.context_updateshow); menu.add(0, CONTEXT_DELETE_ID, 6, R.string.delete_show); } @Override public boolean onContextItemSelected(android.view.MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { case CONTEXT_CHECKIN_ID: { fireTrackerEventContext("Check in"); Cursor show = (Cursor) mAdapter.getItem(info.position); int episodeTvdbId = show.getInt(ShowsQuery.NEXTEPISODE); if (episodeTvdbId <= 0) { return true; } // display a check-in dialog CheckInDialogFragment f = CheckInDialogFragment.newInstance(getActivity(), episodeTvdbId); f.show(getFragmentManager(), "checkin-dialog"); return true; } case CONTEXT_FAVORITE_ID: { onFavoriteShow(String.valueOf(info.id), true); return true; } case CONTEXT_UNFAVORITE_ID: { onFavoriteShow(String.valueOf(info.id), false); return true; } case CONTEXT_HIDE_ID: { fireTrackerEventContext("Hide show"); ContentValues values = new ContentValues(); values.put(Shows.HIDDEN, true); getActivity().getContentResolver().update( Shows.buildShowUri(String.valueOf(info.id)), values, null, null); Toast.makeText(getActivity(), getString(R.string.hidden), Toast.LENGTH_SHORT) .show(); return true; } case CONTEXT_UNHIDE_ID: { fireTrackerEventContext("Unhide show"); ContentValues values = new ContentValues(); values.put(Shows.HIDDEN, false); getActivity().getContentResolver().update( Shows.buildShowUri(String.valueOf(info.id)), values, null, null); Toast.makeText(getActivity(), getString(R.string.unhidden), Toast.LENGTH_SHORT) .show(); return true; } case CONTEXT_DELETE_ID: if (!SgSyncAdapter.isSyncActive(getActivity(), true)) { showDeleteDialog(info.id); } fireTrackerEventContext("Delete show"); return true; case CONTEXT_UPDATE_ID: SgSyncAdapter.requestSync(getActivity(), (int) info.id); fireTrackerEventContext("Update show"); return true; case CONTEXT_FLAG_NEXT_ID: fireTrackerEventContext("Mark next episode"); Cursor show = (Cursor) mAdapter.getItem(info.position); DBUtils.markNextEpisode(getActivity(), (int) info.id, show.getInt(ShowsQuery.NEXTEPISODE)); return true; case CONTEXT_MANAGE_LISTS_ID: { fireTrackerEventContext("Manage lists"); ListsDialogFragment.showListsDialog(String.valueOf(info.id), ListItemTypes.SHOW, getFragmentManager()); return true; } } return super.onContextItemSelected(item); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.shows_menu, menu); // set filter check box states menu.findItem(R.id.menu_action_shows_filter_favorites) .setChecked(mIsFilterFavorites); menu.findItem(R.id.menu_action_shows_filter_unwatched) .setChecked(mIsFilterUnwatched); menu.findItem(R.id.menu_action_shows_filter_upcoming) .setChecked(mIsFilterUpcoming); menu.findItem(R.id.menu_action_shows_filter_hidden) .setChecked(mIsFilterHidden); // set sort check box state menu.findItem(R.id.menu_action_shows_sort_favorites) .setChecked(mIsSortFavoritesFirst); } @Override public void onPrepareOptionsMenu(Menu menu) { // If the nav drawer is open, hide action items related to the content view boolean isDrawerOpen = ((BaseNavDrawerActivity) getActivity()).isMenuDrawerOpen(); menu.findItem(R.id.menu_action_shows_filter).setVisible(!isDrawerOpen); } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.menu_action_shows_filter) { fireTrackerEventAction("Filter shows"); // did not handle here return super.onOptionsItemSelected(item); } else if (itemId == R.id.menu_action_shows_sort) { fireTrackerEventAction("Sort shows"); // did not handle here return super.onOptionsItemSelected(item); } else if (itemId == R.id.menu_action_shows_filter_favorites) { mIsFilterFavorites = !mIsFilterFavorites; changeSortOrFilter(ShowsDistillationSettings.KEY_FILTER_FAVORITES, mIsFilterFavorites, item); fireTrackerEventAction("Filter Favorites"); return true; } else if (itemId == R.id.menu_action_shows_filter_unwatched) { mIsFilterUnwatched = !mIsFilterUnwatched; changeSortOrFilter(ShowsDistillationSettings.KEY_FILTER_UNWATCHED, mIsFilterUnwatched, item); fireTrackerEventAction("Filter Unwatched"); return true; } else if (itemId == R.id.menu_action_shows_filter_upcoming) { mIsFilterUpcoming = !mIsFilterUpcoming; changeSortOrFilter(ShowsDistillationSettings.KEY_FILTER_UPCOMING, mIsFilterUpcoming, item); fireTrackerEventAction("Filter Upcoming"); return true; } else if (itemId == R.id.menu_action_shows_filter_hidden) { mIsFilterHidden = !mIsFilterHidden; changeSortOrFilter(ShowsDistillationSettings.KEY_FILTER_HIDDEN, mIsFilterHidden, item); fireTrackerEventAction("Filter Hidden"); return true; } else if (itemId == R.id.menu_action_shows_sort_title) { if (mSortOrderId == ShowsDistillationSettings.ShowsSortOrder.TITLE_ID) { mSortOrderId = ShowsDistillationSettings.ShowsSortOrder.TITLE_REVERSE_ID; } else { mSortOrderId = ShowsDistillationSettings.ShowsSortOrder.TITLE_ID; } changeSort(); fireTrackerEventAction("Sort Title"); return true; } else if (itemId == R.id.menu_action_shows_sort_episode) { if (mSortOrderId == ShowsDistillationSettings.ShowsSortOrder.EPISODE_ID) { mSortOrderId = ShowsDistillationSettings.ShowsSortOrder.EPISODE_REVERSE_ID; } else { mSortOrderId = ShowsDistillationSettings.ShowsSortOrder.EPISODE_ID; } changeSort(); fireTrackerEventAction("Sort Episode"); return true; } else if (itemId == R.id.menu_action_shows_sort_favorites) { mIsSortFavoritesFirst = !mIsSortFavoritesFirst; changeSortOrFilter(ShowsDistillationSettings.KEY_SORT_FAVORITES_FIRST, mIsSortFavoritesFirst, item); fireTrackerEventAction("Sort Favorites"); return true; } else { return super.onOptionsItemSelected(item); } } private void changeSortOrFilter(String key, boolean state, MenuItem item) { // already start loading, do not need to wait on saving prefs getLoaderManager().restartLoader(ShowsFragment.LOADER_ID, null, this); // update menu item state, then save at last item.setChecked(state); PreferenceManager.getDefaultSharedPreferences(getActivity()).edit() .putBoolean(key, state).commit(); } private void changeSort() { // already start loading, do not need to wait on saving prefs getLoaderManager().restartLoader(ShowsFragment.LOADER_ID, null, this); // save new sort order to preferences PreferenceManager.getDefaultSharedPreferences(getActivity()).edit() .putInt(ShowsDistillationSettings.KEY_SORT_ORDER, mSortOrderId).commit(); } @Override public void onClick(View v) { getActivity().openContextMenu(v); } @TargetApi(16) @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // display overview for this show Intent i = new Intent(getActivity(), OverviewActivity.class); i.putExtra(OverviewFragment.InitBundle.SHOW_TVDBID, (int) id); startActivity(i); getActivity().overridePendingTransition(R.anim.blow_up_enter, R.anim.blow_up_exit); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { StringBuilder selection = new StringBuilder(); // create temporary copies final boolean isFilterFavorites = mIsFilterFavorites; final boolean isFilterUnwatched = mIsFilterUnwatched; final boolean isFilterUpcoming = mIsFilterUpcoming; final boolean isFilterHidden = mIsFilterHidden; // restrict to favorites? if (isFilterFavorites) { selection.append(Shows.FAVORITE).append("=1"); } final long timeInAnHour = System.currentTimeMillis() + DateUtils.HOUR_IN_MILLIS; // restrict to shows with a next episode? if (isFilterUnwatched) { if (selection.length() != 0) { selection.append(" AND "); } selection.append(Shows.NEXTAIRDATEMS).append("!=").append(DBUtils.UNKNOWN_NEXT_AIR_DATE); // exclude shows with upcoming next episode if (!isFilterUpcoming) { selection.append(" AND ") .append(Shows.NEXTAIRDATEMS).append("<=") .append(timeInAnHour); } } // restrict to shows with an upcoming (yet to air) next episode? if (isFilterUpcoming) { if (selection.length() != 0) { selection.append(" AND "); } // Display shows upcoming within <limit> days + 1 hour int upcomingLimitInDays = AdvancedSettings.getUpcomingLimitInDays(getActivity()); long latestAirtime = timeInAnHour + upcomingLimitInDays * DateUtils.DAY_IN_MILLIS; selection.append(Shows.NEXTAIRDATEMS).append("<=").append(latestAirtime); // exclude shows with no upcoming next episode if not filtered for unwatched, too if (!isFilterUnwatched) { selection.append(" AND ") .append(Shows.NEXTAIRDATEMS).append(">=") .append(timeInAnHour); } } // special: if hidden filter is disabled, exclude hidden shows if (selection.length() != 0) { selection.append(" AND "); } selection.append(Shows.HIDDEN).append(isFilterHidden ? "=1" : "=0"); return new CursorLoader(getActivity(), Shows.CONTENT_URI, ShowsQuery.PROJECTION, selection.toString(), null, ShowsDistillationSettings.getSortQuery(mSortOrderId, mIsSortFavoritesFirst)); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // Swap the new cursor in. (The framework will take care of closing the // old cursor once we return.) mAdapter.swapCursor(data); // prepare an updated empty view updateEmptyView(); } @Override public void onLoaderReset(Loader<Cursor> arg0) { // This is called when the last Cursor provided to onLoadFinished() // above is about to be closed. We need to make sure we are no // longer using it. mAdapter.swapCursor(null); } private class SlowAdapter extends CursorAdapter { private final int LAYOUT = R.layout.shows_row; private LayoutInflater mLayoutInflater; private OnClickListener mOnClickListener; private int mStarDrawableId; private int mStarZeroDrawableId; public SlowAdapter(Context context, Cursor c, int flags, int starDrawableResId, int starZeroDrawableId, OnClickListener listener) { super(context, c, flags); mLayoutInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); mStarDrawableId = starDrawableResId; mStarZeroDrawableId = starZeroDrawableId; mOnClickListener = listener; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (!mDataValid) { throw new IllegalStateException( "this should only be called when the cursor is valid"); } if (!mCursor.moveToPosition(position)) { throw new IllegalStateException("couldn't move cursor to position " + position); } final ViewHolder viewHolder; if (convertView == null) { convertView = mLayoutInflater.inflate(LAYOUT, null); viewHolder = new ViewHolder(); viewHolder.name = (TextView) convertView.findViewById(R.id.seriesname); viewHolder.timeAndNetwork = (TextView) convertView .findViewById(R.id.textViewShowsTimeAndNetwork); viewHolder.episode = (TextView) convertView .findViewById(R.id.TextViewShowListNextEpisode); viewHolder.episodeTime = (TextView) convertView.findViewById(R.id.episodetime); viewHolder.poster = (ImageView) convertView.findViewById(R.id.showposter); viewHolder.favorited = (ImageView) convertView.findViewById(R.id.favoritedLabel); viewHolder.contextMenu = (ImageView) convertView .findViewById(R.id.imageViewShowsContextMenu); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } // set text properties immediately viewHolder.name.setText(mCursor.getString(ShowsQuery.TITLE)); // favorite toggle final String showId = mCursor.getString(ShowsQuery._ID); final boolean isFavorited = mCursor.getInt(ShowsQuery.FAVORITE) == 1; viewHolder.favorited.setImageResource(isFavorited ? mStarDrawableId : mStarZeroDrawableId); viewHolder.favorited.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onFavoriteShow(showId, !isFavorited); } }); // next episode info String fieldValue = mCursor.getString(ShowsQuery.NEXTTEXT); if (fieldValue.length() == 0) { // show show status if there are currently no more // episodes int status = mCursor.getInt(ShowsQuery.STATUS); // Continuing == 1 and Ended == 0 if (status == 1) { viewHolder.episodeTime.setText(getString(R.string.show_isalive)); } else if (status == 0) { viewHolder.episodeTime.setText(getString(R.string.show_isnotalive)); } else { viewHolder.episodeTime.setText(""); } viewHolder.episode.setText(""); } else { viewHolder.episode.setText(fieldValue); fieldValue = mCursor.getString(ShowsQuery.NEXTAIRDATETEXT); viewHolder.episodeTime.setText(fieldValue); } // airday final String[] values = Utils.parseMillisecondsToTime( mCursor.getLong(ShowsQuery.AIRSTIME), mCursor.getString(ShowsQuery.AIRSDAYOFWEEK), mContext); if (getResources().getBoolean(R.bool.isLargeTablet)) { // network first, then time, one line viewHolder.timeAndNetwork.setText(mCursor.getString(ShowsQuery.NETWORK) + " / " + values[1] + " " + values[0]); } else { // smaller screen, time first, network second line viewHolder.timeAndNetwork.setText(values[1] + " " + values[0] + "\n" + mCursor.getString(ShowsQuery.NETWORK)); } // set poster final String imagePath = mCursor.getString(ShowsQuery.POSTER); ImageProvider.getInstance(mContext).loadPosterThumb(viewHolder.poster, imagePath); // context menu viewHolder.contextMenu.setVisibility(View.VISIBLE); viewHolder.contextMenu.setOnClickListener(mOnClickListener); return convertView; } @Override public void bindView(View view, Context context, Cursor cursor) { // do nothing here } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return mLayoutInflater.inflate(LAYOUT, parent, false); } } static class ViewHolder { public TextView name; public TextView timeAndNetwork; public TextView episode; public TextView episodeTime; public ImageView poster; public ImageView favorited; public ImageView contextMenu; } private interface ShowsQuery { String[] PROJECTION = { BaseColumns._ID, Shows.TITLE, Shows.NEXTTEXT, Shows.AIRSTIME, Shows.NETWORK, Shows.POSTER, Shows.AIRSDAYOFWEEK, Shows.STATUS, Shows.NEXTAIRDATETEXT, Shows.FAVORITE, Shows.NEXTEPISODE }; int _ID = 0; int TITLE = 1; int NEXTTEXT = 2; int AIRSTIME = 3; int NETWORK = 4; int POSTER = 5; int AIRSDAYOFWEEK = 6; int STATUS = 7; int NEXTAIRDATETEXT = 8; int FAVORITE = 9; int NEXTEPISODE = 10; } private void onFavoriteShow(String showId, boolean isFavorite) { ContentValues values = new ContentValues(); values.put(Shows.FAVORITE, isFavorite); getActivity().getContentResolver().update( Shows.buildShowUri(showId), values, null, null); Utils.runNotificationService(getActivity()); Toast.makeText(getActivity(), getString(isFavorite ? R.string.favorited : R.string.unfavorited), Toast.LENGTH_SHORT) .show(); fireTrackerEventContext(isFavorite ? "Favorite show" : "Unfavorite show"); } private void showDeleteDialog(long showId) { FragmentManager fm = getFragmentManager(); ConfirmDeleteDialogFragment deleteDialog = ConfirmDeleteDialogFragment.newInstance(String .valueOf(showId)); deleteDialog.show(fm, "fragment_delete"); } private final OnSharedPreferenceChangeListener mPrefsListener = new OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(AdvancedSettings.KEY_UPCOMING_LIMIT)) { getLoaderManager().restartLoader(ShowsFragment.LOADER_ID, null, ShowsFragment.this); } } }; public void onEvent(FlagTaskCompletedEvent event) { if (isAdded()) { Utils.updateLatestEpisode(getActivity(), String.valueOf(event.mType.getShowTvdbId())); } } private static void fireTrackerEventAction(String label) { EasyTracker.getTracker().sendEvent(TAG, "Action Item", label, (long) 0); } private static void fireTrackerEventContext(String label) { EasyTracker.getTracker().sendEvent(TAG, "Context Item", label, (long) 0); } }
SeriesGuide/src/main/java/com/battlelancer/seriesguide/ui/ShowsFragment.java
/* * Copyright 2012 Uwe Trottmann * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.battlelancer.seriesguide.ui; import android.annotation.TargetApi; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.BaseColumns; import android.support.v4.app.FragmentManager; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.text.format.DateUtils; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.actionbarsherlock.app.SherlockFragment; import com.actionbarsherlock.view.Menu; import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.battlelancer.seriesguide.provider.SeriesContract.ListItemTypes; import com.battlelancer.seriesguide.provider.SeriesContract.Shows; import com.battlelancer.seriesguide.settings.AdvancedSettings; import com.battlelancer.seriesguide.settings.ShowsDistillationSettings; import com.battlelancer.seriesguide.sync.SgSyncAdapter; import com.battlelancer.seriesguide.ui.dialogs.CheckInDialogFragment; import com.battlelancer.seriesguide.ui.dialogs.ConfirmDeleteDialogFragment; import com.battlelancer.seriesguide.ui.dialogs.ListsDialogFragment; import com.battlelancer.seriesguide.util.DBUtils; import com.battlelancer.seriesguide.util.FlagTask.FlagTaskCompletedEvent; import com.battlelancer.seriesguide.util.ImageProvider; import com.battlelancer.seriesguide.util.Utils; import com.google.analytics.tracking.android.EasyTracker; import com.uwetrottmann.seriesguide.R; import de.greenrobot.event.EventBus; /** * Displays the list of shows in a users local library with sorting and filtering abilities. The * main view of the app. */ public class ShowsFragment extends SherlockFragment implements LoaderManager.LoaderCallbacks<Cursor>, OnItemClickListener, OnClickListener { private static final String TAG = "Shows"; public static final int LOADER_ID = R.layout.shows_fragment; // context menu items private static final int CONTEXT_DELETE_ID = 200; private static final int CONTEXT_UPDATE_ID = 201; private static final int CONTEXT_FLAG_NEXT_ID = 202; private static final int CONTEXT_FAVORITE_ID = 203; private static final int CONTEXT_UNFAVORITE_ID = 204; private static final int CONTEXT_HIDE_ID = 205; private static final int CONTEXT_UNHIDE_ID = 206; private static final int CONTEXT_MANAGE_LISTS_ID = 207; private static final int CONTEXT_CHECKIN_ID = 208; private SlowAdapter mAdapter; private GridView mGrid; private int mSortOrderId; private boolean mIsSortFavoritesFirst; private boolean mIsFilterFavorites; private boolean mIsFilterUnwatched; private boolean mIsFilterUpcoming; private boolean mIsFilterHidden; public static ShowsFragment newInstance() { ShowsFragment f = new ShowsFragment(); return f; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.shows_fragment, container, false); v.findViewById(R.id.emptyViewShows).setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(getActivity(), AddActivity.class)); } }); v.findViewById(R.id.emptyViewShowsFilter).setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { mIsFilterFavorites = mIsFilterUnwatched = mIsFilterUpcoming = mIsFilterHidden = false; // already start loading, do not need to wait on saving prefs getLoaderManager().restartLoader(ShowsFragment.LOADER_ID, null, ShowsFragment.this); // prepare an updated empty view updateEmptyView(); PreferenceManager.getDefaultSharedPreferences(getActivity()).edit() .putBoolean(ShowsDistillationSettings.KEY_FILTER_FAVORITES, false) .putBoolean(ShowsDistillationSettings.KEY_FILTER_UNWATCHED, false) .putBoolean(ShowsDistillationSettings.KEY_FILTER_UPCOMING, false) .putBoolean(ShowsDistillationSettings.KEY_FILTER_HIDDEN, false) .commit(); // refresh filter menu check box states getActivity().supportInvalidateOptionsMenu(); } }); return v; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // get settings getSortAndFilterSettings(); // prepare view adapter int resIdStar = Utils.resolveAttributeToResourceId(getSherlockActivity().getTheme(), R.attr.drawableStar); int resIdStarZero = Utils.resolveAttributeToResourceId(getSherlockActivity().getTheme(), R.attr.drawableStar0); mAdapter = new SlowAdapter(getActivity(), null, 0, resIdStar, resIdStarZero, this); // setup grid view mGrid = (GridView) getView().findViewById(R.id.gridViewShows); mGrid.setAdapter(mAdapter); mGrid.setOnItemClickListener(this); updateEmptyView(); registerForContextMenu(mGrid); // start loading data getLoaderManager().initLoader(LOADER_ID, null, this); // listen for some settings changes PreferenceManager .getDefaultSharedPreferences(getActivity()) .registerOnSharedPreferenceChangeListener(mPrefsListener); setHasOptionsMenu(true); } private void getSortAndFilterSettings() { mIsFilterFavorites = ShowsDistillationSettings.isFilteringFavorites(getActivity()); mIsFilterUnwatched = ShowsDistillationSettings.isFilteringUnwatched(getActivity()); mIsFilterUpcoming = ShowsDistillationSettings.isFilteringUpcoming(getActivity()); mIsFilterHidden = ShowsDistillationSettings.isFilteringHidden(getActivity()); mSortOrderId = ShowsDistillationSettings.getSortOrderId(getActivity()); mIsSortFavoritesFirst = ShowsDistillationSettings.isSortFavoritesFirst(getActivity()); } private void updateEmptyView() { View oldEmptyView = mGrid.getEmptyView(); View emptyView = null; if (mIsFilterFavorites || mIsFilterUnwatched || mIsFilterUpcoming || mIsFilterHidden) { emptyView = getView().findViewById(R.id.emptyViewShowsFilter); } else { emptyView = getView().findViewById(R.id.emptyViewShows); } if (oldEmptyView != null) { oldEmptyView.setVisibility(View.GONE); } if (emptyView != null) { final View emptyViewCopy = emptyView; mGrid.post(new Runnable() { @Override public void run() { mGrid.setEmptyView(emptyViewCopy); } }); } } @Override public void onResume() { super.onResume(); EventBus.getDefault().register(this); } @Override public void onPause() { super.onPause(); EventBus.getDefault().unregister(this); } @Override public void onDestroy() { super.onDestroy(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); prefs.unregisterOnSharedPreferenceChangeListener(mPrefsListener); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menuInfo.toString(); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; final Cursor show = getActivity().getContentResolver().query( Shows.buildShowUri(String.valueOf(info.id)), new String[] { Shows.FAVORITE, Shows.HIDDEN }, null, null, null); show.moveToFirst(); if (show.getInt(0) == 0) { menu.add(0, CONTEXT_FAVORITE_ID, 2, R.string.context_favorite); } else { menu.add(0, CONTEXT_UNFAVORITE_ID, 2, R.string.context_unfavorite); } if (show.getInt(1) == 0) { menu.add(0, CONTEXT_HIDE_ID, 3, R.string.context_hide); } else { menu.add(0, CONTEXT_UNHIDE_ID, 3, R.string.context_unhide); } show.close(); menu.add(0, CONTEXT_CHECKIN_ID, 0, R.string.checkin); menu.add(0, CONTEXT_FLAG_NEXT_ID, 1, R.string.context_marknext); menu.add(0, CONTEXT_MANAGE_LISTS_ID, 4, R.string.list_item_manage); menu.add(0, CONTEXT_UPDATE_ID, 5, R.string.context_updateshow); menu.add(0, CONTEXT_DELETE_ID, 6, R.string.delete_show); } @Override public boolean onContextItemSelected(android.view.MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); switch (item.getItemId()) { case CONTEXT_CHECKIN_ID: { fireTrackerEventContext("Check in"); Cursor show = (Cursor) mAdapter.getItem(info.position); int episodeTvdbId = show.getInt(ShowsQuery.NEXTEPISODE); if (episodeTvdbId <= 0) { return true; } // display a check-in dialog CheckInDialogFragment f = CheckInDialogFragment.newInstance(getActivity(), episodeTvdbId); f.show(getFragmentManager(), "checkin-dialog"); return true; } case CONTEXT_FAVORITE_ID: { onFavoriteShow(String.valueOf(info.id), true); return true; } case CONTEXT_UNFAVORITE_ID: { onFavoriteShow(String.valueOf(info.id), false); return true; } case CONTEXT_HIDE_ID: { fireTrackerEventContext("Hide show"); ContentValues values = new ContentValues(); values.put(Shows.HIDDEN, true); getActivity().getContentResolver().update( Shows.buildShowUri(String.valueOf(info.id)), values, null, null); Toast.makeText(getActivity(), getString(R.string.hidden), Toast.LENGTH_SHORT) .show(); return true; } case CONTEXT_UNHIDE_ID: { fireTrackerEventContext("Unhide show"); ContentValues values = new ContentValues(); values.put(Shows.HIDDEN, false); getActivity().getContentResolver().update( Shows.buildShowUri(String.valueOf(info.id)), values, null, null); Toast.makeText(getActivity(), getString(R.string.unhidden), Toast.LENGTH_SHORT) .show(); return true; } case CONTEXT_DELETE_ID: if (!SgSyncAdapter.isSyncActive(getActivity(), true)) { showDeleteDialog(info.id); } fireTrackerEventContext("Delete show"); return true; case CONTEXT_UPDATE_ID: SgSyncAdapter.requestSync(getActivity(), (int) info.id); fireTrackerEventContext("Update show"); return true; case CONTEXT_FLAG_NEXT_ID: fireTrackerEventContext("Mark next episode"); Cursor show = (Cursor) mAdapter.getItem(info.position); DBUtils.markNextEpisode(getActivity(), (int) info.id, show.getInt(ShowsQuery.NEXTEPISODE)); return true; case CONTEXT_MANAGE_LISTS_ID: { fireTrackerEventContext("Manage lists"); ListsDialogFragment.showListsDialog(String.valueOf(info.id), ListItemTypes.SHOW, getFragmentManager()); return true; } } return super.onContextItemSelected(item); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.shows_menu, menu); // set filter check box states menu.findItem(R.id.menu_action_shows_filter_favorites) .setChecked(mIsFilterFavorites); menu.findItem(R.id.menu_action_shows_filter_unwatched) .setChecked(mIsFilterUnwatched); menu.findItem(R.id.menu_action_shows_filter_upcoming) .setChecked(mIsFilterUpcoming); menu.findItem(R.id.menu_action_shows_filter_hidden) .setChecked(mIsFilterHidden); // set sort check box state menu.findItem(R.id.menu_action_shows_sort_favorites) .setChecked(mIsSortFavoritesFirst); } @Override public void onPrepareOptionsMenu(Menu menu) { // If the nav drawer is open, hide action items related to the content view boolean isDrawerOpen = ((BaseNavDrawerActivity) getActivity()).isMenuDrawerOpen(); menu.findItem(R.id.menu_action_shows_filter).setVisible(!isDrawerOpen); } @Override public boolean onOptionsItemSelected(MenuItem item) { int itemId = item.getItemId(); if (itemId == R.id.menu_action_shows_filter) { fireTrackerEventAction("Filter shows"); // did not handle here return super.onOptionsItemSelected(item); } else if (itemId == R.id.menu_action_shows_sort) { fireTrackerEventAction("Sort shows"); // did not handle here return super.onOptionsItemSelected(item); } else if (itemId == R.id.menu_action_shows_filter_favorites) { mIsFilterFavorites = !mIsFilterFavorites; changeSortOrFilter(ShowsDistillationSettings.KEY_FILTER_FAVORITES, mIsFilterFavorites, item); fireTrackerEventAction("Filter Favorites"); return true; } else if (itemId == R.id.menu_action_shows_filter_unwatched) { mIsFilterUnwatched = !mIsFilterUnwatched; changeSortOrFilter(ShowsDistillationSettings.KEY_FILTER_UNWATCHED, mIsFilterUnwatched, item); fireTrackerEventAction("Filter Unwatched"); return true; } else if (itemId == R.id.menu_action_shows_filter_upcoming) { mIsFilterUpcoming = !mIsFilterUpcoming; changeSortOrFilter(ShowsDistillationSettings.KEY_FILTER_UPCOMING, mIsFilterUpcoming, item); fireTrackerEventAction("Filter Upcoming"); return true; } else if (itemId == R.id.menu_action_shows_filter_hidden) { mIsFilterHidden = !mIsFilterHidden; changeSortOrFilter(ShowsDistillationSettings.KEY_FILTER_HIDDEN, mIsFilterHidden, item); fireTrackerEventAction("Filter Hidden"); return true; } else if (itemId == R.id.menu_action_shows_sort_title) { if (mSortOrderId == ShowsDistillationSettings.ShowsSortOrder.TITLE_ID) { mSortOrderId = ShowsDistillationSettings.ShowsSortOrder.TITLE_REVERSE_ID; } else { mSortOrderId = ShowsDistillationSettings.ShowsSortOrder.TITLE_ID; } changeSort(); fireTrackerEventAction("Sort Title"); return true; } else if (itemId == R.id.menu_action_shows_sort_episode) { if (mSortOrderId == ShowsDistillationSettings.ShowsSortOrder.EPISODE_ID) { mSortOrderId = ShowsDistillationSettings.ShowsSortOrder.EPISODE_REVERSE_ID; } else { mSortOrderId = ShowsDistillationSettings.ShowsSortOrder.EPISODE_ID; } changeSort(); fireTrackerEventAction("Sort Episode"); return true; } else if (itemId == R.id.menu_action_shows_sort_favorites) { mIsSortFavoritesFirst = !mIsSortFavoritesFirst; changeSortOrFilter(ShowsDistillationSettings.KEY_SORT_FAVORITES_FIRST, mIsSortFavoritesFirst, item); fireTrackerEventAction("Sort Favorites"); return true; } else { return super.onOptionsItemSelected(item); } } private void changeSortOrFilter(String key, boolean state, MenuItem item) { // already start loading, do not need to wait on saving prefs getLoaderManager().restartLoader(ShowsFragment.LOADER_ID, null, this); // prepare an updated empty view updateEmptyView(); // update menu item state, then save at last item.setChecked(state); PreferenceManager.getDefaultSharedPreferences(getActivity()).edit() .putBoolean(key, state).commit(); } private void changeSort() { // already start loading, do not need to wait on saving prefs getLoaderManager().restartLoader(ShowsFragment.LOADER_ID, null, this); // save new sort order to preferences PreferenceManager.getDefaultSharedPreferences(getActivity()).edit() .putInt(ShowsDistillationSettings.KEY_SORT_ORDER, mSortOrderId).commit(); } @Override public void onClick(View v) { getActivity().openContextMenu(v); } @TargetApi(16) @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // display overview for this show Intent i = new Intent(getActivity(), OverviewActivity.class); i.putExtra(OverviewFragment.InitBundle.SHOW_TVDBID, (int) id); startActivity(i); getActivity().overridePendingTransition(R.anim.blow_up_enter, R.anim.blow_up_exit); } public Loader<Cursor> onCreateLoader(int id, Bundle args) { StringBuilder selection = new StringBuilder(); // create temporary copies final boolean isFilterFavorites = mIsFilterFavorites; final boolean isFilterUnwatched = mIsFilterUnwatched; final boolean isFilterUpcoming = mIsFilterUpcoming; final boolean isFilterHidden = mIsFilterHidden; // restrict to favorites? if (isFilterFavorites) { selection.append(Shows.FAVORITE).append("=1"); } final long timeInAnHour = System.currentTimeMillis() + DateUtils.HOUR_IN_MILLIS; // restrict to shows with a next episode? if (isFilterUnwatched) { if (selection.length() != 0) { selection.append(" AND "); } selection.append(Shows.NEXTAIRDATEMS).append("!=").append(DBUtils.UNKNOWN_NEXT_AIR_DATE); // exclude shows with upcoming next episode if (!isFilterUpcoming) { selection.append(" AND ") .append(Shows.NEXTAIRDATEMS).append("<=") .append(timeInAnHour); } } // restrict to shows with an upcoming (yet to air) next episode? if (isFilterUpcoming) { if (selection.length() != 0) { selection.append(" AND "); } // Display shows upcoming within <limit> days + 1 hour int upcomingLimitInDays = AdvancedSettings.getUpcomingLimitInDays(getActivity()); long latestAirtime = timeInAnHour + upcomingLimitInDays * DateUtils.DAY_IN_MILLIS; selection.append(Shows.NEXTAIRDATEMS).append("<=").append(latestAirtime); // exclude shows with no upcoming next episode if not filtered for unwatched, too if (!isFilterUnwatched) { selection.append(" AND ") .append(Shows.NEXTAIRDATEMS).append(">=") .append(timeInAnHour); } } // special: if hidden filter is disabled, exclude hidden shows if (selection.length() != 0) { selection.append(" AND "); } selection.append(Shows.HIDDEN).append(isFilterHidden ? "=1" : "=0"); return new CursorLoader(getActivity(), Shows.CONTENT_URI, ShowsQuery.PROJECTION, selection.toString(), null, ShowsDistillationSettings.getSortQuery(mSortOrderId, mIsSortFavoritesFirst)); } public void onLoadFinished(Loader<Cursor> loader, Cursor data) { // Swap the new cursor in. (The framework will take care of closing the // old cursor once we return.) mAdapter.swapCursor(data); } public void onLoaderReset(Loader<Cursor> arg0) { // This is called when the last Cursor provided to onLoadFinished() // above is about to be closed. We need to make sure we are no // longer using it. mAdapter.swapCursor(null); } private class SlowAdapter extends CursorAdapter { private final int LAYOUT = R.layout.shows_row; private LayoutInflater mLayoutInflater; private OnClickListener mOnClickListener; private int mStarDrawableId; private int mStarZeroDrawableId; public SlowAdapter(Context context, Cursor c, int flags, int starDrawableResId, int starZeroDrawableId, OnClickListener listener) { super(context, c, flags); mLayoutInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); mStarDrawableId = starDrawableResId; mStarZeroDrawableId = starZeroDrawableId; mOnClickListener = listener; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (!mDataValid) { throw new IllegalStateException( "this should only be called when the cursor is valid"); } if (!mCursor.moveToPosition(position)) { throw new IllegalStateException("couldn't move cursor to position " + position); } final ViewHolder viewHolder; if (convertView == null) { convertView = mLayoutInflater.inflate(LAYOUT, null); viewHolder = new ViewHolder(); viewHolder.name = (TextView) convertView.findViewById(R.id.seriesname); viewHolder.timeAndNetwork = (TextView) convertView .findViewById(R.id.textViewShowsTimeAndNetwork); viewHolder.episode = (TextView) convertView .findViewById(R.id.TextViewShowListNextEpisode); viewHolder.episodeTime = (TextView) convertView.findViewById(R.id.episodetime); viewHolder.poster = (ImageView) convertView.findViewById(R.id.showposter); viewHolder.favorited = (ImageView) convertView.findViewById(R.id.favoritedLabel); viewHolder.contextMenu = (ImageView) convertView .findViewById(R.id.imageViewShowsContextMenu); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } // set text properties immediately viewHolder.name.setText(mCursor.getString(ShowsQuery.TITLE)); // favorite toggle final String showId = mCursor.getString(ShowsQuery._ID); final boolean isFavorited = mCursor.getInt(ShowsQuery.FAVORITE) == 1; viewHolder.favorited.setImageResource(isFavorited ? mStarDrawableId : mStarZeroDrawableId); viewHolder.favorited.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onFavoriteShow(showId, !isFavorited); } }); // next episode info String fieldValue = mCursor.getString(ShowsQuery.NEXTTEXT); if (fieldValue.length() == 0) { // show show status if there are currently no more // episodes int status = mCursor.getInt(ShowsQuery.STATUS); // Continuing == 1 and Ended == 0 if (status == 1) { viewHolder.episodeTime.setText(getString(R.string.show_isalive)); } else if (status == 0) { viewHolder.episodeTime.setText(getString(R.string.show_isnotalive)); } else { viewHolder.episodeTime.setText(""); } viewHolder.episode.setText(""); } else { viewHolder.episode.setText(fieldValue); fieldValue = mCursor.getString(ShowsQuery.NEXTAIRDATETEXT); viewHolder.episodeTime.setText(fieldValue); } // airday final String[] values = Utils.parseMillisecondsToTime( mCursor.getLong(ShowsQuery.AIRSTIME), mCursor.getString(ShowsQuery.AIRSDAYOFWEEK), mContext); if (getResources().getBoolean(R.bool.isLargeTablet)) { // network first, then time, one line viewHolder.timeAndNetwork.setText(mCursor.getString(ShowsQuery.NETWORK) + " / " + values[1] + " " + values[0]); } else { // smaller screen, time first, network second line viewHolder.timeAndNetwork.setText(values[1] + " " + values[0] + "\n" + mCursor.getString(ShowsQuery.NETWORK)); } // set poster final String imagePath = mCursor.getString(ShowsQuery.POSTER); ImageProvider.getInstance(mContext).loadPosterThumb(viewHolder.poster, imagePath); // context menu viewHolder.contextMenu.setVisibility(View.VISIBLE); viewHolder.contextMenu.setOnClickListener(mOnClickListener); return convertView; } @Override public void bindView(View view, Context context, Cursor cursor) { // do nothing here } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return mLayoutInflater.inflate(LAYOUT, parent, false); } } static class ViewHolder { public TextView name; public TextView timeAndNetwork; public TextView episode; public TextView episodeTime; public ImageView poster; public ImageView favorited; public ImageView contextMenu; } private interface ShowsQuery { String[] PROJECTION = { BaseColumns._ID, Shows.TITLE, Shows.NEXTTEXT, Shows.AIRSTIME, Shows.NETWORK, Shows.POSTER, Shows.AIRSDAYOFWEEK, Shows.STATUS, Shows.NEXTAIRDATETEXT, Shows.FAVORITE, Shows.NEXTEPISODE }; int _ID = 0; int TITLE = 1; int NEXTTEXT = 2; int AIRSTIME = 3; int NETWORK = 4; int POSTER = 5; int AIRSDAYOFWEEK = 6; int STATUS = 7; int NEXTAIRDATETEXT = 8; int FAVORITE = 9; int NEXTEPISODE = 10; } private void onFavoriteShow(String showId, boolean isFavorite) { ContentValues values = new ContentValues(); values.put(Shows.FAVORITE, isFavorite); getActivity().getContentResolver().update( Shows.buildShowUri(showId), values, null, null); Utils.runNotificationService(getActivity()); Toast.makeText(getActivity(), getString(isFavorite ? R.string.favorited : R.string.unfavorited), Toast.LENGTH_SHORT) .show(); fireTrackerEventContext(isFavorite ? "Favorite show" : "Unfavorite show"); } private void showDeleteDialog(long showId) { FragmentManager fm = getFragmentManager(); ConfirmDeleteDialogFragment deleteDialog = ConfirmDeleteDialogFragment.newInstance(String .valueOf(showId)); deleteDialog.show(fm, "fragment_delete"); } private final OnSharedPreferenceChangeListener mPrefsListener = new OnSharedPreferenceChangeListener() { public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(AdvancedSettings.KEY_UPCOMING_LIMIT)) { getLoaderManager().restartLoader(ShowsFragment.LOADER_ID, null, ShowsFragment.this); } } }; public void onEvent(FlagTaskCompletedEvent event) { if (isAdded()) { Utils.updateLatestEpisode(getActivity(), String.valueOf(event.mType.getShowTvdbId())); } } private static void fireTrackerEventAction(String label) { EasyTracker.getTracker().sendEvent(TAG, "Action Item", label, (long) 0); } private static void fireTrackerEventContext(String label) { EasyTracker.getTracker().sendEvent(TAG, "Context Item", label, (long) 0); } }
Fix empty view flickering
SeriesGuide/src/main/java/com/battlelancer/seriesguide/ui/ShowsFragment.java
Fix empty view flickering
<ide><path>eriesGuide/src/main/java/com/battlelancer/seriesguide/ui/ShowsFragment.java <ide> // already start loading, do not need to wait on saving prefs <ide> getLoaderManager().restartLoader(ShowsFragment.LOADER_ID, null, ShowsFragment.this); <ide> <del> // prepare an updated empty view <del> updateEmptyView(); <del> <ide> PreferenceManager.getDefaultSharedPreferences(getActivity()).edit() <ide> .putBoolean(ShowsDistillationSettings.KEY_FILTER_FAVORITES, false) <ide> .putBoolean(ShowsDistillationSettings.KEY_FILTER_UNWATCHED, false) <ide> mGrid = (GridView) getView().findViewById(R.id.gridViewShows); <ide> mGrid.setAdapter(mAdapter); <ide> mGrid.setOnItemClickListener(this); <del> updateEmptyView(); <ide> registerForContextMenu(mGrid); <ide> <ide> // start loading data <ide> } <ide> <ide> if (emptyView != null) { <del> final View emptyViewCopy = emptyView; <del> mGrid.post(new Runnable() { <del> @Override <del> public void run() { <del> mGrid.setEmptyView(emptyViewCopy); <del> } <del> }); <add> mGrid.setEmptyView(emptyView); <ide> } <ide> } <ide> <ide> // already start loading, do not need to wait on saving prefs <ide> getLoaderManager().restartLoader(ShowsFragment.LOADER_ID, null, this); <ide> <del> // prepare an updated empty view <del> updateEmptyView(); <del> <ide> // update menu item state, then save at last <ide> item.setChecked(state); <ide> PreferenceManager.getDefaultSharedPreferences(getActivity()).edit() <ide> getActivity().overridePendingTransition(R.anim.blow_up_enter, R.anim.blow_up_exit); <ide> } <ide> <add> @Override <ide> public Loader<Cursor> onCreateLoader(int id, Bundle args) { <ide> StringBuilder selection = new StringBuilder(); <ide> <ide> ShowsDistillationSettings.getSortQuery(mSortOrderId, mIsSortFavoritesFirst)); <ide> } <ide> <add> @Override <ide> public void onLoadFinished(Loader<Cursor> loader, Cursor data) { <ide> // Swap the new cursor in. (The framework will take care of closing the <ide> // old cursor once we return.) <ide> mAdapter.swapCursor(data); <del> } <del> <add> <add> // prepare an updated empty view <add> updateEmptyView(); <add> <add> } <add> <add> @Override <ide> public void onLoaderReset(Loader<Cursor> arg0) { <ide> // This is called when the last Cursor provided to onLoadFinished() <ide> // above is about to be closed. We need to make sure we are no <ide> <ide> private final OnSharedPreferenceChangeListener mPrefsListener = new OnSharedPreferenceChangeListener() { <ide> <add> @Override <ide> public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { <ide> if (key.equals(AdvancedSettings.KEY_UPCOMING_LIMIT)) { <ide> getLoaderManager().restartLoader(ShowsFragment.LOADER_ID, null, ShowsFragment.this);
Java
mit
5595e20e903a0d6bbbba6d8316d29c8af12a12b2
0
simplechatting/simplechatting
import Settings.*; import java.io.*; import java.nio.*; import java.nio.charset.*; /** * Created by penguin on 17. 6. 14. */ public class SCMessage { static int version = 1; static Charset charset = Charset.forName("UTF-8"); static ByteBuffer buffer = ByteBuffer.allocate(SCSettings.datagramSize); public SCMessage(){ buffer.clear(); } public SCMessage(byte[] data){ buffer = ByteBuffer.allocate(data.length); buffer.clear(); buffer = ByteBuffer.wrap(data); } }
src/SCMessage.java
import java.io.*; import java.nio.charset.*; /** * Created by penguin on 17. 6. 14. */ public class SCMessage { static int version = 1; static Charset charset = Charset.forName("UTF-8"); public int userid; public int groudid; public int msgType; public int line; public String message; public SCMessage(){} public SCMessage(int uid, int gid, int mType, String msg){ userid=uid; groudid=gid; msgType=mType; message=msg; } public SCMessage(int uid, int gid, int mType, int l, String msg){ userid=uid; groudid=gid; msgType=mType; line=l; message=msg; } }
kasfjdlkajdfkljlsdkf
src/SCMessage.java
kasfjdlkajdfkljlsdkf
<ide><path>rc/SCMessage.java <add>import Settings.*; <add> <ide> import java.io.*; <add>import java.nio.*; <ide> import java.nio.charset.*; <ide> <ide> /** <ide> public class SCMessage { <ide> static int version = 1; <ide> static Charset charset = Charset.forName("UTF-8"); <add> static ByteBuffer buffer = ByteBuffer.allocate(SCSettings.datagramSize); <ide> <del> public int userid; <del> public int groudid; <del> public int msgType; <del> public int line; <del> public String message; <add> public SCMessage(){ <add> buffer.clear(); <add> } <ide> <del> public SCMessage(){} <del> public SCMessage(int uid, int gid, int mType, String msg){ <del> userid=uid; <del> groudid=gid; <del> msgType=mType; <del> message=msg; <del> } <del> public SCMessage(int uid, int gid, int mType, int l, String msg){ <del> userid=uid; <del> groudid=gid; <del> msgType=mType; <del> line=l; <del> message=msg; <add> public SCMessage(byte[] data){ <add> buffer = ByteBuffer.allocate(data.length); <add> buffer.clear(); <add> buffer = ByteBuffer.wrap(data); <ide> } <ide> }
Java
apache-2.0
567342f336106bfb1787cd117fde82008b775e7f
0
ucam-cl-dtg/urop-2014-ticking-ui,ucam-cl-dtg/urop-2014-ticking-ui
package uk.ac.cam.cl.ticking.signups; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.cam.cl.signups.api.Group; import uk.ac.cam.cl.signups.api.Sheet; import uk.ac.cam.cl.signups.api.SheetInfo; import uk.ac.cam.cl.signups.api.Slot; import uk.ac.cam.cl.signups.api.beans.CreateColumnBean; import uk.ac.cam.cl.signups.api.beans.GroupSheetBean; import uk.ac.cam.cl.signups.api.beans.PermissionsBean; import uk.ac.cam.cl.signups.api.beans.SlotBookingBean; import uk.ac.cam.cl.signups.api.exceptions.DuplicateNameException; import uk.ac.cam.cl.signups.api.exceptions.ItemNotFoundException; import uk.ac.cam.cl.signups.api.exceptions.NotAllowedException; import uk.ac.cam.cl.signups.interfaces.SignupsWebInterface; import uk.ac.cam.cl.ticking.ui.actors.Role; import uk.ac.cam.cl.ticking.ui.dao.IDataManager; import uk.ac.cam.cl.ticking.ui.ticks.Fork; import uk.ac.cam.cl.ticking.ui.util.Strings; import com.google.inject.Inject; @Path("/signups") public class TickSignups { /* For logging */ Logger log = LoggerFactory.getLogger(TickSignups.class); private SignupsWebInterface service; private IDataManager db; @Inject public TickSignups(IDataManager db, SignupsWebInterface service) { this.service = service; this.db = db; } /* Below are the methods for the student workflow */ /** * Lists each time such that the time is the start time of * at least one free slot in the specified signup sheet. * @param sheetID The ID of the sheet whose free slots are needed. * @return A list of the start times of free slots * @throws ItemNotFoundException */ @GET @Path("/sheets/{sheetID}/times/{tickID}") @Produces("application/json") public Response listAvailableTimes(@Context HttpServletRequest request, @PathParam("tickID") String tickID, @PathParam("sheetID") String sheetID) { String crsid = (String) request.getSession().getAttribute("RavenRemoteUser"); try { List<String> groupIDs = service.getGroupIDs(sheetID); if (groupIDs.size() != 1) { return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("There should be precisely one group associated " + "with this sheet, but there seems to be " + groupIDs.size()).build(); } String groupID = groupIDs.get(0); log.info("crsid: " + crsid); log.info("tickID: " + tickID); log.info("groupID: " + groupID); log.info("sheetID: " + sheetID); return Response.ok(service.listAllFreeStartTimes(crsid, tickID, groupID, sheetID)).build(); } catch (ItemNotFoundException e) { return Response.status(Status.NOT_FOUND).entity(e).build(); } } /** * Books the given student into a free slot at the specified * time. Only allowed if the student has permission to book a * slot for this tick and they haven't made a booking at the * same time already and they haven't already made a booking * for the same tick already. * @return The ticker that the student has been signed up to * see at the given time. */ @POST @Path("/sheets/{sheetID}/bookings") @Consumes("application/json") public Response makeBooking(@Context HttpServletRequest request, @PathParam("sheetID") String sheetID, MakeBookingBean bean) { String crsid = (String) request.getSession().getAttribute("RavenRemoteUser"); List<String> groupIDs; try { groupIDs = service.getGroupIDs(sheetID); } catch (ItemNotFoundException e) { return Response.status(Status.NOT_FOUND).entity(e).build(); } if (groupIDs.size() != 1) { return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("There should be precisely one group associated " + "with this sheet, but there seems to be " + groupIDs.size()).build(); } String groupID = groupIDs.get(0); log.info("Attempting to book slot for user " + crsid + " for tickID " + bean.getTickID() + " at time " + new Date(bean.getStartTime()) + " on sheet " + sheetID + " in group " + groupID); for (Slot slot : service.listUserSlots(crsid)) { if (slot.getStartTime().equals(bean.getStartTime())) { return Response.status(Status.FORBIDDEN) .entity(Strings.EXISTINGTIMEBOOKING).build(); } if (slot.getComment().equals(bean.getTickID())) { return Response.status(Status.FORBIDDEN) .entity(Strings.EXISTINGTICKBOOKING).build(); } } try { if (service.listColumnsWithFreeSlotsAt(sheetID, bean.getStartTime()).size() == 0) { return Response.status(Status.NOT_FOUND) .entity(Strings.NOFREESLOTS).build(); } if (service.getPermissions(groupID, crsid).containsKey(bean.getTickID())) { // have passed this tick String ticker = service.getPermissions(groupID, crsid).get(bean.getTickID()); if (ticker == null) { // any ticker permitted ticker = service.listColumnsWithFreeSlotsAt(sheetID, bean.getStartTime()).get(0); } service.book(sheetID, ticker, bean.getStartTime(), new SlotBookingBean(null, crsid, bean.getTickID())); Fork f = db.getFork(Fork.generateForkId(crsid, bean.getTickID())); f.setSignedUp(true); db.saveFork(f); return Response.ok().entity(ticker).build(); } } catch (ItemNotFoundException e) { e.printStackTrace(); return Response.status(Status.NOT_FOUND) .entity(e).build(); } catch (NotAllowedException e) { e.printStackTrace(); return Response.status(Status.FORBIDDEN) .entity(e).build(); } return Response.status(Status.FORBIDDEN) .entity("You do not have permission to book this slot").build(); } /** * Unbooks the given user from the given slot. */ @DELETE @Path("/bookings/{tickID}") public Response unbookSlot(@Context HttpServletRequest request, @PathParam("tickID") String tickID) { String crsid = (String) request.getSession().getAttribute("RavenRemoteUser"); Slot booking = null; for (Slot slot : service.listUserSlots(crsid)) { if (slot.getComment().equals(tickID)) { booking = slot; } } if (booking == null) { return Response.status(Status.NOT_FOUND).entity("No booking was found for this tick").build(); } try { service.book(booking.getSheetID(), booking.getColumnName(), booking.getStartTime().getTime(), new SlotBookingBean(crsid, null, null)); Fork f = db.getFork(Fork.generateForkId(crsid, tickID)); f.setSignedUp(false); db.saveFork(f); return Response.ok().build(); } catch (ItemNotFoundException e) { e.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("The booking for this tick was found to exist and " + "then not found to exist. See following exception:\n" + e).build(); } catch (NotAllowedException e) { e.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("The removal of the booking should have been allowed but " + "for some reason was not. See following exception:\n" + e).build(); } } /** * Returns a list of the bookings in the future made by one user. */ @GET @Path("/bookings") @Produces("application/json") // TODO: check in order public Response listStudentBookings(@Context HttpServletRequest request) { String crsid = (String) request.getSession().getAttribute("RavenRemoteUser"); List<BookingInfo> toReturn = new ArrayList<BookingInfo>(); for (Slot s :service.listUserSlots(crsid)) { Date endTime = new Date(s.getStartTime().getTime() + s.getDuration()); if (endTime.after(new Date())) { toReturn.add(new BookingInfo(s)); } } return Response.ok(toReturn).build(); } /* Below are the methods for the ticker workflow */ /** * @return The list of the sheets in the given group. */ @GET @Path("/groups/{groupID}") @Produces("application/json") public Response listSheets(@PathParam("groupID") String groupID) { try { return Response.ok(service.listSheets(groupID)).build(); } catch (ItemNotFoundException e) { return Response.status(404).entity(e).build(); } } /** * @return A list of the ticker names for the given sheet. */ @GET @Path("/sheets/{sheetID}") @Produces("application/json") public Response listTickers(@PathParam("sheetID") String sheetID) { try { return Response.ok(service.listColumns(sheetID)).build(); } catch (ItemNotFoundException e) { return Response.status(404).entity(e).build(); } } /** * Returns a list of the slots for the specified ticker. */ @GET @Path("/sheets/{sheetID}/tickers/{ticker}") @Produces("application/json") public Response listSlots(@PathParam("sheetID") String sheetID, @PathParam("ticker") String tickerName) { try { return Response.ok(service.listColumnSlots(sheetID, tickerName)).build(); } catch (ItemNotFoundException e) { return Response.status(Status.NOT_FOUND).entity(e).build(); } } /** * @return Response whose body is has booked the slot (null if no one) and the tick * they have booked to do. */ @GET @Path("/sheets/{sheetID}/tickers/{ticker}/{startTime}") @Produces("application/json") public Response getBooking(@PathParam("sheetID") String sheetID, @PathParam("ticker") String tickerName, @PathParam("startTime") Date startTime) { try { return Response.ok(service.showBooking(sheetID, tickerName, startTime.getTime())).build(); } catch (ItemNotFoundException e) { return Response.status(Status.NOT_FOUND).entity(e).build(); } } /** * Removes all bookings that haven't yet started for the given * user in the given sheet. */ @DELETE @Path("/students/{crsid}/bookings/{sheetID}") public Response removeAllStudentBookings(@Context HttpServletRequest request, @PathParam("sheetID") String sheetID, @PathParam("crsid") String crsid) { String callingCRSID = (String) request.getSession().getAttribute("RavenRemoteUser"); List<String> groupIDs; try { groupIDs = service.getGroupIDs(sheetID); } catch (ItemNotFoundException e) { return Response.status(Status.NOT_FOUND).entity(e).build(); } if (groupIDs.size() != 1) { return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("There should be precisely one group associated " + "with this sheet, but there seems to be " + groupIDs.size()).build(); } String groupID = groupIDs.get(0); if (!db.getRoles(groupID, callingCRSID).contains(Role.MARKER)) { return Response.status(Status.FORBIDDEN).entity(Strings.INVALIDROLE).build(); } try { service.removeAllUserBookings(sheetID, crsid, db.getAuthCode(sheetID)); return Response.ok().build(); } catch (NotAllowedException e) { return Response.status(Status.FORBIDDEN).entity(e).build(); } catch (ItemNotFoundException e) { return Response.status(Status.NOT_FOUND).entity(e).build(); } } public Response allowSignup(String crsid, String groupID, String tickID) { try { service.listSheets(groupID); // to see if group exists } catch (ItemNotFoundException e) { // if it doesn't, create it try { createGroup(groupID); } catch (DuplicateNameException e1) { e1.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("The group was found to both exist and not exist " + "in the signups database, sorry.\n"+e1).build(); } } String groupAuthCode = db.getAuthCode(groupID); try { Map<String, String> map = new HashMap<String, String>(); map.put(tickID, null); service.addPermissions(groupID, crsid, new PermissionsBean(map, groupAuthCode)); return Response.ok().build(); } catch (NotAllowedException e) { e.printStackTrace(); return Response.status(Status.FORBIDDEN) .entity(e).build(); } catch (ItemNotFoundException e) { e.printStackTrace(); return Response.status(Status.NOT_FOUND) .entity(e).build(); } } public Response disallowSignup(String crsid, String groupID, String tickID) { Map<String, String> map = new HashMap<String, String>(); map.put(tickID, null); try { service.removePermissions(groupID, crsid, new PermissionsBean(map, db.getAuthCode(groupID))); } catch (NotAllowedException e) { e.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("Permission was denied - it shouldn't be.\n" + e).build(); } catch (ItemNotFoundException e) { e.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity(e).build(); } return Response.ok().build(); } /** * Ensures that the given student is assigned the given ticker * (if possible) in the future for the specified tick. */ @POST @Path("/students/{crsid}/permissions/{groupID}/{tickID}/{ticker}") public Response assignTickerForTickForUser(@Context HttpServletRequest request, @PathParam("crsid") String crsid, @PathParam("groupID") String groupID, @PathParam("tickID") String tickID, @PathParam("ticker") String ticker) { String callerCRSID = (String) request.getSession().getAttribute("RavenRemoteUser"); if (!db.getRoles(groupID, callerCRSID).contains(Role.MARKER)) { return Response.status(Status.FORBIDDEN).entity(Strings.INVALIDROLE).build(); } String groupAuthCode = db.getAuthCode(groupID); try { Map<String, String> map = new HashMap<String, String>(); map.put(tickID, ticker); service.addPermissions(groupID, crsid, new PermissionsBean(map, groupAuthCode)); return Response.ok().build(); } catch (NotAllowedException e) { e.printStackTrace(); return Response.status(Status.FORBIDDEN) .entity(e).build(); } catch (ItemNotFoundException e) { e.printStackTrace(); return Response.status(Status.NOT_FOUND) .entity(e).build(); } } public Response assignTickerForTickForUser(String crsid, String groupID, String tickID, String ticker) { String groupAuthCode = db.getAuthCode(groupID); try { Map<String, String> map = new HashMap<String, String>(); map.put(tickID, ticker); service.addPermissions(groupID, crsid, new PermissionsBean(map, groupAuthCode)); return Response.ok().build(); } catch (NotAllowedException e) { e.printStackTrace(); return Response.status(Status.FORBIDDEN) .entity(e).build(); } catch (ItemNotFoundException e) { e.printStackTrace(); return Response.status(Status.NOT_FOUND) .entity(e).build(); } } /* Below are the methods for the author workflow */ /** * Creates a new sheet for the given group. */ @POST @Path("/sheets") @Consumes("application/json") @Produces("application/json") public Response createSheet(@Context HttpServletRequest request, CreateSheetBean bean) { String crsid = (String) request.getSession().getAttribute("RavenRemoteUser"); if (!db.getRoles(bean.getGroupID(), crsid).contains(Role.AUTHOR)) { return Response.status(Status.FORBIDDEN).entity(Strings.INVALIDROLE).build(); } long sheetLengthInMinutes = (bean.getEndTime().getTime() - bean.getStartTime().getTime())/60000; if (sheetLengthInMinutes % bean.getSlotLengthInMinutes() != 0) { return Response.status(Status.BAD_REQUEST).entity("The difference in minutes " + "between the start and end times should be an integer multiple of " + "the length of the slots").build(); } Sheet newSheet = new Sheet(bean.getTitle(), bean.getDescription(), bean.getLocation()); String id; String auth; try { SheetInfo info = service.addSheet(newSheet); id = info.getSheetID(); auth = info.getAuthCode(); db.addAuthCode(id, auth); } catch (DuplicateNameException e) { return Response.serverError().entity("This sheet already seems to exist").build(); } for (String ticker : bean.getTickerNames()) { try { service.createColumn(id, new CreateColumnBean(ticker, auth, bean.getStartTime(), bean.getEndTime(), bean.getSlotLengthInMinutes())); } catch (ItemNotFoundException e) { e.printStackTrace(); throw new RuntimeException("This should only happen if the sheet or column is not found " + "but we are creating them"); } catch (NotAllowedException e) { e.printStackTrace(); throw new RuntimeException("We should have permission to access the sheet we have just created"); } catch (DuplicateNameException e) { /* * Actually, this isn't the end of the world, we can just ignore it. * e.printStackTrace(); * return Response.status(Status.BAD_REQUEST).entity("You must have specified two " * + "identical columns (or slots)").build(); */ } } try { service.addSheetToGroup(bean.getGroupID(), new GroupSheetBean(id, db.getAuthCode(bean.getGroupID()), auth)); } catch (ItemNotFoundException e) { // group doesn't yet exist: create and retry try { createGroup(bean.getGroupID()); service.addSheetToGroup(bean.getGroupID(), new GroupSheetBean(id, db.getAuthCode(bean.getGroupID()), auth)); } catch (DuplicateNameException e1) { e1.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("The group was found to both exist and not exist " + "in the signups database, sorry.\n"+e1).build(); } catch (ItemNotFoundException e1) { e1.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("The group was not found in the signups database, we " + "attempted to create it, but it still wasn't found." + "\n"+e1).build(); } catch (NotAllowedException e1) { e1.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("The group was not found in the signups database, " + "we attempted to create it, but permission was not " + "given - it should have been").build(); } } catch (NotAllowedException e) { e.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("The auth codes stored by the database were for some " + "reason found to be incorrect./n" + e).build(); } return Response.ok().build(); } /** * Adds a new column to the sheet, filled with regularly spaced * empty slots. * @param sheetID * @param authCode * @param name * @param startTime Time of first slot * @param numberOfSlots * @param slotLength In minutes */ @POST @Path("/sheets/{sheetID}/tickers") @Consumes("application/json") @Produces("application/json") //TODO: argument needs to be a bean public Response addColumn(@PathParam("sheetID") String sheetID, String authCode, String name, Date startTime, Date endTime, int slotLength /* in minutes */) { try { service.createColumn(sheetID, new CreateColumnBean(name, authCode, startTime, endTime, slotLength)); } catch (ItemNotFoundException e) { e.printStackTrace(); return Response.status(Status.NOT_FOUND).entity(e).build(); } catch (NotAllowedException e) { e.printStackTrace(); return Response.status(Status.FORBIDDEN).entity(e).build(); } catch (DuplicateNameException e) { e.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e).build(); } return Response.ok().build(); } /** * Deletes the specified column from the sheet. This also deletes * all the bookings made for that column. */ @DELETE @Path("/sheets/{sheetID}/tickers/{ticker}") @Consumes("text/plain") @Produces("application/json") public Response deleteColumn(@PathParam("sheetID") String sheetID, @PathParam("ticker") String ticker, String authCode) { try { service.deleteColumn(sheetID, ticker, authCode); } catch (NotAllowedException e) { e.printStackTrace(); return Response.status(Status.FORBIDDEN).entity(e).build(); } catch (ItemNotFoundException e) { e.printStackTrace(); return Response.status(Status.NOT_FOUND).entity(e).build(); } return Response.ok().build(); } /** * Modifies bookings no matter what. */ @POST @Path("/sheets/{sheetID}/bookings/{startTime}") @Consumes("application/json") // TODO: check arguments // TODO: unify with normal modify booking and even perhaps make booking TODO: maybe not public Response forceModifyBooking(@PathParam("sheetID") String sheetID, String authCode, String tickID, @PathParam("sheetID") Long startTime, String currentlyBookedUser, String userToBook) { String ticker = null; for (Slot slot : service.listUserSlots(currentlyBookedUser)) { if (slot.getStartTime().getTime() == startTime && slot.getComment().equals(tickID) && slot.getSheetID().equals(sheetID)) { ticker = slot.getColumnName(); } } if (ticker == null) { return Response.status(Status.NOT_FOUND).entity("The slot was not found").build(); } try { service.book(sheetID, ticker, startTime, new SlotBookingBean(currentlyBookedUser, userToBook, tickID, authCode)); } catch (ItemNotFoundException e) { e.printStackTrace(); return Response.status(Status.NOT_FOUND).entity(e).build(); } catch (NotAllowedException e) { e.printStackTrace(); return Response.status(Status.FORBIDDEN).entity(e).build(); } return Response.ok().build(); } public void createGroup(String groupID) throws DuplicateNameException { String groupAuthCode = service.addGroup(new Group(groupID)); db.addAuthCode(groupID, groupAuthCode); } }
ETick/src/main/java/uk/ac/cam/cl/ticking/signups/TickSignups.java
package uk.ac.cam.cl.ticking.signups; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.cam.cl.signups.api.Group; import uk.ac.cam.cl.signups.api.Sheet; import uk.ac.cam.cl.signups.api.SheetInfo; import uk.ac.cam.cl.signups.api.Slot; import uk.ac.cam.cl.signups.api.beans.CreateColumnBean; import uk.ac.cam.cl.signups.api.beans.GroupSheetBean; import uk.ac.cam.cl.signups.api.beans.PermissionsBean; import uk.ac.cam.cl.signups.api.beans.SlotBookingBean; import uk.ac.cam.cl.signups.api.exceptions.DuplicateNameException; import uk.ac.cam.cl.signups.api.exceptions.ItemNotFoundException; import uk.ac.cam.cl.signups.api.exceptions.NotAllowedException; import uk.ac.cam.cl.signups.interfaces.SignupsWebInterface; import uk.ac.cam.cl.ticking.ui.actors.Role; import uk.ac.cam.cl.ticking.ui.dao.IDataManager; import uk.ac.cam.cl.ticking.ui.ticks.Fork; import uk.ac.cam.cl.ticking.ui.util.Strings; import com.google.inject.Inject; @Path("/signups") public class TickSignups { /* For logging */ Logger log = LoggerFactory.getLogger(TickSignups.class); private SignupsWebInterface service; private IDataManager db; @Inject public TickSignups(IDataManager db, SignupsWebInterface service) { this.service = service; this.db = db; } /* Below are the methods for the student workflow */ /** * Lists each time such that the time is the start time of * at least one free slot in the specified signup sheet. * @param sheetID The ID of the sheet whose free slots are needed. * @return A list of the start times of free slots * @throws ItemNotFoundException */ @GET @Path("/sheets/{sheetID}/times/{tickID}") @Produces("application/json") public Response listAvailableTimes(@Context HttpServletRequest request, @PathParam("tickID") String tickID, @PathParam("sheetID") String sheetID) { String crsid = (String) request.getSession().getAttribute("RavenRemoteUser"); try { List<String> groupIDs = service.getGroupIDs(sheetID); if (groupIDs.size() != 1) { return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("There should be precisely one group associated " + "with this sheet, but there seems to be " + groupIDs.size()).build(); } String groupID = groupIDs.get(0); log.info("crsid: " + crsid); log.info("tickID: " + tickID); log.info("groupID: " + groupID); log.info("sheetID: " + sheetID); return Response.ok(service.listAllFreeStartTimes(crsid, tickID, groupID, sheetID)).build(); } catch (ItemNotFoundException e) { return Response.status(Status.NOT_FOUND).entity(e).build(); } } /** * Books the given student into a free slot at the specified * time. Only allowed if the student has permission to book a * slot for this tick and they haven't made a booking at the * same time already and they haven't already made a booking * for the same tick already. * @return The ticker that the student has been signed up to * see at the given time. */ @POST @Path("/sheets/{sheetID}/bookings") @Consumes("application/json") public Response makeBooking(@Context HttpServletRequest request, @PathParam("sheetID") String sheetID, MakeBookingBean bean) { String crsid = (String) request.getSession().getAttribute("RavenRemoteUser"); List<String> groupIDs; try { groupIDs = service.getGroupIDs(sheetID); } catch (ItemNotFoundException e) { return Response.status(Status.NOT_FOUND).entity(e).build(); } if (groupIDs.size() != 1) { return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("There should be precisely one group associated " + "with this sheet, but there seems to be " + groupIDs.size()).build(); } String groupID = groupIDs.get(0); log.info("Attempting to book slot for user " + crsid + " for tickID " + bean.getTickID() + " at time " + new Date(bean.getStartTime()) + " on sheet " + sheetID + " in group " + groupID); for (Slot slot : service.listUserSlots(crsid)) { if (slot.getStartTime().equals(bean.getStartTime())) { return Response.status(Status.FORBIDDEN) .entity(Strings.EXISTINGTIMEBOOKING).build(); } if (slot.getComment().equals(bean.getTickID())) { return Response.status(Status.FORBIDDEN) .entity(Strings.EXISTINGTICKBOOKING).build(); } } try { if (service.listColumnsWithFreeSlotsAt(sheetID, bean.getStartTime()).size() == 0) { return Response.status(Status.NOT_FOUND) .entity(Strings.NOFREESLOTS).build(); } if (service.getPermissions(groupID, crsid).containsKey(bean.getTickID())) { // have passed this tick String ticker = service.getPermissions(groupID, crsid).get(bean.getTickID()); if (ticker == null) { // any ticker permitted ticker = service.listColumnsWithFreeSlotsAt(sheetID, bean.getStartTime()).get(0); } service.book(sheetID, ticker, bean.getStartTime(), new SlotBookingBean(null, crsid, bean.getTickID())); Fork f = db.getFork(Fork.generateForkId(crsid, bean.getTickID())); f.setSignedUp(true); db.saveFork(f); return Response.ok().entity(ticker).build(); } } catch (ItemNotFoundException e) { e.printStackTrace(); return Response.status(Status.NOT_FOUND) .entity(e).build(); } catch (NotAllowedException e) { e.printStackTrace(); return Response.status(Status.FORBIDDEN) .entity(e).build(); } return Response.status(Status.FORBIDDEN) .entity("You do not have permission to book this slot").build(); } /** * Unbooks the given user from the given slot. */ @DELETE @Path("/bookings/{tickID}") public Response unbookSlot(@Context HttpServletRequest request, @PathParam("tickID") String tickID) { String crsid = (String) request.getSession().getAttribute("RavenRemoteUser"); Slot booking = null; for (Slot slot : service.listUserSlots(crsid)) { if (slot.getComment().equals(tickID)) { booking = slot; } } if (booking == null) { return Response.status(Status.NOT_FOUND).entity("No booking was found for this tick").build(); } try { service.book(booking.getSheetID(), booking.getColumnName(), booking.getStartTime().getTime(), new SlotBookingBean(crsid, null, null)); Fork f = db.getFork(Fork.generateForkId(crsid, tickID)); f.setSignedUp(false); db.saveFork(f); return Response.ok().build(); } catch (ItemNotFoundException e) { e.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("The booking for this tick was found to exist and " + "then not found to exist. See following exception:\n" + e).build(); } catch (NotAllowedException e) { e.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("The removal of the booking should have been allowed but " + "for some reason was not. See following exception:\n" + e).build(); } } /** * Returns a list of the bookings in the future made by one user. */ @GET @Path("/bookings") @Produces("application/json") // TODO: check in order public Response listStudentBookings(@Context HttpServletRequest request) { String crsid = (String) request.getSession().getAttribute("RavenRemoteUser"); List<BookingInfo> toReturn = new ArrayList<BookingInfo>(); for (Slot s :service.listUserSlots(crsid)) { Date endTime = new Date(s.getStartTime().getTime() + s.getDuration()); if (endTime.after(new Date())) { toReturn.add(new BookingInfo(s)); } } return Response.ok(toReturn).build(); } /* Below are the methods for the ticker workflow */ /** * @return The list of the sheets in the given group. */ @GET @Path("/groups/{groupID}") @Produces("application/json") public Response listSheets(@PathParam("groupID") String groupID) { try { return Response.ok(service.listSheets(groupID)).build(); } catch (ItemNotFoundException e) { return Response.status(404).entity(e).build(); } } /** * @return A list of the ticker names for the given sheet. */ @GET @Path("/sheets/{sheetID}") @Produces("application/json") public Response listTickers(@PathParam("sheetID") String sheetID) { try { return Response.ok(service.listColumns(sheetID)).build(); } catch (ItemNotFoundException e) { return Response.status(404).entity(e).build(); } } /** * Returns a list of the slots for the specified ticker. */ @GET @Path("/sheets/{sheetID}/tickers/{ticker}") @Produces("application/json") public Response listSlots(@PathParam("sheetID") String sheetID, @PathParam("ticker") String tickerName) { try { return Response.ok(service.listColumnSlots(sheetID, tickerName)).build(); } catch (ItemNotFoundException e) { return Response.status(Status.NOT_FOUND).entity(e).build(); } } /** * @return Response whose body is has booked the slot (null if no one) and the tick * they have booked to do. */ @GET @Path("/sheets/{sheetID}/tickers/{ticker}/{startTime}") @Produces("application/json") public Response getBooking(@PathParam("sheetID") String sheetID, @PathParam("ticker") String tickerName, @PathParam("startTime") Date startTime) { try { return Response.ok(service.showBooking(sheetID, tickerName, startTime.getTime())).build(); } catch (ItemNotFoundException e) { return Response.status(Status.NOT_FOUND).entity(e).build(); } } /** * Removes all bookings that haven't yet started for the given * user in the given sheet. */ @DELETE @Path("/students/{crsid}/bookings/{sheetID}") @Consumes("text/plain") public Response removeAllStudentBookings(@PathParam("sheetID") String sheetID, @PathParam("crsid") String crsid, String authCode) { try { service.removeAllUserBookings(sheetID, crsid, authCode); return Response.ok().build(); } catch (NotAllowedException e) { return Response.status(Status.FORBIDDEN).entity(e).build(); } catch (ItemNotFoundException e) { return Response.status(Status.NOT_FOUND).entity(e).build(); } } public Response allowSignup(String crsid, String groupID, String tickID) { try { service.listSheets(groupID); // to see if group exists } catch (ItemNotFoundException e) { // if it doesn't, create it try { createGroup(groupID); } catch (DuplicateNameException e1) { e1.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("The group was found to both exist and not exist " + "in the signups database, sorry.\n"+e1).build(); } } String groupAuthCode = db.getAuthCode(groupID); try { Map<String, String> map = new HashMap<String, String>(); map.put(tickID, null); service.addPermissions(groupID, crsid, new PermissionsBean(map, groupAuthCode)); return Response.ok().build(); } catch (NotAllowedException e) { e.printStackTrace(); return Response.status(Status.FORBIDDEN) .entity(e).build(); } catch (ItemNotFoundException e) { e.printStackTrace(); return Response.status(Status.NOT_FOUND) .entity(e).build(); } } public Response disallowSignup(String crsid, String groupID, String tickID) { Map<String, String> map = new HashMap<String, String>(); map.put(tickID, null); try { service.removePermissions(groupID, crsid, new PermissionsBean(map, db.getAuthCode(groupID))); } catch (NotAllowedException e) { e.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("Permission was denied - it shouldn't be.\n" + e).build(); } catch (ItemNotFoundException e) { e.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity(e).build(); } return Response.ok().build(); } /** * Ensures that the given student is assigned the given ticker * (if possible) in the future for the specified tick. */ @POST @Path("/students/{crsid}/permissions/{groupID}/{tickID}/{ticker}") public Response assignTickerForTickForUser(@Context HttpServletRequest request, @PathParam("crsid") String crsid, @PathParam("groupID") String groupID, @PathParam("tickID") String tickID, @PathParam("ticker") String ticker) { String callerCRSID = (String) request.getSession().getAttribute("RavenRemoteUser"); if (!db.getRoles(groupID, callerCRSID).contains(Role.MARKER)) { return Response.status(Status.FORBIDDEN).entity(Strings.INVALIDROLE).build(); } String groupAuthCode = db.getAuthCode(groupID); try { Map<String, String> map = new HashMap<String, String>(); map.put(tickID, ticker); service.addPermissions(groupID, crsid, new PermissionsBean(map, groupAuthCode)); return Response.ok().build(); } catch (NotAllowedException e) { e.printStackTrace(); return Response.status(Status.FORBIDDEN) .entity(e).build(); } catch (ItemNotFoundException e) { e.printStackTrace(); return Response.status(Status.NOT_FOUND) .entity(e).build(); } } public Response assignTickerForTickForUser(String crsid, String groupID, String tickID, String ticker) { String groupAuthCode = db.getAuthCode(groupID); try { Map<String, String> map = new HashMap<String, String>(); map.put(tickID, ticker); service.addPermissions(groupID, crsid, new PermissionsBean(map, groupAuthCode)); return Response.ok().build(); } catch (NotAllowedException e) { e.printStackTrace(); return Response.status(Status.FORBIDDEN) .entity(e).build(); } catch (ItemNotFoundException e) { e.printStackTrace(); return Response.status(Status.NOT_FOUND) .entity(e).build(); } } /* Below are the methods for the author workflow */ /** * Creates a new sheet for the given group. */ @POST @Path("/sheets") @Consumes("application/json") @Produces("application/json") public Response createSheet(@Context HttpServletRequest request, CreateSheetBean bean) { String crsid = (String) request.getSession().getAttribute("RavenRemoteUser"); if (!db.getRoles(bean.getGroupID(), crsid).contains(Role.AUTHOR)) { return Response.status(Status.FORBIDDEN).entity(Strings.INVALIDROLE).build(); } long sheetLengthInMinutes = (bean.getEndTime().getTime() - bean.getStartTime().getTime())/60000; if (sheetLengthInMinutes % bean.getSlotLengthInMinutes() != 0) { return Response.status(Status.BAD_REQUEST).entity("The difference in minutes " + "between the start and end times should be an integer multiple of " + "the length of the slots").build(); } Sheet newSheet = new Sheet(bean.getTitle(), bean.getDescription(), bean.getLocation()); String id; String auth; try { SheetInfo info = service.addSheet(newSheet); id = info.getSheetID(); auth = info.getAuthCode(); db.addAuthCode(id, auth); } catch (DuplicateNameException e) { return Response.serverError().entity("This sheet already seems to exist").build(); } for (String ticker : bean.getTickerNames()) { try { service.createColumn(id, new CreateColumnBean(ticker, auth, bean.getStartTime(), bean.getEndTime(), bean.getSlotLengthInMinutes())); } catch (ItemNotFoundException e) { e.printStackTrace(); throw new RuntimeException("This should only happen if the sheet or column is not found " + "but we are creating them"); } catch (NotAllowedException e) { e.printStackTrace(); throw new RuntimeException("We should have permission to access the sheet we have just created"); } catch (DuplicateNameException e) { /* * Actually, this isn't the end of the world, we can just ignore it. * e.printStackTrace(); * return Response.status(Status.BAD_REQUEST).entity("You must have specified two " * + "identical columns (or slots)").build(); */ } } try { service.addSheetToGroup(bean.getGroupID(), new GroupSheetBean(id, db.getAuthCode(bean.getGroupID()), auth)); } catch (ItemNotFoundException e) { // group doesn't yet exist: create and retry try { createGroup(bean.getGroupID()); service.addSheetToGroup(bean.getGroupID(), new GroupSheetBean(id, db.getAuthCode(bean.getGroupID()), auth)); } catch (DuplicateNameException e1) { e1.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("The group was found to both exist and not exist " + "in the signups database, sorry.\n"+e1).build(); } catch (ItemNotFoundException e1) { e1.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("The group was not found in the signups database, we " + "attempted to create it, but it still wasn't found." + "\n"+e1).build(); } catch (NotAllowedException e1) { e1.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("The group was not found in the signups database, " + "we attempted to create it, but permission was not " + "given - it should have been").build(); } } catch (NotAllowedException e) { e.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR) .entity("The auth codes stored by the database were for some " + "reason found to be incorrect./n" + e).build(); } return Response.ok().build(); } /** * Adds a new column to the sheet, filled with regularly spaced * empty slots. * @param sheetID * @param authCode * @param name * @param startTime Time of first slot * @param numberOfSlots * @param slotLength In minutes */ @POST @Path("/sheets/{sheetID}/tickers") @Consumes("application/json") @Produces("application/json") //TODO: argument needs to be a bean public Response addColumn(@PathParam("sheetID") String sheetID, String authCode, String name, Date startTime, Date endTime, int slotLength /* in minutes */) { try { service.createColumn(sheetID, new CreateColumnBean(name, authCode, startTime, endTime, slotLength)); } catch (ItemNotFoundException e) { e.printStackTrace(); return Response.status(Status.NOT_FOUND).entity(e).build(); } catch (NotAllowedException e) { e.printStackTrace(); return Response.status(Status.FORBIDDEN).entity(e).build(); } catch (DuplicateNameException e) { e.printStackTrace(); return Response.status(Status.INTERNAL_SERVER_ERROR).entity(e).build(); } return Response.ok().build(); } /** * Deletes the specified column from the sheet. This also deletes * all the bookings made for that column. */ @DELETE @Path("/sheets/{sheetID}/tickers/{ticker}") @Consumes("text/plain") @Produces("application/json") public Response deleteColumn(@PathParam("sheetID") String sheetID, @PathParam("ticker") String ticker, String authCode) { try { service.deleteColumn(sheetID, ticker, authCode); } catch (NotAllowedException e) { e.printStackTrace(); return Response.status(Status.FORBIDDEN).entity(e).build(); } catch (ItemNotFoundException e) { e.printStackTrace(); return Response.status(Status.NOT_FOUND).entity(e).build(); } return Response.ok().build(); } /** * Modifies bookings no matter what. */ @POST @Path("/sheets/{sheetID}/bookings/{startTime}") @Consumes("application/json") // TODO: check arguments // TODO: unify with normal modify booking and even perhaps make booking TODO: maybe not public Response forceModifyBooking(@PathParam("sheetID") String sheetID, String authCode, String tickID, @PathParam("sheetID") Long startTime, String currentlyBookedUser, String userToBook) { String ticker = null; for (Slot slot : service.listUserSlots(currentlyBookedUser)) { if (slot.getStartTime().getTime() == startTime && slot.getComment().equals(tickID) && slot.getSheetID().equals(sheetID)) { ticker = slot.getColumnName(); } } if (ticker == null) { return Response.status(Status.NOT_FOUND).entity("The slot was not found").build(); } try { service.book(sheetID, ticker, startTime, new SlotBookingBean(currentlyBookedUser, userToBook, tickID, authCode)); } catch (ItemNotFoundException e) { e.printStackTrace(); return Response.status(Status.NOT_FOUND).entity(e).build(); } catch (NotAllowedException e) { e.printStackTrace(); return Response.status(Status.FORBIDDEN).entity(e).build(); } return Response.ok().build(); } public void createGroup(String groupID) throws DuplicateNameException { String groupAuthCode = service.addGroup(new Group(groupID)); db.addAuthCode(groupID, groupAuthCode); } }
Updated method that removes all future bookings for a no show student
ETick/src/main/java/uk/ac/cam/cl/ticking/signups/TickSignups.java
Updated method that removes all future bookings for a no show student
<ide><path>Tick/src/main/java/uk/ac/cam/cl/ticking/signups/TickSignups.java <ide> */ <ide> @DELETE <ide> @Path("/students/{crsid}/bookings/{sheetID}") <del> @Consumes("text/plain") <del> public Response removeAllStudentBookings(@PathParam("sheetID") String sheetID, <del> @PathParam("crsid") String crsid, String authCode) { <del> try { <del> service.removeAllUserBookings(sheetID, crsid, authCode); <add> public Response removeAllStudentBookings(@Context HttpServletRequest request, <add> @PathParam("sheetID") String sheetID, <add> @PathParam("crsid") String crsid) { <add> String callingCRSID = (String) request.getSession().getAttribute("RavenRemoteUser"); <add> List<String> groupIDs; <add> try { <add> groupIDs = service.getGroupIDs(sheetID); <add> } catch (ItemNotFoundException e) { <add> return Response.status(Status.NOT_FOUND).entity(e).build(); <add> } <add> if (groupIDs.size() != 1) { <add> return Response.status(Status.INTERNAL_SERVER_ERROR) <add> .entity("There should be precisely one group associated " <add> + "with this sheet, but there seems to be " + groupIDs.size()).build(); <add> } <add> String groupID = groupIDs.get(0); <add> if (!db.getRoles(groupID, callingCRSID).contains(Role.MARKER)) { <add> return Response.status(Status.FORBIDDEN).entity(Strings.INVALIDROLE).build(); <add> } <add> try { <add> service.removeAllUserBookings(sheetID, crsid, db.getAuthCode(sheetID)); <ide> return Response.ok().build(); <ide> } catch (NotAllowedException e) { <ide> return Response.status(Status.FORBIDDEN).entity(e).build(); <ide> return Response.status(Status.NOT_FOUND).entity(e).build(); <ide> } <ide> } <add> <add> <ide> <ide> public Response allowSignup(String crsid, String groupID, String tickID) { <ide> try {
Java
bsd-3-clause
4d5887cd11f9f6c2c27409633e85c3596ae36707
0
NCIP/caadapter,NCIP/caadapter,NCIP/caadapter
/** * The content of this file is subject to the caAdapter Software License (the "License"). * A copy of the License is available at: * [caAdapter CVS home directory]\etc\license\caAdapter_license.txt. or at: * http://ncicb.nci.nih.gov/infrastructure/cacore_overview/caadapter/indexContent * /docs/caAdapter_License */ package gov.nih.nci.cbiit.cmts.ui.mapping; import gov.nih.nci.cbiit.cmts.common.XSDParser; import gov.nih.nci.cbiit.cmts.core.Component; import gov.nih.nci.cbiit.cmts.core.ComponentType; import gov.nih.nci.cbiit.cmts.core.Mapping; import gov.nih.nci.cbiit.cmts.mapping.MappingFactory; import gov.nih.nci.cbiit.cmts.ui.actions.SaveAsMapAction; import gov.nih.nci.cbiit.cmts.ui.actions.SaveMapAction; import gov.nih.nci.cbiit.cmts.ui.common.ActionConstants; import gov.nih.nci.cbiit.cmts.ui.common.ContextManager; import gov.nih.nci.cbiit.cmts.ui.common.ContextManagerClient; import gov.nih.nci.cbiit.cmts.ui.common.DefaultSettings; import gov.nih.nci.cbiit.cmts.ui.common.MenuConstants; import gov.nih.nci.cbiit.cmts.ui.dnd.TreeDragTransferHandler; import gov.nih.nci.cbiit.cmts.ui.dnd.TreeTransferHandler; import gov.nih.nci.cbiit.cmts.ui.function.FunctionLibraryPane; import gov.nih.nci.cbiit.cmts.ui.jgraph.MiddlePanelJGraphController; import gov.nih.nci.cbiit.cmts.ui.jgraph.MiddlePanelMarqueeHandler; import gov.nih.nci.cbiit.cmts.ui.main.MainFrame; import gov.nih.nci.cbiit.cmts.ui.main.MainFrameContainer; import gov.nih.nci.cbiit.cmts.ui.properties.DefaultPropertiesPage; import gov.nih.nci.cbiit.cmts.ui.tree.MappingSourceTree; import gov.nih.nci.cbiit.cmts.ui.tree.MappingTargetTree; import gov.nih.nci.cbiit.cmts.ui.tree.TreeMouseAdapter; import gov.nih.nci.cbiit.cmts.ui.tree.TreeSelectionHandler; import gov.nih.nci.cbiit.cmts.ui.util.GeneralUtilities; import gov.nih.nci.cbiit.cmts.web.MainApplet; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.applet.Applet; import javax.swing.*; import javax.swing.tree.TreeNode; import javax.swing.tree.TreeSelectionModel; import javax.xml.bind.JAXBException; import org.apache.xerces.xs.XSNamedMap; /** * This class * * @author Chunqing Lin * @author LAST UPDATE $Author: wangeug $ * @since CMTS v1.0 * @version $Revision: 1.16 $ * @date $Date: 2009-12-02 18:53:16 $ * */ public class MappingMainPanel extends JPanel implements ActionListener, ContextManagerClient{ private static final String Cmps_V3_MESSAGE_FILE_DEFAULT_EXTENSION = ".map"; private static final String OPEN_DIALOG_TITLE_FOR_DEFAULT_SOURCE_FILE = "Open source data schema"; private static final String OPEN_DIALOG_TITLE_FOR_DEFAULT_TARGET_FILE = "Open target data schema"; private static final String SELECT_CSV_TIP = "select CSV"; private static final String SELECT_HMD_TIP = "select HMD"; private static final String SELECT_SOURCE = "Open Source..."; private static final String SELECT_TARGET = "Open Target..."; private static final String SOURCE_TREE_FILE_DEFAULT_EXTENTION = ".xsd"; private static final String TARGET_TREE_FILE_DEFAULT_EXTENTION = ".xsd"; private Mapping mapping = null; private File mappingSourceFile = null; private File mappingTargetFile = null; private MappingMiddlePanel middlePanel = null; private File saveFile = null; private JTextField sourceLocationArea = new JTextField(); private MappingTreeScrollPane sourceScrollPane = new MappingTreeScrollPane(MappingTreeScrollPane.DRAW_NODE_TO_RIGHT); private MappingSourceTree sTree = null; private JTextField targetLocationArea = new JTextField(); private MappingTreeScrollPane targetScrollPane = new MappingTreeScrollPane(MappingTreeScrollPane.DRAW_NODE_TO_LEFT); private MappingTargetTree tTree = null; private MiddlePanelJGraphController graphController =null; private MainFrameContainer mainFrame = null; public MappingMainPanel(MainFrameContainer mainFrame) throws Exception { this.setBorder(BorderFactory.createEmptyBorder()); this.setLayout(new BorderLayout()); this.mainFrame = mainFrame; middlePanel = new MappingMiddlePanel(this); graphController = new MiddlePanelJGraphController(this); // middlePanel.setGraphController(graphController); MiddlePanelMarqueeHandler marquee=(MiddlePanelMarqueeHandler)middlePanel.getGraph().getMarqueeHandler(); marquee.setController(graphController); this.add(getCenterPanel(true), BorderLayout.CENTER); } public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); try { boolean everythingGood = true; if (SELECT_SOURCE.equals(command)) { //this.sourceButtonPanel.repaint(); File file = DefaultSettings.getUserInputOfFileFromGUI(this, //FileUtil.getUIWorkingDirectoryPath(), SOURCE_TREE_FILE_DEFAULT_EXTENTION, OPEN_DIALOG_TITLE_FOR_DEFAULT_SOURCE_FILE, false, false); if (file != null) { everythingGood = processOpenSourceTree(file, true, true); } } else if (SELECT_TARGET.equals(command)) { //this.targetButtonPanel.repaint(); File file = DefaultSettings.getUserInputOfFileFromGUI(this, // TARGET_TREE_FILE_DEFAULT_EXTENTION, OPEN_DIALOG_TITLE_FOR_DEFAULT_TARGET_FILE, false, false); //FileUtil.getUIWorkingDirectoryPath(), // TARGET_TREE_FILE_DEFAULT_EXTENTION+";"+Cmps_V3_MESSAGE_FILE_DEFAULT_EXTENSION, OPEN_DIALOG_TITLE_FOR_DEFAULT_TARGET_FILE, false, false); //last added fileExtension :.h3s will be set as default Cmps_V3_MESSAGE_FILE_DEFAULT_EXTENSION+";"+TARGET_TREE_FILE_DEFAULT_EXTENTION, OPEN_DIALOG_TITLE_FOR_DEFAULT_TARGET_FILE, false, false); if (file != null) { everythingGood = processOpenTargetTree(file, true, true); } } if (!everythingGood) { // Message msg = MessageResources.getMessage("GEN3", new Object[0]); // JOptionPane.showMessageDialog(this, msg.toString(), "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { e1.printStackTrace(); DefaultSettings.reportThrowableToLogAndUI(this, e1, "", this, false, false); } } protected void buildSourceTree(Object metaInfo, File absoluteFile, boolean isToResetGraph) throws Exception { TreeNode nodes=loadSourceTreeData(metaInfo,absoluteFile); //Build the source tree sTree = new MappingSourceTree(middlePanel, nodes); sTree.addMouseListener(new TreeMouseAdapter()); TreeSelectionHandler treeSelectionHanderl=new TreeSelectionHandler(getGraphController()); sTree.getSelectionModel().addTreeSelectionListener(treeSelectionHanderl); sTree.setTransferHandler(new TreeDragTransferHandler()); sTree.setDragEnabled(true); // sTree.setDropMode(DropMode.ON); sTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); sourceScrollPane.setViewportView(sTree); sTree.expandAll(); //register collapse all and expand all actions. // sourceTreeCollapseAllAction.setTree(sTree); // sourceTreeExpandAllAction.setTree(sTree); // sTree.getInputMap().put(sourceTreeCollapseAllAction.getAcceleratorKey(), sourceTreeCollapseAllAction.getName()); // sTree.getActionMap().put(sourceTreeCollapseAllAction.getName(), sourceTreeCollapseAllAction); // sTree.getInputMap().put(sourceTreeExpandAllAction.getAcceleratorKey(), sourceTreeExpandAllAction.getName()); // sTree.getActionMap().put(sourceTreeExpandAllAction.getName(), sourceTreeExpandAllAction); if (tTree != null && isToResetGraph) { resetMiddlePanel(); } if (absoluteFile != null) { String absoluteFilePath = absoluteFile.getAbsolutePath(); sourceLocationArea.setText(absoluteFilePath); sourceLocationArea.setToolTipText(absoluteFilePath); mappingSourceFile = absoluteFile; } else { mappingSourceFile = null; } if (this.getRootPane() != null) { this.getRootPane().repaint(); } // getMappingFileSynchronizer().registerFile(MappingFileSynchronizer.FILE_TYPE.Source_File, absoluteFile); } protected void buildTargetTree(Object metaInfo, File absoluteFile, boolean isToResetGraph) throws Exception { TreeNode nodes=loadTargetTreeData(metaInfo,absoluteFile); //Build the target tree tTree = new MappingTargetTree(this.getMiddlePanel(), nodes); tTree.addMouseListener(new TreeMouseAdapter()); TreeSelectionHandler treeSelectionHanderl=new TreeSelectionHandler(getGraphController()); tTree.getSelectionModel().addTreeSelectionListener(treeSelectionHanderl); TreeTransferHandler targetTreeTransferHandler= new TreeTransferHandler(this); tTree.setTransferHandler(targetTreeTransferHandler); tTree.setDropMode(DropMode.ON); tTree.setDragEnabled(true); targetScrollPane.setViewportView(tTree); tTree.expandAll(); // //register collapse all and expand all actions. // targetTreeCollapseAllAction.setTree(tTree); // targetTreeExpandAllAction.setTree(tTree); // tTree.getInputMap().put(targetTreeCollapseAllAction.getAcceleratorKey(), targetTreeCollapseAllAction.getName()); // tTree.getActionMap().put(targetTreeCollapseAllAction.getName(), targetTreeCollapseAllAction); // tTree.getInputMap().put(targetTreeExpandAllAction.getAcceleratorKey(), targetTreeExpandAllAction.getName()); // tTree.getActionMap().put(targetTreeExpandAllAction.getName(), targetTreeExpandAllAction); if (sTree != null && isToResetGraph) { resetMiddlePanel(); } if (absoluteFile != null) { String absoluteFilePath = absoluteFile.getAbsolutePath(); targetLocationArea.setText(absoluteFilePath); targetLocationArea.setToolTipText(absoluteFilePath); mappingTargetFile = absoluteFile;//new File(absoluteFilePath); } else { mappingTargetFile = null; } if (this.getRootPane() != null) { this.getRootPane().repaint(); } // getMappingFileSynchronizer().registerFile(MappingFileSynchronizer.FILE_TYPE.Target_File, absoluteFile); //// drop target for DnD from source tree. // targetTreeDropTransferHandler = new TargetTreeDropTransferHandler(tTree, getMappingDataManager(), DnDConstants.ACTION_LINK); } /** * Provide the extended implementation of this method by adding additional files of source and target; * * @return a list of file objects that this context is associated with. */ public java.util.List<File> getAssociatedFileList() { List<File> resultList = new ArrayList<java.io.File>(); if(saveFile!=null) { resultList.add(saveFile); } if (mappingSourceFile != null) { resultList.add(mappingSourceFile); } if (mappingTargetFile != null) { resultList.add(mappingTargetFile); } return resultList; } /** * @return the graphController */ public MiddlePanelJGraphController getGraphController() { return graphController; } protected JComponent getCenterPanel(boolean functionPaneRequired) {//construct the top level layout of mapping panel /** * GUI Layout: * JSplitPane - Horizontal: --> leftRightSplitPane * left: JSplitPane - Horizontal: --> topCenterPanel, centerSplitPane * left: source panel; --> sourceButtonPanel * right: JSplitPane - Horizontal: --> rightSplitPane * left: middle panel for graph; -->middleContainerPanel * right: target panel; -->targetButtonPanel * right: JSplitPane - Vertical: -->topBottomSplitPane * top: functional pane; -->functionPane * bottom: properties panel; -->propertiesPane */ JSplitPane leftRightSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); DefaultSettings.setDefaultFeatureForJSplitPane(leftRightSplitPane); int locDiv = (int) (mainFrame.getAssociatedUIContainer().getWidth() * 0.85); leftRightSplitPane.setDividerLocation(locDiv); //.setDividerLocation(0.85); //System.out.println("First locDiv : " + locDiv); leftRightSplitPane.setLeftComponent(getTopLevelLeftPanel()); leftRightSplitPane.setRightComponent(getTopLevelRightPanel(functionPaneRequired)); return leftRightSplitPane; } /** * return the close action inherited with this client. * @return the close action inherited with this client. */ public Action getDefaultCloseAction() {//by doing this way, the menu and the panel will use the same close action. Map actionMap = getMenuItems(MenuConstants.FILE_MENU_NAME); Action closeAction = (Action) actionMap.get(ActionConstants.CLOSE); return closeAction; } /** * return the open action inherited with this client. */ public Action getDefaultOpenAction() { ContextManager contextManager = ContextManager.getContextManager(); Action openAction=contextManager.getDefinedAction(ActionConstants.OPEN_MAP_FILE); return openAction; } /** * return the save action inherited with this client. * @return the save action inherited with this client. */ public Action getDefaultSaveAction() { Map actionMap = getMenuItems(MenuConstants.FILE_MENU_NAME); Action saveAction = (Action) actionMap.get(ActionConstants.SAVE); return saveAction; } /** * @return the mapping */ public Mapping getMapping() { if(this.mapping == null){ this.mapping = new Mapping(); getGraphController().setMappingData(mapping); } return mapping; } public Map getMenuItems(String menu_name) { Action action = null; Map <String, Action>actionMap = null; ContextManager contextManager = ContextManager.getContextManager(); actionMap = contextManager.getClientMenuActions("CMTS", menu_name); if (MenuConstants.FILE_MENU_NAME.equals(menu_name)) { JRootPane rootPane = this.getRootPane(); if (rootPane == null){ //rootpane is not null implies this panel is fully displayed; //on the flip side, if it is null, it implies it is under certain construction. contextManager.enableAction(ActionConstants.NEW_MAP_FILE, true); contextManager.enableAction(ActionConstants.OPEN_MAP_FILE, true); contextManager.enableAction(ActionConstants.CLOSE, false); contextManager.enableAction(ActionConstants.SAVE, false); contextManager.enableAction(ActionConstants.SAVE_AS, false); }else{ contextManager.enableAction(ActionConstants.CLOSE, true); contextManager.enableAction(ActionConstants.SAVE, true); contextManager.enableAction(ActionConstants.SAVE_AS, true); } } //since the action depends on the panel instance, //the old action instance should be removed if (actionMap!=null) contextManager.removeClientMenuAction("CMTS", menu_name, ""); action = new SaveMapAction(this); contextManager.addClientMenuAction("CMTS", MenuConstants.FILE_MENU_NAME,ActionConstants.SAVE, action); action.setEnabled(true); action = new SaveAsMapAction(this); contextManager.addClientMenuAction("CMTS", MenuConstants.FILE_MENU_NAME,ActionConstants.SAVE_AS, action); action.setEnabled(true); actionMap = contextManager.getClientMenuActions("CMTS", menu_name); return actionMap; } public MappingMiddlePanel getMiddlePanel() { return middlePanel; } /** * Return the top root container (frame or dialog or window) this panel is associated with. * @return the top root container (frame or dialog or window) this panel is associated with. */ public Container getRootContainer() { return DefaultSettings.findRootContainer(this); } /** * Return the save file. * @return the save file. */ public File getSaveFile() { return saveFile; } public JScrollPane getSourceScrollPane() { return sourceScrollPane; } public JTree getSourceTree() { return sTree; } public JScrollPane getTargetScrollPane() { return targetScrollPane; } public JTree getTargetTree() { return tTree; } /** * Return a list of Action objects that is included in this Context manager. * @return a list of Action objects that is included in this Context manager. */ public java.util.List<Action> getToolbarActionList() { java.util.List<Action> actions = new ArrayList<Action>(); actions.add(getDefaultOpenAction()); //the menu bar display its buttons inorder Map <String, Action>actionMap = getMenuItems(MenuConstants.TOOLBAR_MENU_NAME); actions.add(actionMap.get(ActionConstants.SAVE)); actions.add(actionMap.get(ActionConstants.VALIDATE)); //add the "Refresh" menu if exist actions.add(actionMap.get(ActionConstants.REFRESH)); return actions; } protected JPanel getTopLevelLeftPanel() { JPanel topCenterPanel = new JPanel(new BorderLayout()); topCenterPanel.setBorder(BorderFactory.createEtchedBorder()); JSplitPane centerSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); DefaultSettings.setDefaultFeatureForJSplitPane(centerSplitPane); int frameWidth = mainFrame.getAssociatedUIContainer().getWidth(); //construct source panel JPanel sourceButtonPanel = new JPanel(new BorderLayout()); sourceButtonPanel.setBorder(BorderFactory.createEmptyBorder()); JPanel sourceLocationPanel = new JPanel(new BorderLayout(2, 0)); sourceLocationPanel.setBorder(BorderFactory.createEmptyBorder()); // sourceTreeCollapseAllAction = new TreeCollapseAllAction(sTree); // sourceTreeExpandAllAction = new TreeExpandAllAction(sTree); JToolBar sourceTreeToolBar = new JToolBar("Source Tree Tool Bar"); sourceTreeToolBar.setFloatable(false); // sourceTreeToolBar.add(sourceTreeExpandAllAction); // sourceTreeToolBar.add(sourceTreeCollapseAllAction); sourceLocationPanel.add(sourceTreeToolBar, BorderLayout.WEST); sourceLocationArea.setEditable(false); //sourceLocationArea.setPreferredSize(new Dimension((DefaultSettings.FRAME_DEFAULT_WIDTH / 10), 24)); sourceLocationArea.setPreferredSize(new Dimension((frameWidth / 10), 24)); sourceLocationPanel.add(sourceLocationArea, BorderLayout.CENTER); JButton openSourceButton = new JButton(SELECT_SOURCE); sourceLocationPanel.add(openSourceButton, BorderLayout.EAST); openSourceButton.setMnemonic('S'); openSourceButton.setToolTipText(SELECT_CSV_TIP); openSourceButton.addActionListener(this); sourceButtonPanel.add(sourceLocationPanel, BorderLayout.NORTH); //sourceScrollPane.setSize(new Dimension((DefaultSettings.FRAME_DEFAULT_WIDTH / 4), (int) (DefaultSettings.FRAME_DEFAULT_HEIGHT / 1.5))); sourceScrollPane.setSize(new Dimension((int)((frameWidth*0.85) / 4), (int) (DefaultSettings.FRAME_DEFAULT_HEIGHT / 1.5))); sourceButtonPanel.add(sourceScrollPane, BorderLayout.CENTER); //construct target panel JPanel targetButtonPanel = new JPanel(new BorderLayout()); targetButtonPanel.setBorder(BorderFactory.createEmptyBorder()); JPanel targetLocationPanel = new JPanel(new BorderLayout(2, 0)); targetLocationPanel.setBorder(BorderFactory.createEmptyBorder()); // targetTreeCollapseAllAction = new TreeCollapseAllAction(tTree); // targetTreeExpandAllAction = new TreeExpandAllAction(tTree); JToolBar targetTreeToolBar = new JToolBar("Target Tree Tool Bar"); targetTreeToolBar.setFloatable(false); // targetTreeToolBar.add(targetTreeExpandAllAction); // targetTreeToolBar.add(targetTreeCollapseAllAction); targetLocationPanel.add(targetTreeToolBar, BorderLayout.WEST); targetLocationArea.setEditable(false); //targetLocationArea.setPreferredSize(new Dimension((DefaultSettings.FRAME_DEFAULT_WIDTH / 10), 24)); targetLocationArea.setPreferredSize(new Dimension((frameWidth / 10), 24)); targetLocationPanel.add(targetLocationArea, BorderLayout.CENTER); JButton openTargetButton = new JButton(SELECT_TARGET); targetLocationPanel.add(openTargetButton, BorderLayout.EAST); openTargetButton.setMnemonic('T'); openTargetButton.setToolTipText(SELECT_HMD_TIP); openTargetButton.addActionListener(this); targetButtonPanel.add(targetLocationPanel, BorderLayout.NORTH); targetButtonPanel.add(targetScrollPane, BorderLayout.CENTER); //targetButtonPanel.setPreferredSize(new Dimension((DefaultSettings.FRAME_DEFAULT_WIDTH / 5), (int) (DefaultSettings.FRAME_DEFAULT_HEIGHT / 1.5))); targetButtonPanel.setPreferredSize(new Dimension((int)((frameWidth*0.85) / 5), (int) (DefaultSettings.FRAME_DEFAULT_HEIGHT / 1.5))); //construct middle panel JPanel middleContainerPanel = new JPanel(new BorderLayout()); JLabel placeHolderLabel = new JLabel(); //placeHolderLabel.setPreferredSize(new Dimension((int) (DefaultSettings.FRAME_DEFAULT_WIDTH / 3.5), 24)); placeHolderLabel.setPreferredSize(new Dimension((int)((frameWidth*0.85) / 3.5), 24)); middleContainerPanel.add(placeHolderLabel, BorderLayout.NORTH); middleContainerPanel.add(middlePanel, BorderLayout.CENTER); JSplitPane rightSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); DefaultSettings.setDefaultFeatureForJSplitPane(rightSplitPane); //rightSplitPane.setDividerLocation(0.5); rightSplitPane.setDividerLocation(50); rightSplitPane.setLeftComponent(middleContainerPanel); rightSplitPane.setRightComponent(targetButtonPanel); rightSplitPane.setDividerLocation((int)((frameWidth*0.85)/3)); centerSplitPane.setLeftComponent(sourceButtonPanel); centerSplitPane.setRightComponent(rightSplitPane); centerSplitPane.setDividerLocation(((int)((frameWidth*0.85)/3)) - (centerSplitPane.getDividerSize()*2)); topCenterPanel.add(centerSplitPane, BorderLayout.CENTER); //topCenterPanel.setPreferredSize(new Dimension((int) (DefaultSettings.FRAME_DEFAULT_WIDTH * 0.8), (int) (DefaultSettings.FRAME_DEFAULT_HEIGHT / 1.5))); topCenterPanel.setPreferredSize(new Dimension((int) (frameWidth * 0.85), (int) (DefaultSettings.FRAME_DEFAULT_HEIGHT / 1.5))); return topCenterPanel; } /** * This constructs function and properties panels. * * @return the top level right pane. */ private JComponent getTopLevelRightPanel(boolean functionPaneRequired) { FunctionLibraryPane functionPane = new FunctionLibraryPane(this); functionPane.setBorder(BorderFactory.createTitledBorder("Functions")); DefaultPropertiesPage propertiesPane = new DefaultPropertiesPage(getGraphController().getPropertiesSwitchController()); Dimension rightMostDim = new Dimension((DefaultSettings.FRAME_DEFAULT_WIDTH / 11), 50); propertiesPane.setPreferredSize(rightMostDim); functionPane.setPreferredSize(rightMostDim); JSplitPane topBottomSplitPane = null; if(functionPaneRequired) { topBottomSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, functionPane, propertiesPane); DefaultSettings.setDefaultFeatureForJSplitPane(topBottomSplitPane); int locDiv = (int) (mainFrame.getAssociatedUIContainer().getHeight() * 0.2); if (locDiv < 130) locDiv = 130; topBottomSplitPane.setDividerLocation(locDiv); //System.out.println("VVVV topBottomSplitPane.getDividerLocation():" + topBottomSplitPane.getDividerLocation()); } else { topBottomSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, new JPanel(), propertiesPane); DefaultSettings.setDefaultFeatureForJSplitPane(topBottomSplitPane); topBottomSplitPane.setDividerLocation(10); } return topBottomSplitPane; } public boolean isChanged() { // TODO Auto-generated method stub return false; } protected TreeNode loadSourceTreeData(Object metaInfo, File absoluteFile)throws Exception { TreeNode node = null; if(metaInfo instanceof Mapping){ Mapping.Components components = ((Mapping)metaInfo).getComponents(); List<Component> l = components.getComponent(); for(Component c:l){ if(c.getType().equals(ComponentType.SOURCE)) node = new ElementMetaLoader(ElementMetaLoader.SOURCE_MODE).loadData(c); } }else{ throw new RuntimeException("ElementMetaNodeLoader.loadData() input " + "not recognized. " + metaInfo); } return node; } protected TreeNode loadTargetTreeData( Object metaInfo, File absoluteFile)throws Exception { TreeNode node = null; if(metaInfo instanceof Mapping){ Mapping.Components components = ((Mapping)metaInfo).getComponents(); List<Component> l = components.getComponent(); for(Component c:l){ if(c.getType().equals(ComponentType.TARGET)) node = new ElementMetaLoader(ElementMetaLoader.TARGET_MODE).loadData(c); } }else{ throw new RuntimeException("ElementMetaNodeLoader.loadData() input " + "not recognized. " + metaInfo); } return node; } /** * Called by actionPerformed() and overridable by descendant classes. * * @param file * @throws Exception changed from protected to pulic by sean */ public void processOpenMapFile(File file) throws Exception { long stTime=System.currentTimeMillis(); // parse the file. Mapping mapping = MappingFactory.loadMapping(file); //build source tree buildSourceTree(mapping, null, false); //build target tree buildTargetTree(mapping, null, false); for (Component mapComp:mapping.getComponents().getComponent()) { if (mapComp.getRootElement()==null) continue; JTextField tField = null; if (mapComp.getType().value().equals(ComponentType.SOURCE.value())) tField = sourceLocationArea; if (mapComp.getType().value().equals(ComponentType.TARGET.value())) tField = targetLocationArea; if (tField != null) { String c = mapComp.getLocation(); if (c == null) c = ""; else c = c.trim(); if (!c.equals("")) { tField.setText(mapComp.getLocation()); //tField.setEditable(true); //tField.setFocusable(false); } } if (mapComp.getType().value().equals(ComponentType.TARGET.value())) targetLocationArea.setText(mapComp.getLocation()); } getGraphController().setMappingData(mapping); setSaveFile(file); getMiddlePanel().renderInJGraph(); System.out.println("CmtsMappingPanel.processOpenMapFile()..timespending:"+(System.currentTimeMillis()-stTime)); } /** * Called by actionPerformed() and overridable by descendant classes. * * @param file * @throws Exception */ protected boolean processOpenSourceTree(File file, boolean isToResetGraph, boolean supressReportIssuesToUI) throws Exception { // String fileExtension = FileUtil.getFileExtension(file, true); XSDParser p = new XSDParser(); p.loadSchema(file.getPath(), null);//(file); CellRenderXSObject srcRoot = userSelectRoot(p); if(srcRoot == null || srcRoot.getCoreObject().getName().trim().length() == 0) return false; MappingFactory.loadMetaXSD(getMapping(), p,srcRoot.getCoreObject().getNamespace(), srcRoot.getCoreObject().getName(), ComponentType.SOURCE); buildSourceTree(getMapping(), file, isToResetGraph); return true; } /** * Called by actionPerformed() and overridable by descendant classes. * * @param file * @throws Exception */ protected boolean processOpenTargetTree(File file, boolean isToResetGraph, boolean supressReportIssuesToUI) throws Exception { // String fileExtension = FileUtil.getFileExtension(file, true); XSDParser p = new XSDParser(); p.loadSchema(file.getPath(), null); CellRenderXSObject trgtRoot = userSelectRoot(p); if(trgtRoot == null || trgtRoot.getCoreObject().getName().trim().length() == 0) return false; MappingFactory.loadMetaXSD(getMapping(), p, trgtRoot.getCoreObject().getNamespace(), trgtRoot.getCoreObject().getName(), ComponentType.TARGET); buildTargetTree(getMapping(), file, isToResetGraph); // middlePanel.getMappingDataManager().registerTargetComponent(metaInfo, file); return true; } private void resetMiddlePanel() { if (middlePanel != null) { // middlePanel.resetGraph(); middlePanel.repaint(); } } /** * Explicitly set the value. * * @param newValue */ public void setChanged(boolean newValue) { getGraphController().setGraphChanged(newValue); } /** * @param mapping the mapping to set */ public void setMapping(Mapping mapping) { this.mapping = mapping; } /** * Set a new save file. * * @param saveFile * @return true if the value is changed, false otherwise. */ public boolean setSaveFile(File saveFile) { //removed the equal check so as to support explicit refresh or reload call. // ContextManager contextManager = ContextManager.getContextManager(); boolean sameFile = GeneralUtilities.areEqual(this.saveFile, saveFile); if(!sameFile) {//remove interest in the context file manager, first for old file // contextManager.getContextFileManager().removeFileUsageListener(this); } this.saveFile = saveFile; // if(!sameFile) // {//register interest in the context file manager for new file // contextManager.getContextFileManager().registerFileUsageListener(this); // } updateTitle(this.saveFile.getName()); // getMappingFileSynchronizer().registerFile(MappingFileSynchronizer.FILE_TYPE.Mapping_File, saveFile); return true; } @Override public void setSize(int width, int height) { double topCenterFactor = 1; sourceLocationArea.setSize(new Dimension((width / 6), 25)); sourceScrollPane.setSize(new Dimension((int) (width / 4.5), (int) (height * topCenterFactor))); targetLocationArea.setSize(new Dimension(width / 6, 25)); targetScrollPane.setSize(new Dimension((int) (width / 4.5), (int) (height * topCenterFactor))); middlePanel.setSize(new Dimension((width / 4), (int) (height * topCenterFactor))); topCenterFactor = 0.5; Dimension rightMostDim = new Dimension((width / 5), (int) (height * topCenterFactor)); // propertiesPane.setSize(rightMostDim); // functionPane.setSize(rightMostDim); } public void synchronizeRegisteredFile(boolean notigyOberver) { //do nothing, only the "MappingFilePanel" will implement it } /** * Overridable function to update Title in the tabbed pane. * @param newTitle */ private void updateTitle(String newTitle) { JRootPane rootPane = getRootPane(); if (rootPane != null) { Container container = rootPane.getParent(); if (container instanceof MainFrame) { ((MainFrame)container).setCurrentPanelTitle(newTitle); } if (container instanceof MainApplet) { ((MainApplet)container).setCurrentPanelTitle(newTitle); } } } /** * Promote user to select a root node:Element or Complex type * @param xsdParser * @return */ private CellRenderXSObject userSelectRoot(XSDParser xsdParser) { XSNamedMap[] map = xsdParser.getMappableNames(); CellRenderXSObject[] choices = new CellRenderXSObject[map[0].getLength()+map[1].getLength()]; int pos = 0; for(int i=0; i<map[0].getLength(); i++) choices[pos++] =new CellRenderXSObject(map[0].item(i));//.getName(); for(int i=0; i<map[1].getLength(); i++) choices[pos++] = new CellRenderXSObject(map[1].item(i));//.getNamespace() +":" +map[1].item(i).getName(); CellRenderXSObject chosenRoot = null; Container con = this; while(con != null) { if ((con instanceof Frame)||(con instanceof Applet)) { chosenRoot = (CellRenderXSObject)DefaultSettings.showListChoiceDialog(con, "choose root element", "Please choose root element", choices); break; } con = con.getParent(); } //CellRenderXSObject chosenRoot = (CellRenderXSObject)DefaultSettings.showListChoiceDialog(MainFrame.getInstance(), "choose root element", "Please choose root element", choices); return chosenRoot; } } /** * HISTORY: $Log: not supported by cvs2svn $ * HISTORY: Revision 1.15 2009/11/23 18:31:44 wangeug * HISTORY: create new package: ui.main * HISTORY: * HISTORY: Revision 1.14 2009/11/03 18:32:54 wangeug * HISTORY: clean codes: keep MiddlePanelJGraphController only with MiddleMappingPanel * HISTORY: * HISTORY: Revision 1.13 2009/10/30 14:45:30 wangeug * HISTORY: simplify code: only respond to link highter * HISTORY: * HISTORY: Revision 1.12 2009/10/28 16:47:06 wangeug * HISTORY: clean codes * HISTORY: * HISTORY: Revision 1.11 2009/10/27 19:26:16 wangeug * HISTORY: clean codes * HISTORY: * HISTORY: Revision 1.10 2009/10/27 18:25:08 wangeug * HISTORY: hook property panel with tree nodes * HISTORY: * HISTORY: Revision 1.9 2009/10/16 17:36:34 wangeug * HISTORY: use cell renderer * HISTORY: * HISTORY: Revision 1.8 2009/10/15 18:35:33 wangeug * HISTORY: clean codes * HISTORY: * HISTORY: Revision 1.7 2008/12/29 22:18:18 linc * HISTORY: function UI added. * HISTORY: * HISTORY: Revision 1.6 2008/12/09 19:04:17 linc * HISTORY: First GUI release * HISTORY: * HISTORY: Revision 1.5 2008/12/04 21:34:20 linc * HISTORY: Drap and Drop support with new Swing. * HISTORY: * HISTORY: Revision 1.4 2008/12/03 20:46:14 linc * HISTORY: UI update. * HISTORY: * HISTORY: Revision 1.3 2008/11/04 15:58:57 linc * HISTORY: updated. * HISTORY: * HISTORY: Revision 1.2 2008/10/30 16:02:14 linc * HISTORY: updated. * HISTORY: * HISTORY: Revision 1.1 2008/10/27 20:06:30 linc * HISTORY: GUI first add. * HISTORY: */
software/cmts/src/java/gov/nih/nci/cbiit/cmts/ui/mapping/MappingMainPanel.java
/** * The content of this file is subject to the caAdapter Software License (the "License"). * A copy of the License is available at: * [caAdapter CVS home directory]\etc\license\caAdapter_license.txt. or at: * http://ncicb.nci.nih.gov/infrastructure/cacore_overview/caadapter/indexContent * /docs/caAdapter_License */ package gov.nih.nci.cbiit.cmts.ui.mapping; import gov.nih.nci.cbiit.cmts.common.XSDParser; import gov.nih.nci.cbiit.cmts.core.Component; import gov.nih.nci.cbiit.cmts.core.ComponentType; import gov.nih.nci.cbiit.cmts.core.Mapping; import gov.nih.nci.cbiit.cmts.mapping.MappingFactory; import gov.nih.nci.cbiit.cmts.ui.actions.SaveAsMapAction; import gov.nih.nci.cbiit.cmts.ui.actions.SaveMapAction; import gov.nih.nci.cbiit.cmts.ui.common.ActionConstants; import gov.nih.nci.cbiit.cmts.ui.common.ContextManager; import gov.nih.nci.cbiit.cmts.ui.common.ContextManagerClient; import gov.nih.nci.cbiit.cmts.ui.common.DefaultSettings; import gov.nih.nci.cbiit.cmts.ui.common.MenuConstants; import gov.nih.nci.cbiit.cmts.ui.dnd.TreeDragTransferHandler; import gov.nih.nci.cbiit.cmts.ui.dnd.TreeTransferHandler; import gov.nih.nci.cbiit.cmts.ui.function.FunctionLibraryPane; import gov.nih.nci.cbiit.cmts.ui.jgraph.MiddlePanelJGraphController; import gov.nih.nci.cbiit.cmts.ui.jgraph.MiddlePanelMarqueeHandler; import gov.nih.nci.cbiit.cmts.ui.main.MainFrame; import gov.nih.nci.cbiit.cmts.ui.main.MainFrameContainer; import gov.nih.nci.cbiit.cmts.ui.properties.DefaultPropertiesPage; import gov.nih.nci.cbiit.cmts.ui.tree.MappingSourceTree; import gov.nih.nci.cbiit.cmts.ui.tree.MappingTargetTree; import gov.nih.nci.cbiit.cmts.ui.tree.TreeMouseAdapter; import gov.nih.nci.cbiit.cmts.ui.tree.TreeSelectionHandler; import gov.nih.nci.cbiit.cmts.ui.util.GeneralUtilities; import gov.nih.nci.cbiit.cmts.web.MainApplet; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.applet.Applet; import javax.swing.*; import javax.swing.tree.TreeNode; import javax.swing.tree.TreeSelectionModel; import javax.xml.bind.JAXBException; import org.apache.xerces.xs.XSNamedMap; /** * This class * * @author Chunqing Lin * @author LAST UPDATE $Author: wangeug $ * @since CMTS v1.0 * @version $Revision: 1.16 $ * @date $Date: 2009-12-02 18:53:16 $ * */ public class MappingMainPanel extends JPanel implements ActionListener, ContextManagerClient{ private static final String Cmps_V3_MESSAGE_FILE_DEFAULT_EXTENSION = ".map"; private static final String OPEN_DIALOG_TITLE_FOR_DEFAULT_SOURCE_FILE = "Open source data schema"; private static final String OPEN_DIALOG_TITLE_FOR_DEFAULT_TARGET_FILE = "Open target data schema"; private static final String SELECT_CSV_TIP = "select CSV"; private static final String SELECT_HMD_TIP = "select HMD"; private static final String SELECT_SOURCE = "Open Source..."; private static final String SELECT_TARGET = "Open Target..."; private static final String SOURCE_TREE_FILE_DEFAULT_EXTENTION = ".xsd"; private static final String TARGET_TREE_FILE_DEFAULT_EXTENTION = ".xsd"; private Mapping mapping = null; private File mappingSourceFile = null; private File mappingTargetFile = null; private MappingMiddlePanel middlePanel = null; private File saveFile = null; private JTextField sourceLocationArea = new JTextField(); private MappingTreeScrollPane sourceScrollPane = new MappingTreeScrollPane(MappingTreeScrollPane.DRAW_NODE_TO_RIGHT); private MappingSourceTree sTree = null; private JTextField targetLocationArea = new JTextField(); private MappingTreeScrollPane targetScrollPane = new MappingTreeScrollPane(MappingTreeScrollPane.DRAW_NODE_TO_LEFT); private MappingTargetTree tTree = null; private MiddlePanelJGraphController graphController =null; private MainFrameContainer mainFrame = null; public MappingMainPanel(MainFrameContainer mainFrame) throws Exception { this.setBorder(BorderFactory.createEmptyBorder()); this.setLayout(new BorderLayout()); this.mainFrame = mainFrame; middlePanel = new MappingMiddlePanel(this); graphController = new MiddlePanelJGraphController(this); // middlePanel.setGraphController(graphController); MiddlePanelMarqueeHandler marquee=(MiddlePanelMarqueeHandler)middlePanel.getGraph().getMarqueeHandler(); marquee.setController(graphController); this.add(getCenterPanel(true), BorderLayout.CENTER); } public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); try { boolean everythingGood = true; if (SELECT_SOURCE.equals(command)) { //this.sourceButtonPanel.repaint(); File file = DefaultSettings.getUserInputOfFileFromGUI(this, //FileUtil.getUIWorkingDirectoryPath(), SOURCE_TREE_FILE_DEFAULT_EXTENTION, OPEN_DIALOG_TITLE_FOR_DEFAULT_SOURCE_FILE, false, false); if (file != null) { everythingGood = processOpenSourceTree(file, true, true); } } else if (SELECT_TARGET.equals(command)) { //this.targetButtonPanel.repaint(); File file = DefaultSettings.getUserInputOfFileFromGUI(this, // TARGET_TREE_FILE_DEFAULT_EXTENTION, OPEN_DIALOG_TITLE_FOR_DEFAULT_TARGET_FILE, false, false); //FileUtil.getUIWorkingDirectoryPath(), // TARGET_TREE_FILE_DEFAULT_EXTENTION+";"+Cmps_V3_MESSAGE_FILE_DEFAULT_EXTENSION, OPEN_DIALOG_TITLE_FOR_DEFAULT_TARGET_FILE, false, false); //last added fileExtension :.h3s will be set as default Cmps_V3_MESSAGE_FILE_DEFAULT_EXTENSION+";"+TARGET_TREE_FILE_DEFAULT_EXTENTION, OPEN_DIALOG_TITLE_FOR_DEFAULT_TARGET_FILE, false, false); if (file != null) { everythingGood = processOpenTargetTree(file, true, true); } } if (!everythingGood) { // Message msg = MessageResources.getMessage("GEN3", new Object[0]); // JOptionPane.showMessageDialog(this, msg.toString(), "Error", JOptionPane.ERROR_MESSAGE); } } catch (Exception e1) { e1.printStackTrace(); DefaultSettings.reportThrowableToLogAndUI(this, e1, "", this, false, false); } } protected void buildSourceTree(Object metaInfo, File absoluteFile, boolean isToResetGraph) throws Exception { TreeNode nodes=loadSourceTreeData(metaInfo,absoluteFile); //Build the source tree sTree = new MappingSourceTree(middlePanel, nodes); sTree.addMouseListener(new TreeMouseAdapter()); TreeSelectionHandler treeSelectionHanderl=new TreeSelectionHandler(getGraphController()); sTree.getSelectionModel().addTreeSelectionListener(treeSelectionHanderl); sTree.setTransferHandler(new TreeDragTransferHandler()); sTree.setDragEnabled(true); // sTree.setDropMode(DropMode.ON); sTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); sourceScrollPane.setViewportView(sTree); sTree.expandAll(); //register collapse all and expand all actions. // sourceTreeCollapseAllAction.setTree(sTree); // sourceTreeExpandAllAction.setTree(sTree); // sTree.getInputMap().put(sourceTreeCollapseAllAction.getAcceleratorKey(), sourceTreeCollapseAllAction.getName()); // sTree.getActionMap().put(sourceTreeCollapseAllAction.getName(), sourceTreeCollapseAllAction); // sTree.getInputMap().put(sourceTreeExpandAllAction.getAcceleratorKey(), sourceTreeExpandAllAction.getName()); // sTree.getActionMap().put(sourceTreeExpandAllAction.getName(), sourceTreeExpandAllAction); if (tTree != null && isToResetGraph) { resetMiddlePanel(); } if (absoluteFile != null) { String absoluteFilePath = absoluteFile.getAbsolutePath(); sourceLocationArea.setText(absoluteFilePath); sourceLocationArea.setToolTipText(absoluteFilePath); mappingSourceFile = absoluteFile; } else { mappingSourceFile = null; } if (this.getRootPane() != null) { this.getRootPane().repaint(); } // getMappingFileSynchronizer().registerFile(MappingFileSynchronizer.FILE_TYPE.Source_File, absoluteFile); } protected void buildTargetTree(Object metaInfo, File absoluteFile, boolean isToResetGraph) throws Exception { TreeNode nodes=loadTargetTreeData(metaInfo,absoluteFile); //Build the target tree tTree = new MappingTargetTree(this.getMiddlePanel(), nodes); tTree.addMouseListener(new TreeMouseAdapter()); TreeSelectionHandler treeSelectionHanderl=new TreeSelectionHandler(getGraphController()); tTree.getSelectionModel().addTreeSelectionListener(treeSelectionHanderl); TreeTransferHandler targetTreeTransferHandler= new TreeTransferHandler(this); tTree.setTransferHandler(targetTreeTransferHandler); tTree.setDropMode(DropMode.ON); tTree.setDragEnabled(true); targetScrollPane.setViewportView(tTree); tTree.expandAll(); // //register collapse all and expand all actions. // targetTreeCollapseAllAction.setTree(tTree); // targetTreeExpandAllAction.setTree(tTree); // tTree.getInputMap().put(targetTreeCollapseAllAction.getAcceleratorKey(), targetTreeCollapseAllAction.getName()); // tTree.getActionMap().put(targetTreeCollapseAllAction.getName(), targetTreeCollapseAllAction); // tTree.getInputMap().put(targetTreeExpandAllAction.getAcceleratorKey(), targetTreeExpandAllAction.getName()); // tTree.getActionMap().put(targetTreeExpandAllAction.getName(), targetTreeExpandAllAction); if (sTree != null && isToResetGraph) { resetMiddlePanel(); } if (absoluteFile != null) { String absoluteFilePath = absoluteFile.getAbsolutePath(); targetLocationArea.setText(absoluteFilePath); targetLocationArea.setToolTipText(absoluteFilePath); mappingTargetFile = absoluteFile;//new File(absoluteFilePath); } else { mappingTargetFile = null; } if (this.getRootPane() != null) { this.getRootPane().repaint(); } // getMappingFileSynchronizer().registerFile(MappingFileSynchronizer.FILE_TYPE.Target_File, absoluteFile); //// drop target for DnD from source tree. // targetTreeDropTransferHandler = new TargetTreeDropTransferHandler(tTree, getMappingDataManager(), DnDConstants.ACTION_LINK); } /** * Provide the extended implementation of this method by adding additional files of source and target; * * @return a list of file objects that this context is associated with. */ public java.util.List<File> getAssociatedFileList() { List<File> resultList = new ArrayList<java.io.File>(); if(saveFile!=null) { resultList.add(saveFile); } if (mappingSourceFile != null) { resultList.add(mappingSourceFile); } if (mappingTargetFile != null) { resultList.add(mappingTargetFile); } return resultList; } /** * @return the graphController */ public MiddlePanelJGraphController getGraphController() { return graphController; } protected JComponent getCenterPanel(boolean functionPaneRequired) {//construct the top level layout of mapping panel /** * GUI Layout: * JSplitPane - Horizontal: --> leftRightSplitPane * left: JSplitPane - Horizontal: --> topCenterPanel, centerSplitPane * left: source panel; --> sourceButtonPanel * right: JSplitPane - Horizontal: --> rightSplitPane * left: middle panel for graph; -->middleContainerPanel * right: target panel; -->targetButtonPanel * right: JSplitPane - Vertical: -->topBottomSplitPane * top: functional pane; -->functionPane * bottom: properties panel; -->propertiesPane */ JSplitPane leftRightSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); DefaultSettings.setDefaultFeatureForJSplitPane(leftRightSplitPane); int locDiv = (int) (mainFrame.getAssociatedUIContainer().getWidth() * 0.85); leftRightSplitPane.setDividerLocation(locDiv); //.setDividerLocation(0.85); //System.out.println("First locDiv : " + locDiv); leftRightSplitPane.setLeftComponent(getTopLevelLeftPanel()); leftRightSplitPane.setRightComponent(getTopLevelRightPanel(functionPaneRequired)); return leftRightSplitPane; } /** * return the close action inherited with this client. * @return the close action inherited with this client. */ public Action getDefaultCloseAction() {//by doing this way, the menu and the panel will use the same close action. Map actionMap = getMenuItems(MenuConstants.FILE_MENU_NAME); Action closeAction = (Action) actionMap.get(ActionConstants.CLOSE); return closeAction; } /** * return the open action inherited with this client. */ public Action getDefaultOpenAction() { ContextManager contextManager = ContextManager.getContextManager(); Action openAction=contextManager.getDefinedAction(ActionConstants.OPEN_MAP_FILE); return openAction; } /** * return the save action inherited with this client. * @return the save action inherited with this client. */ public Action getDefaultSaveAction() { Map actionMap = getMenuItems(MenuConstants.FILE_MENU_NAME); Action saveAction = (Action) actionMap.get(ActionConstants.SAVE); return saveAction; } /** * @return the mapping */ public Mapping getMapping() { if(this.mapping == null){ this.mapping = new Mapping(); getGraphController().setMappingData(mapping); } return mapping; } public Map getMenuItems(String menu_name) { Action action = null; Map <String, Action>actionMap = null; ContextManager contextManager = ContextManager.getContextManager(); actionMap = contextManager.getClientMenuActions("CMTS", menu_name); if (MenuConstants.FILE_MENU_NAME.equals(menu_name)) { JRootPane rootPane = this.getRootPane(); if (rootPane == null){ //rootpane is not null implies this panel is fully displayed; //on the flip side, if it is null, it implies it is under certain construction. contextManager.enableAction(ActionConstants.NEW_MAP_FILE, true); contextManager.enableAction(ActionConstants.OPEN_MAP_FILE, true); contextManager.enableAction(ActionConstants.CLOSE, false); contextManager.enableAction(ActionConstants.SAVE, false); contextManager.enableAction(ActionConstants.SAVE_AS, false); }else{ contextManager.enableAction(ActionConstants.CLOSE, true); contextManager.enableAction(ActionConstants.SAVE, true); contextManager.enableAction(ActionConstants.SAVE_AS, true); } } //since the action depends on the panel instance, //the old action instance should be removed if (actionMap!=null) contextManager.removeClientMenuAction("CMTS", menu_name, ""); action = new SaveMapAction(this); contextManager.addClientMenuAction("CMTS", MenuConstants.FILE_MENU_NAME,ActionConstants.SAVE, action); action.setEnabled(true); action = new SaveAsMapAction(this); contextManager.addClientMenuAction("CMTS", MenuConstants.FILE_MENU_NAME,ActionConstants.SAVE_AS, action); action.setEnabled(true); actionMap = contextManager.getClientMenuActions("CMTS", menu_name); return actionMap; } public MappingMiddlePanel getMiddlePanel() { return middlePanel; } /** * Return the top root container (frame or dialog or window) this panel is associated with. * @return the top root container (frame or dialog or window) this panel is associated with. */ public Container getRootContainer() { return DefaultSettings.findRootContainer(this); } /** * Return the save file. * @return the save file. */ public File getSaveFile() { return saveFile; } public JScrollPane getSourceScrollPane() { return sourceScrollPane; } public JTree getSourceTree() { return sTree; } public JScrollPane getTargetScrollPane() { return targetScrollPane; } public JTree getTargetTree() { return tTree; } /** * Return a list of Action objects that is included in this Context manager. * @return a list of Action objects that is included in this Context manager. */ public java.util.List<Action> getToolbarActionList() { java.util.List<Action> actions = new ArrayList<Action>(); actions.add(getDefaultOpenAction()); //the menu bar display its buttons inorder Map <String, Action>actionMap = getMenuItems(MenuConstants.TOOLBAR_MENU_NAME); actions.add(actionMap.get(ActionConstants.SAVE)); actions.add(actionMap.get(ActionConstants.VALIDATE)); //add the "Refresh" menu if exist actions.add(actionMap.get(ActionConstants.REFRESH)); return actions; } protected JPanel getTopLevelLeftPanel() { JPanel topCenterPanel = new JPanel(new BorderLayout()); topCenterPanel.setBorder(BorderFactory.createEtchedBorder()); JSplitPane centerSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); DefaultSettings.setDefaultFeatureForJSplitPane(centerSplitPane); int frameWidth = mainFrame.getAssociatedUIContainer().getWidth(); //construct source panel JPanel sourceButtonPanel = new JPanel(new BorderLayout()); sourceButtonPanel.setBorder(BorderFactory.createEmptyBorder()); JPanel sourceLocationPanel = new JPanel(new BorderLayout(2, 0)); sourceLocationPanel.setBorder(BorderFactory.createEmptyBorder()); // sourceTreeCollapseAllAction = new TreeCollapseAllAction(sTree); // sourceTreeExpandAllAction = new TreeExpandAllAction(sTree); JToolBar sourceTreeToolBar = new JToolBar("Source Tree Tool Bar"); sourceTreeToolBar.setFloatable(false); // sourceTreeToolBar.add(sourceTreeExpandAllAction); // sourceTreeToolBar.add(sourceTreeCollapseAllAction); sourceLocationPanel.add(sourceTreeToolBar, BorderLayout.WEST); sourceLocationArea.setEditable(false); //sourceLocationArea.setPreferredSize(new Dimension((DefaultSettings.FRAME_DEFAULT_WIDTH / 10), 24)); sourceLocationArea.setPreferredSize(new Dimension((frameWidth / 10), 24)); sourceLocationPanel.add(sourceLocationArea, BorderLayout.CENTER); JButton openSourceButton = new JButton(SELECT_SOURCE); sourceLocationPanel.add(openSourceButton, BorderLayout.EAST); openSourceButton.setMnemonic('S'); openSourceButton.setToolTipText(SELECT_CSV_TIP); openSourceButton.addActionListener(this); sourceButtonPanel.add(sourceLocationPanel, BorderLayout.NORTH); //sourceScrollPane.setSize(new Dimension((DefaultSettings.FRAME_DEFAULT_WIDTH / 4), (int) (DefaultSettings.FRAME_DEFAULT_HEIGHT / 1.5))); sourceScrollPane.setSize(new Dimension((int)((frameWidth*0.85) / 4), (int) (DefaultSettings.FRAME_DEFAULT_HEIGHT / 1.5))); sourceButtonPanel.add(sourceScrollPane, BorderLayout.CENTER); //construct target panel JPanel targetButtonPanel = new JPanel(new BorderLayout()); targetButtonPanel.setBorder(BorderFactory.createEmptyBorder()); JPanel targetLocationPanel = new JPanel(new BorderLayout(2, 0)); targetLocationPanel.setBorder(BorderFactory.createEmptyBorder()); // targetTreeCollapseAllAction = new TreeCollapseAllAction(tTree); // targetTreeExpandAllAction = new TreeExpandAllAction(tTree); JToolBar targetTreeToolBar = new JToolBar("Target Tree Tool Bar"); targetTreeToolBar.setFloatable(false); // targetTreeToolBar.add(targetTreeExpandAllAction); // targetTreeToolBar.add(targetTreeCollapseAllAction); targetLocationPanel.add(targetTreeToolBar, BorderLayout.WEST); targetLocationArea.setEditable(false); //targetLocationArea.setPreferredSize(new Dimension((DefaultSettings.FRAME_DEFAULT_WIDTH / 10), 24)); targetLocationArea.setPreferredSize(new Dimension((frameWidth / 10), 24)); targetLocationPanel.add(targetLocationArea, BorderLayout.CENTER); JButton openTargetButton = new JButton(SELECT_TARGET); targetLocationPanel.add(openTargetButton, BorderLayout.EAST); openTargetButton.setMnemonic('T'); openTargetButton.setToolTipText(SELECT_HMD_TIP); openTargetButton.addActionListener(this); targetButtonPanel.add(targetLocationPanel, BorderLayout.NORTH); targetButtonPanel.add(targetScrollPane, BorderLayout.CENTER); //targetButtonPanel.setPreferredSize(new Dimension((DefaultSettings.FRAME_DEFAULT_WIDTH / 5), (int) (DefaultSettings.FRAME_DEFAULT_HEIGHT / 1.5))); targetButtonPanel.setPreferredSize(new Dimension((int)((frameWidth*0.85) / 5), (int) (DefaultSettings.FRAME_DEFAULT_HEIGHT / 1.5))); //construct middle panel JPanel middleContainerPanel = new JPanel(new BorderLayout()); JLabel placeHolderLabel = new JLabel(); //placeHolderLabel.setPreferredSize(new Dimension((int) (DefaultSettings.FRAME_DEFAULT_WIDTH / 3.5), 24)); placeHolderLabel.setPreferredSize(new Dimension((int)((frameWidth*0.85) / 3.5), 24)); middleContainerPanel.add(placeHolderLabel, BorderLayout.NORTH); middleContainerPanel.add(middlePanel, BorderLayout.CENTER); JSplitPane rightSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); DefaultSettings.setDefaultFeatureForJSplitPane(rightSplitPane); //rightSplitPane.setDividerLocation(0.5); rightSplitPane.setDividerLocation(50); rightSplitPane.setLeftComponent(middleContainerPanel); rightSplitPane.setRightComponent(targetButtonPanel); rightSplitPane.setDividerLocation((int)((frameWidth*0.85)/3)); centerSplitPane.setLeftComponent(sourceButtonPanel); centerSplitPane.setRightComponent(rightSplitPane); centerSplitPane.setDividerLocation(((int)((frameWidth*0.85)/3)) - (centerSplitPane.getDividerSize()*2)); topCenterPanel.add(centerSplitPane, BorderLayout.CENTER); //topCenterPanel.setPreferredSize(new Dimension((int) (DefaultSettings.FRAME_DEFAULT_WIDTH * 0.8), (int) (DefaultSettings.FRAME_DEFAULT_HEIGHT / 1.5))); topCenterPanel.setPreferredSize(new Dimension((int) (frameWidth * 0.85), (int) (DefaultSettings.FRAME_DEFAULT_HEIGHT / 1.5))); return topCenterPanel; } /** * This constructs function and properties panels. * * @return the top level right pane. */ private JComponent getTopLevelRightPanel(boolean functionPaneRequired) { FunctionLibraryPane functionPane = new FunctionLibraryPane(this); functionPane.setBorder(BorderFactory.createTitledBorder("Functions")); DefaultPropertiesPage propertiesPane = new DefaultPropertiesPage(getGraphController().getPropertiesSwitchController()); Dimension rightMostDim = new Dimension((DefaultSettings.FRAME_DEFAULT_WIDTH / 11), 50); propertiesPane.setPreferredSize(rightMostDim); functionPane.setPreferredSize(rightMostDim); JSplitPane topBottomSplitPane = null; if(functionPaneRequired) { topBottomSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, functionPane, propertiesPane); DefaultSettings.setDefaultFeatureForJSplitPane(topBottomSplitPane); int locDiv = (int) (mainFrame.getAssociatedUIContainer().getHeight() * 0.2); if (locDiv < 130) locDiv = 130; topBottomSplitPane.setDividerLocation(locDiv); //System.out.println("VVVV topBottomSplitPane.getDividerLocation():" + topBottomSplitPane.getDividerLocation()); } else { topBottomSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, new JPanel(), propertiesPane); DefaultSettings.setDefaultFeatureForJSplitPane(topBottomSplitPane); topBottomSplitPane.setDividerLocation(10); } return topBottomSplitPane; } public boolean isChanged() { // TODO Auto-generated method stub return false; } protected TreeNode loadSourceTreeData(Object metaInfo, File absoluteFile)throws Exception { TreeNode node = null; if(metaInfo instanceof Mapping){ Mapping.Components components = ((Mapping)metaInfo).getComponents(); List<Component> l = components.getComponent(); for(Component c:l){ if(c.getType().equals(ComponentType.SOURCE)) node = new ElementMetaLoader(ElementMetaLoader.SOURCE_MODE).loadData(c); } }else{ throw new RuntimeException("ElementMetaNodeLoader.loadData() input " + "not recognized. " + metaInfo); } return node; } protected TreeNode loadTargetTreeData( Object metaInfo, File absoluteFile)throws Exception { TreeNode node = null; if(metaInfo instanceof Mapping){ Mapping.Components components = ((Mapping)metaInfo).getComponents(); List<Component> l = components.getComponent(); for(Component c:l){ if(c.getType().equals(ComponentType.TARGET)) node = new ElementMetaLoader(ElementMetaLoader.TARGET_MODE).loadData(c); } }else{ throw new RuntimeException("ElementMetaNodeLoader.loadData() input " + "not recognized. " + metaInfo); } return node; } /** * Called by actionPerformed() and overridable by descendant classes. * * @param file * @throws Exception changed from protected to pulic by sean */ public void processOpenMapFile(File file) throws Exception { long stTime=System.currentTimeMillis(); // parse the file. Mapping mapping = MappingFactory.loadMapping(file); //build source tree buildSourceTree(mapping, null, false); //build target tree buildTargetTree(mapping, null, false); for (Component mapComp:mapping.getComponents().getComponent()) { if (mapComp.getRootElement()==null) continue; JTextField tField = null; if (mapComp.getType().value().equals(ComponentType.SOURCE.value())) tField = sourceLocationArea; if (mapComp.getType().value().equals(ComponentType.TARGET.value())) tField = targetLocationArea; if (tField != null) { String c = mapComp.getLocation(); if (c == null) c = ""; else c = c.trim(); if (!c.equals("")) { tField.setText(mapComp.getLocation()); //tField.setEditable(true); //tField.setFocusable(false); } } if (mapComp.getType().value().equals(ComponentType.TARGET.value())) targetLocationArea.setText(mapComp.getLocation()); } getGraphController().setMappingData(mapping); setSaveFile(file); getMiddlePanel().renderInJGraph(); System.out.println("CmtsMappingPanel.processOpenMapFile()..timespending:"+(System.currentTimeMillis()-stTime)); } /** * Called by actionPerformed() and overridable by descendant classes. * * @param file * @throws Exception */ protected boolean processOpenSourceTree(File file, boolean isToResetGraph, boolean supressReportIssuesToUI) throws Exception { // String fileExtension = FileUtil.getFileExtension(file, true); XSDParser p = new XSDParser(); p.loadSchema(file); CellRenderXSObject srcRoot = userSelectRoot(p); if(srcRoot == null || srcRoot.getCoreObject().getName().trim().length() == 0) return false; MappingFactory.loadMetaXSD(getMapping(), p,srcRoot.getCoreObject().getNamespace(), srcRoot.getCoreObject().getName(), ComponentType.SOURCE); buildSourceTree(getMapping(), file, isToResetGraph); return true; } /** * Called by actionPerformed() and overridable by descendant classes. * * @param file * @throws Exception */ protected boolean processOpenTargetTree(File file, boolean isToResetGraph, boolean supressReportIssuesToUI) throws Exception { // String fileExtension = FileUtil.getFileExtension(file, true); XSDParser p = new XSDParser(); p.loadSchema(file); CellRenderXSObject trgtRoot = userSelectRoot(p); if(trgtRoot == null || trgtRoot.getCoreObject().getName().trim().length() == 0) return false; MappingFactory.loadMetaXSD(getMapping(), p, trgtRoot.getCoreObject().getNamespace(), trgtRoot.getCoreObject().getName(), ComponentType.TARGET); buildTargetTree(getMapping(), file, isToResetGraph); // middlePanel.getMappingDataManager().registerTargetComponent(metaInfo, file); return true; } private void resetMiddlePanel() { if (middlePanel != null) { // middlePanel.resetGraph(); middlePanel.repaint(); } } /** * Explicitly set the value. * * @param newValue */ public void setChanged(boolean newValue) { getGraphController().setGraphChanged(newValue); } /** * @param mapping the mapping to set */ public void setMapping(Mapping mapping) { this.mapping = mapping; } /** * Set a new save file. * * @param saveFile * @return true if the value is changed, false otherwise. */ public boolean setSaveFile(File saveFile) { //removed the equal check so as to support explicit refresh or reload call. // ContextManager contextManager = ContextManager.getContextManager(); boolean sameFile = GeneralUtilities.areEqual(this.saveFile, saveFile); if(!sameFile) {//remove interest in the context file manager, first for old file // contextManager.getContextFileManager().removeFileUsageListener(this); } this.saveFile = saveFile; // if(!sameFile) // {//register interest in the context file manager for new file // contextManager.getContextFileManager().registerFileUsageListener(this); // } updateTitle(this.saveFile.getName()); // getMappingFileSynchronizer().registerFile(MappingFileSynchronizer.FILE_TYPE.Mapping_File, saveFile); return true; } @Override public void setSize(int width, int height) { double topCenterFactor = 1; sourceLocationArea.setSize(new Dimension((width / 6), 25)); sourceScrollPane.setSize(new Dimension((int) (width / 4.5), (int) (height * topCenterFactor))); targetLocationArea.setSize(new Dimension(width / 6, 25)); targetScrollPane.setSize(new Dimension((int) (width / 4.5), (int) (height * topCenterFactor))); middlePanel.setSize(new Dimension((width / 4), (int) (height * topCenterFactor))); topCenterFactor = 0.5; Dimension rightMostDim = new Dimension((width / 5), (int) (height * topCenterFactor)); // propertiesPane.setSize(rightMostDim); // functionPane.setSize(rightMostDim); } public void synchronizeRegisteredFile(boolean notigyOberver) { //do nothing, only the "MappingFilePanel" will implement it } /** * Overridable function to update Title in the tabbed pane. * @param newTitle */ private void updateTitle(String newTitle) { JRootPane rootPane = getRootPane(); if (rootPane != null) { Container container = rootPane.getParent(); if (container instanceof MainFrame) { ((MainFrame)container).setCurrentPanelTitle(newTitle); } if (container instanceof MainApplet) { ((MainApplet)container).setCurrentPanelTitle(newTitle); } } } /** * Promote user to select a root node:Element or Complex type * @param xsdParser * @return */ private CellRenderXSObject userSelectRoot(XSDParser xsdParser) { XSNamedMap[] map = xsdParser.getMappableNames(); CellRenderXSObject[] choices = new CellRenderXSObject[map[0].getLength()+map[1].getLength()]; int pos = 0; for(int i=0; i<map[0].getLength(); i++) choices[pos++] =new CellRenderXSObject(map[0].item(i));//.getName(); for(int i=0; i<map[1].getLength(); i++) choices[pos++] = new CellRenderXSObject(map[1].item(i));//.getNamespace() +":" +map[1].item(i).getName(); CellRenderXSObject chosenRoot = null; Container con = this; while(con != null) { if ((con instanceof Frame)||(con instanceof Applet)) { chosenRoot = (CellRenderXSObject)DefaultSettings.showListChoiceDialog(con, "choose root element", "Please choose root element", choices); break; } con = con.getParent(); } //CellRenderXSObject chosenRoot = (CellRenderXSObject)DefaultSettings.showListChoiceDialog(MainFrame.getInstance(), "choose root element", "Please choose root element", choices); return chosenRoot; } } /** * HISTORY: $Log: not supported by cvs2svn $ * HISTORY: Revision 1.15 2009/11/23 18:31:44 wangeug * HISTORY: create new package: ui.main * HISTORY: * HISTORY: Revision 1.14 2009/11/03 18:32:54 wangeug * HISTORY: clean codes: keep MiddlePanelJGraphController only with MiddleMappingPanel * HISTORY: * HISTORY: Revision 1.13 2009/10/30 14:45:30 wangeug * HISTORY: simplify code: only respond to link highter * HISTORY: * HISTORY: Revision 1.12 2009/10/28 16:47:06 wangeug * HISTORY: clean codes * HISTORY: * HISTORY: Revision 1.11 2009/10/27 19:26:16 wangeug * HISTORY: clean codes * HISTORY: * HISTORY: Revision 1.10 2009/10/27 18:25:08 wangeug * HISTORY: hook property panel with tree nodes * HISTORY: * HISTORY: Revision 1.9 2009/10/16 17:36:34 wangeug * HISTORY: use cell renderer * HISTORY: * HISTORY: Revision 1.8 2009/10/15 18:35:33 wangeug * HISTORY: clean codes * HISTORY: * HISTORY: Revision 1.7 2008/12/29 22:18:18 linc * HISTORY: function UI added. * HISTORY: * HISTORY: Revision 1.6 2008/12/09 19:04:17 linc * HISTORY: First GUI release * HISTORY: * HISTORY: Revision 1.5 2008/12/04 21:34:20 linc * HISTORY: Drap and Drop support with new Swing. * HISTORY: * HISTORY: Revision 1.4 2008/12/03 20:46:14 linc * HISTORY: UI update. * HISTORY: * HISTORY: Revision 1.3 2008/11/04 15:58:57 linc * HISTORY: updated. * HISTORY: * HISTORY: Revision 1.2 2008/10/30 16:02:14 linc * HISTORY: updated. * HISTORY: * HISTORY: Revision 1.1 2008/10/27 20:06:30 linc * HISTORY: GUI first add. * HISTORY: */
clean codes SVN-Revision: 3200
software/cmts/src/java/gov/nih/nci/cbiit/cmts/ui/mapping/MappingMainPanel.java
clean codes
<ide><path>oftware/cmts/src/java/gov/nih/nci/cbiit/cmts/ui/mapping/MappingMainPanel.java <ide> { <ide> // String fileExtension = FileUtil.getFileExtension(file, true); <ide> XSDParser p = new XSDParser(); <del> p.loadSchema(file); <add> p.loadSchema(file.getPath(), null);//(file); <ide> CellRenderXSObject srcRoot = userSelectRoot(p); <ide> if(srcRoot == null || srcRoot.getCoreObject().getName().trim().length() == 0) <ide> return false; <ide> { <ide> // String fileExtension = FileUtil.getFileExtension(file, true); <ide> XSDParser p = new XSDParser(); <del> p.loadSchema(file); <add> p.loadSchema(file.getPath(), null); <ide> CellRenderXSObject trgtRoot = userSelectRoot(p); <ide> if(trgtRoot == null || trgtRoot.getCoreObject().getName().trim().length() == 0) <ide> return false;
JavaScript
mit
d5d4a9fc476a0abc7b3e3e1aa041be1d7699326b
0
sensebox/OpenSenseMap-API,mpfeil/OpenSenseMap-API,mpfeil/OpenSenseMap-API,sensebox/OpenSenseMap-API
var restify = require('restify'), mongoose = require('mongoose'), fs = require('fs'), GeoJSON = require('geojson'), _ = require('lodash'), products = require('./products'), cfg = require('./config'), schemas = require('./schemas'), csvstringify = require('csv-stringify'), csvtransform = require('stream-transform'), Stream = require('stream'), nodemailer = require('nodemailer'), smtpTransport = require('nodemailer-smtp-transport'), htmlToText = require('nodemailer-html-to-text').htmlToText, moment = require('moment'), request = require('request'); mongoose.Promise = require('bluebird'); var dbHost = process.env.DB_HOST || cfg.dbhost; var TIME_AGO_MAX = 1000*60*60*24*32; var TIME_AGO_48_H = 1000*60*60*48; // 48 hours var TIME_AGO_15_D = 1000*60*60*24*15 // 15 days /* Logging */ var consoleStream = new Stream(); consoleStream.writable = true; consoleStream.write = function(obj) { if(obj.req){ console.log(obj.time, obj.req.remoteAddress, obj.req.method, obj.req.url); } else if(obj.msg) { console.log(obj.time, obj.msg); } else { //console.log(obj.time, obj); } }; var Logger = require('bunyan'), reqlog = new Logger.createLogger({ name: 'OSeM-API', streams: [ { level: 'debug', type: 'raw', stream: consoleStream } ], serializers: { err: Logger.stdSerializers.err, req: Logger.stdSerializers.req, res: Logger.stdSerializers.res } }), log = new Logger.createLogger({ name: 'OSeM-API', streams: [ { level: 'debug', type: 'raw', stream: consoleStream } ], serializers: { err: Logger.stdSerializers.err, req: Logger.stdSerializers.req, res: Logger.stdSerializers.res } }); var server = restify.createServer({ name: 'opensensemap-api', version: '0.0.1', log: reqlog }); server.use(restify.CORS({'origins': ['*'] })); //['http://localhost', 'https://opensensemap.org']})); server.use(restify.fullResponse()); server.use(restify.queryParser()); server.use(restify.bodyParser()); server.pre(function(request, response, next) { response.charSet('utf-8'); request.log.info({req: request}, 'REQUEST'); return next(); }); // use this function to retry if a connection cannot be established immediately var connectWithRetry = function () { return mongoose.connect(cfg.dbconnectionstring, { keepAlive: 1 }, function (err) { if (err) { console.error('Failed to connect to mongo on startup - retrying in 5 sec', err); setTimeout(connectWithRetry, 5000); } }); }; conn = connectWithRetry(); var LocationSchema = schemas.LocationSchema; var measurementSchema = schemas.measurementSchema; var sensorSchema = schemas.sensorSchema; var boxSchema = schemas.boxSchema; var userSchema = schemas.userSchema; var Measurement = mongoose.model('Measurement', measurementSchema); var Box = mongoose.model('Box', boxSchema); var Sensor = mongoose.model('Sensor', sensorSchema); var User = mongoose.model('User', userSchema); var Location = mongoose.model('Location', LocationSchema); var PATH = '/boxes'; var userPATH = 'users'; // GET server.get({path : PATH , version : '0.0.1'} , findAllBoxes); server.get({path : /(boxes)\.([a-z]+)/, version : '0.1.0'} , findAllBoxes); server.get({path : PATH +'/:boxId' , version : '0.0.1'} , findBox); server.get({path : PATH +'/:boxId/sensors', version : '0.0.1'}, getMeasurements); server.get({path : PATH +'/:boxId/data/:sensorId', version : '0.0.1'}, getData); server.get({path : PATH +'/data', version : '0.1.0'}, getDataMulti); server.get({path : userPATH +'/:boxId', version : '0.0.1'}, validApiKey); server.get({path : PATH +'/:boxId/script', version : '0.1.0'}, getScript); server.get({path : '/stats', version : '0.1.0'}, getStatistics); // POST server.post({path : PATH , version: '0.0.1'}, postNewBox); server.post({path : PATH +'/:boxId/:sensorId' , version : '0.0.1'}, postNewMeasurement); server.post({path : PATH +'/:boxId/data' , version : '0.1.0'}, postNewMeasurements); server.post({path : PATH +'/data', version : '0.1.0'}, getDataMulti); // PUT server.put({path: PATH + '/:boxId' , version: '0.1.0'} , updateBox); // DELETE server.del({path: PATH + '/:boxId' , version: '0.1.0'} , deleteBox); // helper function to determine the requested format function getFormat (req, allowed_formats, default_format) { if (typeof req.params["format"] === "undefined") { return default_format; } else if (allowed_formats.indexOf(req.params["format"].toLowerCase()) !== -1) { return req.params["format"]; } } function unknownMethodHandler(req, res) { if (req.method.toLowerCase() === 'options') { var allowHeaders = ['Accept', 'X-ApiKey', 'Accept-Version', 'Content-Type', 'Api-Version', 'Origin', 'X-Requested-With']; // added Origin & X-Requested-With if (res.methods.indexOf('OPTIONS') === -1) res.methods.push('OPTIONS'); res.header('Access-Control-Allow-Credentials', true); res.header('Access-Control-Allow-Headers', allowHeaders.join(', ')); res.header('Access-Control-Allow-Methods', res.methods.join(', ')); res.header('Access-Control-Allow-Origin', req.headers.origin); return res.send(204); } else { return res.send(new restify.MethodNotAllowedError()); } } server.on('MethodNotAllowed', unknownMethodHandler); /** * @api {get} /boxes/users/:boxId Check for valid API key * @apiDescription Check for valid API key. Will return status code 400 if invalid, 200 if valid. * @apiParam {ID} boxId senseBox unique ID. * @apiHeader {ObjectId} x-apikey senseBox specific apikey * @apiHeaderExample {json} Request-Example: * { * 'X-ApiKey':54d3a96d5438b4440913434b * } * @apiError {String} ApiKey is invalid! * @apiError {String} ApiKey not existing! * @apiSuccess {String} ApiKey is valid! * @apiVersion 0.0.1 * @apiGroup Boxes * @apiName validApiKey */ function validApiKey (req,res,next) { User.findOne({apikey:req.headers['x-apikey']}, function (error, user) { if (error) { res.send(400, "ApiKey does not exist"); } if (user && user.boxes.length > 0 && user.boxes.indexOf(req.params.boxId) != -1) { res.send(200, "ApiKey is valid"); } else { res.send(400, "ApiKey is invalid"); } }); } function decodeBase64Image(dataString) { var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/), response = {}; if (matches.length !== 3) { return new Error('Invalid input string'); } response.type = matches[1]; response.data = new Buffer(matches[2], 'base64'); return response; } /** * @api {put} /boxes/:boxId Update a senseBox: Image and sensor names * @apiDescription Modify the specified senseBox. * @apiParam {ID} boxId senseBox unique ID. * @apiHeader {ObjectId} x-apikey senseBox specific apikey * @apiHeaderExample {json} Request-Example: * { * 'X-ApiKey':54d3a96d5438b4440913434b * } * @apiSampleRequest * { * "_id": "56e741ff933e450c0fe2f705", * "name": "MeineBox", * "sensors": [ * { * "_id": "56e741ff933e450c0fe2f707", * "title": "UV-Intensität", * "unit": "μW/cm²", * "sensorType": "VEML6070", * } * ], * "grouptag": "vcxyxsdf", * "exposure": "outdoor", * "loc": { * "lng": 8.6956, * "lat": 50.0430 * } * } * @apiVersion 0.0.1 * @apiGroup Boxes * @apiName updateBox */ function updateBox(req, res, next) { /* var newBoxData = { _id name sensors description weblink grouptag exposure loc image }; */ User.findOne({apikey:req.headers["x-apikey"]}, function (error, user) { if (error) { res.send(400, "ApiKey does not exist"); } var qrys = []; if (user.boxes.indexOf(req.params.boxId) !== -1) { Box.findById(req.params.boxId, function (err, box) { if (err) return handleError(err); if (typeof req.params.name !== 'undefined' && req.params.name !== "") { if(box.name !== req.params.name) qrys.push(box.set({name: req.params.name})); } if (typeof req.params.exposure !== 'undefined' && req.params.exposure !== "") { if(box.exposure !== req.params.exposure) qrys.push(box.set({exposure: req.params.exposure})); } if (typeof req.params.grouptag !== 'undefined' && req.params.grouptag !== "") { if(box.grouptag !== req.params.grouptag) qrys.push(box.set({grouptag: req.params.grouptag})); } if (typeof req.params.weblink !== 'undefined' && req.params.weblink !== "") { if(box.weblink !== req.params.weblink) qrys.push(box.set({weblink: req.params.weblink})); } if (typeof req.params.description !== 'undefined' && req.params.description !== "") { if(box.description !== req.params.description) qrys.push(box.set({description: req.params.description})); } if (typeof req.params.loc !== 'undefined' && req.params.loc !== "") { if(String(box.loc[0].geometry.coordinates[0]) !== req.params.loc.lng || String(box.loc[0].geometry.coordinates[1]) !== req.params.loc.lat){ box.loc[0].geometry.coordinates = [req.params.loc.lng, req.params.loc.lat]; } } if (typeof req.params.image !== 'undefined' && req.params.image !== "") { var data = req.params.image.toString(); var imageBuffer = decodeBase64Image(data); var extension = (imageBuffer.type === 'image/jpeg') ? '.jpg' : '.png'; try { fs.writeFileSync(cfg.imageFolder+""+req.params.boxId+extension, imageBuffer.data); qrys.push(box.set({image: req.params.boxId+extension+'?'+(new Date().getTime())})); } catch(e) { if (err) return handleError(e); } } if (typeof req.params.sensors !== 'undefined' && req.params.sensors.length>0) { req.params.sensors.forEach(function(updatedsensor){ if(updatedsensor.deleted){ qrys.push(Measurement.find({ sensor_id: updatedsensor._id }).remove()); qrys.push(Box.update({'sensors._id': mongoose.Types.ObjectId(updatedsensor._id)}, { $pull: { 'sensors': { _id: mongoose.Types.ObjectId(updatedsensor._id) } } })); } else if(updatedsensor.edited && updatedsensor.new) { var newsensor = new Sensor({ 'title': updatedsensor.title, 'unit': updatedsensor.unit, 'sensorType': updatedsensor.sensorType, 'icon' : updatedsensor.icon }); box.sensors.push(newsensor); }else if(updatedsensor.edited && !updatedsensor.deleted){ qrys.push(Box.update({'sensors._id': mongoose.Types.ObjectId(updatedsensor._id)}, {'$set': { 'sensors.$.title': updatedsensor.title, 'sensors.$.unit': updatedsensor.unit, 'sensors.$.sensorType': updatedsensor.sensorType, 'sensors.$.icon': updatedsensor.icon }})); } }); } qrys.push(box.save()); Promise.all(qrys).then(function(){ genScript(box, box.model); res.send(200, box); }); }); } else { res.send(400, "ApiKey does not match senseBoxID"); } }); } /** * @api {get} /boxes/:boxId/sensors Get all last measurements * @apiDescription Get last measurements of all sensors of the secified senseBox. * @apiVersion 0.0.1 * @apiGroup Measurements * @apiName getMeasurements * @apiParam {ID} boxId senseBox unique ID. */ function getMeasurements(req, res, next) { Box.findOne({_id: req.params.boxId},{sensors:1}).populate('sensors.lastMeasurement').lean().exec(function(error,sensors){ if (error) { return next(new restify.InvalidArgumentError(JSON.stringify(error.errors))); } else { res.send(200, sensors); } }); } /** * @api {get} /boxes/:boxId/data/:sensorId?from-date=:fromDate&to-date:toDate Get last n measurements for a sensor * @apiDescription Get up to 1000 measurements from a sensor for a specific time frame, parameters `from-date` and `to-date` are optional. If not set, the last 24 hours are used. The maximum time frame is 1 month. A maxmimum of 1000 values wil be returned for each request. * @apiVersion 0.0.1 * @apiGroup Measurements * @apiName getData * @apiParam {ID} boxId senseBox unique ID. * @apiParam {ID} sensorId Sensor unique ID. * @apiParam {String} from-date Beginning date of measurement data (default: 24 hours ago from now) * @apiParam {String} to-date End date of measurement data (default: now) * @apiParam {String} download If set, offer download to the user (default: false, always on if CSV is used) * @apiParam {String} format Can be 'JSON' (default) or 'CSV' (default: JSON) */ function getData(req, res, next) { 'use strict' // default to now var toDate = (typeof req.params["to-date"] == 'undefined' || req.params["to-date"] == "") ? new Date() : new Date(req.params["to-date"]); // default to 48 hours earlier var fromDate = (typeof req.params["from-date"] == 'undefined' || req.params["from-date"] == "") ? new Date(toDate.valueOf() - TIME_AGO_48_H) : new Date(req.params["from-date"]); var format = getFormat(req, ["json", "csv"], "json"); if (typeof format === "undefined") { return next(new restify.InvalidArgumentError("Invalid format: " + req.params['format'])); } if (toDate.valueOf() < fromDate.valueOf()) { return next(new restify.InvalidArgumentError(JSON.stringify('Invalid time frame specified'))); } if (toDate.valueOf()-fromDate.valueOf() > TIME_AGO_MAX) { return next(new restify.InvalidArgumentError(JSON.stringify('Please choose a time frame up to 31 days maximum'))); } var queryLimit = 10000; var qry = { sensor_id: req.params.sensorId, createdAt: { $gte: new Date(fromDate), $lte: new Date(toDate) } }; if (format === "csv") { var stringifier = csvstringify({ columns: ['createdAt', 'value'], header: 1, delimiter: ';' }); var transformer = csvtransform(function (data) { data.createdAt = new Date(data.createdAt).toISOString(); return data; }); transformer.on('error', function(err){ console.log(err.message); _postToSlack(err.message); return next(new restify.InternalServerError(JSON.stringify(err.message))); }); res.header('Content-Type', 'text/csv'); res.header('Content-Disposition', 'attachment; filename='+req.params.sensorId+'.csv'); Measurement.find(qry,{"createdAt":1, "value":1, "_id": 0}) // do not send _id column .limit(queryLimit) .lean() .cursor({ batchSize: 500 }) .pipe(transformer) .pipe(stringifier) .pipe(res); } else if (format === "json") { res.header('Content-Type', 'application/json; charset=utf-8'); if (typeof req.params["download"] !== "undefined" && req.params["download"] === "true"){ // offer download to browser res.header('Content-Disposition', 'attachment; filename='+req.params.sensorId+'.'+format); } let returnlength = 0; let index = 0; Measurement.find(qry, {"createdAt":1, "value":1, "_id": 0}) // do not send _id column .limit(queryLimit) .lean() .cursor({ batchSize: 500 }) .eachAsync((doc) => { returnlength = 1; doc.__v = undefined; // !(index++) is true the first time because !(0) evaluates to true // http://stackoverflow.com/a/34485539/1781026 res.write((!(index++) ? '[' : ',') + JSON.stringify(doc)) }) .then(() => { if (returnlength === 0) { res.status(404); res.end("[]"); } else { res.end("]"); } }) .catch(function (err) { console.log(err); _postToSlack(err.errors); return next(new restify.InternalServerError(JSON.stringify(err.errors))); }); } } /** * @api {get,post} /boxes/data?boxid=:boxIdsfrom-date=:fromDate&to-date:toDate&phenomenon=:phenomenon Get last n measurements for a sensor * @apiDescription Download data from multiple boxes as CSV * @apiVersion 0.1.0 * @apiGroup Measurements * @apiName getDataMulti * @apiParam {ID} boxId Comma separated list of senseBox unique IDs. */ function getDataMulti(req, res, next) { 'use strict' // default to now var toDate = (typeof req.params["to-date"] == 'undefined' || req.params["to-date"] == "") ? new Date() : new Date(req.params["to-date"]); // default to 15 days earlier var fromDate = (typeof req.params["from-date"] == 'undefined' || req.params["from-date"] == "") ? new Date(toDate.valueOf() - TIME_AGO_15_D) : new Date(req.params["from-date"]); if (toDate.valueOf() < fromDate.valueOf()) { return next(new restify.InvalidArgumentError(JSON.stringify('Invalid time frame specified'))); } if (toDate.valueOf()-fromDate.valueOf() > TIME_AGO_MAX) { return next(new restify.InvalidArgumentError(JSON.stringify('Please choose a time frame up to 31 days maximum'))); } log.debug(fromDate, "to", toDate); if(req.params["phenomenon"] && req.params["boxid"]) { //var generator = csvstringify({columns: ['createdAt', 'value']}); var phenom = req.params["phenomenon"].toString(); var boxId = req.params["boxid"].toString(); var boxIds = boxId.split(','); Box.find({ '_id': { '$in': boxIds }, 'sensors.title': req.params["phenomenon"].toString() }) .lean() .exec() .then(function (boxData) { var sensors = Object.create(null); for (var i = 0, len = boxData.length; i < len; i++) { for (var j = 0, sensorslen = boxData[i].sensors.length; j < sensorslen; j++) { if (boxData[i].sensors[j].title === phenom) { sensors[boxData[i].sensors[j]['_id']] = Object.create(null); sensors[boxData[i].sensors[j]['_id']].lat = boxData[i].loc[0].geometry.coordinates[0]; sensors[boxData[i].sensors[j]['_id']].lng = boxData[i].loc[0].geometry.coordinates[1]; } } } var stringifier = csvstringify({ columns: ['createdAt', 'value', 'lat', 'lng'], header: 1, delimiter: ';' }); var transformer = csvtransform(function (data) { data.createdAt = new Date(data.createdAt).toISOString(); data.lat = sensors[data.sensor_id].lat; data.lng = sensors[data.sensor_id].lng; return data; }); transformer.on('error', function(err){ console.log(err.message); _postToSlack(err.message); return next(new restify.InternalServerError(JSON.stringify(err.message))); }); Measurement.find({ 'sensor_id': { '$in': Object.keys(sensors) }, createdAt: { "$gt": fromDate, "$lt": toDate } }, {"createdAt":1, "value":1, "_id": 0, "sensor_id":1}) .lean() .cursor({ batchSize: 500 }) .pipe(transformer) .pipe(stringifier) .pipe(res) }) .catch(function (err) { console.log(err); _postToSlack(err.errors); return next(new restify.InternalServerError(JSON.stringify(err.errors))); }); } else { return next(new restify.InvalidArgumentError(JSON.stringify('Invalid parameters'))); } } /** * @api {post} /boxes/:boxId/:sensorId Post new measurement * @apiDescription Posts a new measurement to a specific sensor of a box. * @apiVersion 0.0.1 * @apiGroup Measurements * @apiName postNewMeasurement * @apiParam {ID} boxId senseBox unique ID. * @apiParam {ID} sensorId Sensors unique ID. * @apiParamExample Request-Example: * curl --data value=22 localhost:8000/boxes/56ccb342eda956582a88e48c/56ccb342eda956582a88e490 */ function postNewMeasurement(req, res, next) { Box.findOne({_id: req.params.boxId}, function(error,box){ if (error) { return next(new restify.InvalidArgumentError(JSON.stringify(error.message))); } else { if (!box) { return next(new restify.NotFoundError("box not found")); } saveMeasurement(box, req.params.sensorId, req.params.value, req.params.createdAt).then(function(result){ if(result){ res.send(201, "Measurement saved in box"); } else { return next(new restify.BadRequestError("Measurement could not be saved")); } }) .catch(function (err) { if (err === "sensor not found") { return next(new restify.NotFoundError("sensor not found in box")); } var errmsg = "Measurement could not be saved"; if (err.message) { errmsg += ": " + err.message; } return next(new restify.BadRequestError(errmsg)); }); } }); } function saveMeasurement(box, sensorId, value, createdAt){ for (var i = box.sensors.length - 1; i >= 0; i--) { if (box.sensors[i]._id.equals(sensorId)) { var measurementData = { value: value, _id: mongoose.Types.ObjectId(), sensor_id: sensorId }; if (typeof createdAt !== "undefined") { try { measurementData.createdAt = new Date(createdAt); } catch (e) { return Promise.reject(e); } } var measurement = new Measurement(measurementData); box.sensors[i].lastMeasurement = measurement._id; var qrys = [ box.save(), measurement.save() ]; return Promise.all(qrys); } else if (i === 0) { return Promise.reject("sensor not found"); } }; } /** * @api {post} /boxes/:boxId/data Post multiple new measurements * @apiDescription Post multiple new measurements as an JSON array to a box. * @apiVersion 0.1.0 * @apiGroup Measurements * @apiName postNewMeasurements * @apiParam {ID} boxId senseBox unique ID. * @apiSampleRequest * [{ "sensor": "56cb7c25b66992a02fe389de", "value": "3" },{ "sensor": "56cb7c25b66992a02fe389df", "value": "2" }] * curl -X POST -H 'Content-type:application/json' -d "[{ \"sensor\": \"56cb7c25b66992a02fe389de\", \"value\": \"3\" },{ \"sensor\": \"56cb7c25b66992a02fe389df\", \"value\": \"2\" }]" localhost:8000/boxes/56cb7c25b66992a02fe389d9/data */ function postNewMeasurements(req, res, next) { // when the body is an array, restify overwrites the req.params with the given array. // to get the boxId, try to extract it from the path var boxId = req.path().split("/")[2]; Box.findOne({ _id: boxId }) .then(function (box) { if (!box) { return next(new restify.NotFoundError("no senseBox found")); } saveMeasurementArray(box, req.body) .then(function () { res.send(201, "Measurements saved in box"); }) .catch(function (err) { console.log(err); _postToSlack(err); return next(new restify.InternalServerError(JSON.stringify(err))); }); }) .catch(function (err) { console.log(err); _postToSlack(err); return next(new restify.InternalServerError(JSON.stringify(err))); }); } function saveMeasurementArray (box, data) { if (!Array.isArray(data)) { return Promise.reject("array expected"); } if (data.length > 2000) { return Promise.reject("array too big. Please stay below 2000 items"); } var qrys = []; data.forEach(function (measurement) { for (var i = box.sensors.length - 1; i >= 0; i--) { if (box.sensors[i]._id.equals(measurement.sensor)) { var measurementData = { value: measurement.value, _id: mongoose.Types.ObjectId(), sensor_id: measurement.sensor }; if (typeof measurement.createdAt !== "undefined") { try { measurementData.createdAt = new Date(measurement.createdAt); } catch (e) { return Promise.reject(e); } } var measurement = new Measurement(measurementData); box.sensors[i].lastMeasurement = measurement._id; qrys.push(box.save()); qrys.push(measurement.save()); } } }); return Promise.all(qrys); } /** * @api {get} /boxes?date=:date&phenomenon=:phenomenon Get all senseBoxes. With the optional `date` and `phenomenon` parameters you can find senseBoxes that have submitted data around that time, +/- 2 hours, or specify two dates separated by a comma. * @apiName findAllBoxes * @apiGroup Boxes * @apiVersion 0.1.0 * @apiParam {String} date A date or datetime (UTC) where a station should provide measurements. Use in combination with `phenomenon`. * @apiParam {String} phenomenon A sensor phenomenon (determined by sensor name) such as temperature, humidity or UV intensity. Use in combination with `date`. * @apiSampleRequest http://opensensemap.org:8000/boxes * @apiSampleRequest http://opensensemap.org:8000/boxes?date=2015-03-07T02:50Z&phenomenon=Temperatur * @apiSampleRequest http://opensensemap.org:8000/boxes?date=2015-03-07T02:50Z,2015-04-07T02:50Z&phenomenon=Temperatur */ function findAllBoxes(req, res , next){ var activityAroundDate = (typeof req.params["date"] === 'undefined' || req.params["date"] === "") ? undefined : req.params["date"]; var phenomenon = (typeof req.params["phenomenon"] === 'undefined' || req.params["phenomenon"] === "") ? undefined : req.params["phenomenon"]; var format = getFormat(req, ["json", "geojson"], "json"); if (typeof format === "undefined") { return next(new restify.InvalidArgumentError("Invalid format: " + req.params['format'])); } var fromDate, toDate, dates; if(activityAroundDate && (dates = activityAroundDate.split(',')) && dates.length===2 && moment(dates[0]).isBefore(dates[1])){ // moment().isBefore() will check the date's validities as well fromDate = moment.utc(dates[0]).toDate(); toDate = moment.utc(dates[1]).toDate(); } else if(moment(activityAroundDate).isValid()) { fromDate = moment.utc(activityAroundDate).subtract(4, 'hours').toDate(); toDate = moment.utc(activityAroundDate).add(4, 'hours').toDate(); } // prepare query & callback var boxQry = Box.find({}).populate('sensors.lastMeasurement'); var boxQryCallback = function(err, boxes){ // extend/update 'lastMeasurement' to the queried date var sensorQrys = []; if(typeof activityAroundDate !== 'undefined') { boxes.forEach(function(box){ box.sensors.forEach(function(sensor){ sensorQrys.push( Measurement.findOne({ sensor_id: sensor._id, createdAt: { "$gt": fromDate, "$lt": toDate } }).lean().exec() ); }); }); } Promise.all(sensorQrys).then(function(thatresult){ // merge 'old' data that was queried according to the date/timestamp into the box result set // by replacing the "lastMeasurement" attribute's values with one fitting the query if(typeof activityAroundDate !== 'undefined'/* && typeof phenomenon !== 'undefined'*/) { var _boxes = boxes.slice(); // TODO: too many loops _boxes.forEach(function(box){ box.sensors.forEach(function(sensor){ thatresult.forEach(function(thisresult){ if(thisresult !== null){ if(sensor.lastMeasurement){ if(thisresult.sensor_id.toString() == sensor._id.toString()) { sensor.lastMeasurement = thisresult; } } } }); }); }); return(_boxes); } return(boxes); }) .then(function (result_boxes) { // clean up result.. return result_boxes.map(function (box) { box.__v = undefined; box.sensor = box.sensors.map(function (sensor) { sensor.__v = undefined; if (sensor.lastMeasurement) { sensor.lastMeasurement.__v = undefined; } return sensor; }); box.loc[0]._id = undefined; return box; }); }) .then(function(resultset){ if (format === "json") { res.send(resultset); } else if (format === "geojson") { tmp = JSON.stringify(resultset); tmp = JSON.parse(tmp); var geojson = _.transform(tmp, function(result, n) { lat = n.loc[0].geometry.coordinates[1]; lng = n.loc[0].geometry.coordinates[0]; n["loc"] = undefined; n["lat"] = lat; n["lng"] = lng; return result.push(n); }); res.send(GeoJSON.parse(geojson, {Point: ['lat','lng']})); } }).catch(function (err) { console.log(err); _postToSlack(err); return next(new restify.InternalServerError(JSON.stringify(err))); }); }; // if date and phenom. are specified then filter boxes, // otherwise show all boxes if(typeof activityAroundDate !== 'undefined') { Measurement.find({ createdAt: { "$gt": fromDate, "$lt": toDate } }).lean().distinct('sensor_id', function(err,measurements){ var qry = { "sensors._id": { "$in": measurements } }; if(typeof phenomenon !== 'undefined'){ qry = { "sensors._id": { "$in": measurements }, "sensors.title": phenomenon }; } boxQry = Box.find(qry).populate('sensors.lastMeasurement'); boxQry.exec(boxQryCallback); }); } else { boxQry.exec(boxQryCallback); } } /** * @api {get} /boxes/:boxId Get one senseBox * @apiName findBox * @apiVersion 0.0.1 * @apiGroup Boxes * @apiParam {ID} boxId senseBox unique ID. * @apiSuccess {String} _id senseBox unique ID. * @apiSuccess {String} boxType senseBox type (fixed or mobile). * @apiSuccess {Array} sensors All attached sensors. * @apiSuccess {Array} loc Location of senseBox. * @apiSuccessExample Example data on success: * { "_id": "5386e44d5f08822009b8b614", "name": "PHOBOS", "boxType": "fixed", "sensors": [ { "_id": "5386e44d5f08822009b8b615", "boxes_id": "5386e44d5f08822009b8b614", "lastMeasurement": { "_id": "5388d07f5f08822009b937b7", "createdAt": "2014-05-30T18:39:59.353Z", "updatedAt": "2014-05-30T18:39:59.353Z", "value": "584", "sensor_id": "5386e44d5f08822009b8b615", }, "sensorType": "GL5528", "title": "Helligkeit", "unit": "Pegel" } ], "loc": [ { "_id": "5386e44d5f08822009b8b61a", "geometry": { "coordinates": [ 10.54555893642828, 49.61361673283691 ], "type": "Point" }, "type": "feature" } ] } */ function findBox(req, res, next) { var id = req.params['boxId'].toString(); var format = getFormat(req, ["json", "geojson"], "json"); if (typeof format === "undefined") { return next(new restify.InvalidArgumentError("Invalid format: " + req.params['format'])); } if (mongoose.Types.ObjectId.isValid(id)) { Box.findOne({_id: id}).exec().then(function(box){ if (box) { box.populate('sensors.lastMeasurement'); // clean up box box.__v = undefined; box.sensor = box.sensors.map(function (sensor) { sensor.__v = undefined; if (sensor.lastMeasurement) { sensor.lastMeasurement.__v = undefined; } return sensor; }); box.loc[0]._id = undefined; if (format === "json") { res.send(box); } else if (format === "geojson") { var tmp = JSON.stringify(box); tmp = JSON.parse(tmp); var lat = tmp.loc[0].geometry.coordinates[1]; var lng = tmp.loc[0].geometry.coordinates[0]; tmp["loc"] = undefined; tmp["lat"] = lat; tmp["lng"] = lng; var geojson = [tmp]; res.send(GeoJSON.parse(geojson, {Point: ['lat','lng']})); } } else { return next(new restify.NotFoundError("No senseBox found")); } }).catch(function (error) { var e = error.errors; _postToSlack(e); return next(new restify.InternalServerError(e)); }); } else{ return next(new restify.NotFoundError("No senseBox found")); } } function createNewUser (req) { var userData = { firstname: req.params.user.firstname, lastname: req.params.user.lastname, email: req.params.user.email, apikey: req.params.orderID, boxes: [] } var user = new User(userData); return user; } function createNewBox (req) { var boxData = { name: req.params.name, boxType: req.params.boxType, loc: req.params.loc, grouptag: req.params.tag, exposure: req.params.exposure, _id: mongoose.Types.ObjectId(), model: req.params.model, sensors: [] }; var box = new Box(boxData); if (req.params.model) { switch(req.params.model){ case 'homeEthernet': req.params.sensors = products.senseboxhome; break; case 'homeWifi': req.params.sensors = products.senseboxhome; break; case 'basicEthernet': req.params.sensors = products.senseboxbasic; break; default: break; } } for (var i = req.params.sensors.length - 1; i >= 0; i--) { var id = mongoose.Types.ObjectId(); var sensorData = { _id: id, title: req.params.sensors[i].title, unit: req.params.sensors[i].unit, sensorType: req.params.sensors[i].sensorType, icon: req.params.sensors[i].icon }; box.sensors.push(sensorData); }; return box; } /** * @api {post} /boxes Post new senseBox * @apiDescription Create a new senseBox. * @apiVersion 0.0.1 * @apiGroup Boxes * @apiName postNewBox */ function postNewBox(req, res, next) { User.findOne({apikey:req.params.orderID}, function (err, user) { if (err) { log.error(err); return res.send(400, "An error occured"); } else { log.debug("A new sensebox is being submitted"); if (!user) { var newUser = createNewUser(req); var newBox = createNewBox(req); var savedBox = {}; newUser._doc.boxes.push(newBox._doc._id.toString()); newBox.save( function (err, box) { if (err) { return next(new restify.InvalidArgumentError(JSON.stringify(error.errors))); } try { genScript(box, box.model); savedBox = box; newUser.save( function (err, user) { if (err) { return next(new restify.InvalidArgumentError(JSON.stringify(error.errors))); } else { if(cfg.email_host!==''){ sendWelcomeMail(user, newBox); sendYeahMail(user, newBox); _postToSlack("Eine neue <https://opensensemap.org/explore/" + newBox._id + "|senseBox> wurde registriert (" + newBox.name + ")"); } return res.send(201, user); } }); } catch (e) { log.error(e); return res.send(400, "An error occured"); } }); } else { log.error(err); return res.send(400, "An error occured"); } } }); next(); } // generate Arduino script function genScript(box, model) { var output = cfg.targetFolder+""+box._id+".ino"; try { if(fs.statSync(output)){ fs.unlinkSync(output); } } catch(e){} var isCustom = false; switch(model){ case 'homeEthernet': filename = "files/template_home/template_home.ino"; break; case 'basicEthernet': filename = "files/template_basic/template_basic.ino"; break; case 'homeWifi': filename = "files/template_home_wifi/template_home_wifi.ino"; break; default: isCustom = true; filename = "files/template_custom_setup/template_custom_setup.ino"; break; } fs.readFileSync(filename).toString().split('\n').forEach(function (line) { if (line.indexOf("//senseBox ID") != -1) { fs.appendFileSync(output, line.toString() + "\n"); fs.appendFileSync(output, '#define SENSEBOX_ID "'+box._id+'"\n'); } else if (line.indexOf("//Sensor IDs") != -1) { fs.appendFileSync(output, line.toString() + "\n"); var customSensorindex = 1; for (var i = box.sensors.length - 1; i >= 0; i--) { var sensor = box.sensors[i]; log.debug(sensor); if (!isCustom && sensor.title == "Temperatur") { fs.appendFileSync(output, '#define TEMPSENSOR_ID "'+sensor._id+'"\n'); } else if(!isCustom && sensor.title == "rel. Luftfeuchte") { fs.appendFileSync(output, '#define HUMISENSOR_ID "'+sensor._id+'"\n'); } else if(!isCustom && sensor.title == "Luftdruck") { fs.appendFileSync(output, '#define PRESSURESENSOR_ID "'+sensor._id+'"\n'); } else if(!isCustom && sensor.title == "Lautstärke") { fs.appendFileSync(output, '#define NOISESENSOR_ID "'+sensor._id+'"\n'); } else if(!isCustom && sensor.title == "Helligkeit") { fs.appendFileSync(output, '#define LIGHTSENSOR_ID "'+sensor._id+'"\n'); } else if (!isCustom && sensor.title == "Beleuchtungsstärke") { fs.appendFileSync(output, '#define LUXSENSOR_ID "'+sensor._id+'"\n'); } else if (!isCustom && sensor.title == "UV-Intensität") { fs.appendFileSync(output, '#define UVSENSOR_ID "'+sensor._id+'"\n'); } else { fs.appendFileSync(output, '#define SENSOR'+customSensorindex+'_ID "'+sensor._id+'" \/\/ '+sensor.title+'\n'); customSensorindex++; } } } else { fs.appendFileSync(output, line.toString() + "\n"); } }); } /** * @api {get} /boxes/:boxId/script Download the Arduino script for your senseBox * @apiName getScript * @apiGroup Boxes * @apiVersion 0.1.0 */ function getScript(req, res, next) { if (!req.headers["x-apikey"]) { return next(new restify.NotAuthorizedError()); } User.findOne({ apikey: req.headers["x-apikey"], boxes: { $in: [ req.params.boxId ] } }) .lean() .then(function (user) { if (user.boxes.indexOf(req.params.boxId) !== -1) { Box.findById(req.params.boxId).then(function (box) { var file = cfg.targetFolder+""+box._id+".ino"; if (!fs.existsSync(file)) { genScript(box, box.model); } return res.send(200, fs.readFileSync(file, 'utf-8')); }) .catch(function (err) { return next(new restify.NotFoundError(err.message)); }); } else { return next(new restify.NotAuthorizedError()); } }). catch(function (error) { console.log(error); return next(new restify.NotAuthorizedError()); }); } /** * @api {delete} /boxes/:boxId Delete a senseBox and its measurements * @apiName deleteBox * @apiGroup Boxes * @apiVersion 0.1.0 */ function deleteBox(req, res, next) { User.findOne({apikey:req.headers["x-apikey"]}, function (findusererror, user) { if (findusererror) { res.send(400, "ApiKey does not exist"); } if (user.boxes.indexOf(req.params.boxId) !== -1) { qrys = []; Box.findById(req.params.boxId, function (findboxerr, box) { box.sensors.forEach(function(sensor){ qrys.push(Measurement.find({ sensor_id: sensor._id }).remove()); }); qrys.push(box.remove()); qrys.push(user.remove()); }); Promise.all(qrys).then(function(thatresult){ }).then(function(){ res.send(200, "Box deleted"); }); } }); } /** * @api {get} /boxes/stats Get some statistics about the database * @apiName getStatistics * @apiGroup misc * @apiVersion 0.1.0 * @apiSuccessExample {json} [8,13, 2] // 8 boxes, 13 measurements in the database, 2 in the last minute */ function getStatistics(req, res, next){ var qrys = [ Box.count({}), Measurement.count({}), Measurement.count({ createdAt: { "$gt": new Date(Date.now() - 60000), "$lt": new Date() } }) ]; Promise.all(qrys).then(function(results){ res.send(200, results); }); } // Send box script to user via email function sendWelcomeMail(user, box) { var templatePath = './templates/registration.html'; var templateContent = fs.readFileSync(templatePath, encoding = 'utf8'); var template = _.template(templateContent); var compiled = template({ 'user': user, 'box': box }); var transporter = nodemailer.createTransport(smtpTransport({ host: cfg.email_host, port: cfg.email_port, secure: cfg.email_secure, auth: { user: cfg.email_user, pass: cfg.email_pass } })); transporter.use('compile', htmlToText()); transporter.sendMail({ from: { name: cfg.email_fromName, address: cfg.email_fromEmail }, replyTo: { name: cfg.email_fromName, address: cfg.email_replyTo }, to: { name: user.firstname+" "+user.lastname, address: user.email }, subject: cfg.email_subject, template: 'registration', html: compiled, attachments: [ { filename: "sensebox.ino", path: cfg.targetFolder + box._id + ".ino" } ] }, function(err, info){ if(err){ log.error("Email error"); log.error(err); } if(info){ log.debug("Email sent successfully"); } }); } // Send Yeah Mail to senseBox Team function sendYeahMail(user, box) { var templatePath = './templates/yeah.html'; var templateContent = fs.readFileSync(templatePath, encoding = 'utf8'); var template = _.template(templateContent); var compiled = template({ 'user': user, 'box': box }); var transporter = nodemailer.createTransport(smtpTransport({ host: cfg.email_host, port: cfg.email_port, secure: cfg.email_secure, auth: { user: cfg.email_user, pass: cfg.email_pass } })); transporter.use('compile', htmlToText()); transporter.sendMail({ from: { name: cfg.email_fromName, address: cfg.email_fromEmail }, replyTo: { name: cfg.email_fromName, address: cfg.email_replyTo }, to: { name: user.firstname+" "+user.lastname, address: "[email protected]" }, subject: cfg.email_subject, template: 'yeah', html: compiled }, function(err, info){ if(err){ log.error("Email error"); log.error(err); } if(info){ log.debug("Email sent successfully"); } }); } function _postToSlack (text) { if (cfg.slack_url) { request.post({ url: cfg.slack_url, json: { text: text }}); } } function isEmptyObject(obj) { return !Object.keys(obj).length; } server.listen(cfg.port, function () { console.log('%s listening at %s', server.name, server.url); }); server.on('uncaughtException', function (req, res, route, err) { _postToSlack("Error in API (" + route.spec.method + " " + route.spec.path + ", " + req.href() + "): " + err); log.error('Uncaught error', err); console.log(err.stack); return res.send(500, "An error occured"); });
app.js
var restify = require('restify'), mongoose = require('mongoose'), fs = require('fs'), GeoJSON = require('geojson'), _ = require('lodash'), products = require('./products'), cfg = require('./config'), schemas = require('./schemas'), csvstringify = require('csv-stringify'), csvtransform = require('stream-transform'), Stream = require('stream'), nodemailer = require('nodemailer'), smtpTransport = require('nodemailer-smtp-transport'), htmlToText = require('nodemailer-html-to-text').htmlToText, moment = require('moment'), request = require('request'); mongoose.Promise = require('bluebird'); var dbHost = process.env.DB_HOST || cfg.dbhost; var TIME_AGO_MAX = 1000*60*60*24*32; var TIME_AGO_48_H = 1000*60*60*48; // 48 hours var TIME_AGO_15_D = 1000*60*60*24*15 // 15 days /* Logging */ var consoleStream = new Stream(); consoleStream.writable = true; consoleStream.write = function(obj) { if(obj.req){ console.log(obj.time, obj.req.remoteAddress, obj.req.method, obj.req.url); } else if(obj.msg) { console.log(obj.time, obj.msg); } else { //console.log(obj.time, obj); } }; var Logger = require('bunyan'), reqlog = new Logger.createLogger({ name: 'OSeM-API', streams: [ { level: 'debug', type: 'raw', stream: consoleStream } ], serializers: { err: Logger.stdSerializers.err, req: Logger.stdSerializers.req, res: Logger.stdSerializers.res } }), log = new Logger.createLogger({ name: 'OSeM-API', streams: [ { level: 'debug', type: 'raw', stream: consoleStream } ], serializers: { err: Logger.stdSerializers.err, req: Logger.stdSerializers.req, res: Logger.stdSerializers.res } }); var server = restify.createServer({ name: 'opensensemap-api', version: '0.0.1', log: reqlog }); server.use(restify.CORS({'origins': ['*'] })); //['http://localhost', 'https://opensensemap.org']})); server.use(restify.fullResponse()); server.use(restify.queryParser()); server.use(restify.bodyParser()); server.pre(function(request, response, next) { response.charSet('utf-8'); request.log.info({req: request}, 'REQUEST'); return next(); }); // use this function to retry if a connection cannot be established immediately var connectWithRetry = function () { return mongoose.connect(cfg.dbconnectionstring, { keepAlive: 1 }, function (err) { if (err) { console.error('Failed to connect to mongo on startup - retrying in 5 sec', err); setTimeout(connectWithRetry, 5000); } }); }; conn = connectWithRetry(); var LocationSchema = schemas.LocationSchema; var measurementSchema = schemas.measurementSchema; var sensorSchema = schemas.sensorSchema; var boxSchema = schemas.boxSchema; var userSchema = schemas.userSchema; var Measurement = mongoose.model('Measurement', measurementSchema); var Box = mongoose.model('Box', boxSchema); var Sensor = mongoose.model('Sensor', sensorSchema); var User = mongoose.model('User', userSchema); var Location = mongoose.model('Location', LocationSchema); var PATH = '/boxes'; var userPATH = 'users'; // GET server.get({path : PATH , version : '0.0.1'} , findAllBoxes); server.get({path : /(boxes)\.([a-z]+)/, version : '0.1.0'} , findAllBoxes); server.get({path : PATH +'/:boxId' , version : '0.0.1'} , findBox); server.get({path : PATH +'/:boxId/sensors', version : '0.0.1'}, getMeasurements); server.get({path : PATH +'/:boxId/data/:sensorId', version : '0.0.1'}, getData); server.get({path : PATH +'/data', version : '0.1.0'}, getDataMulti); server.get({path : userPATH +'/:boxId', version : '0.0.1'}, validApiKey); server.get({path : PATH +'/:boxId/script', version : '0.1.0'}, getScript); server.get({path : '/stats', version : '0.1.0'}, getStatistics); // POST server.post({path : PATH , version: '0.0.1'}, postNewBox); server.post({path : PATH +'/:boxId/:sensorId' , version : '0.0.1'}, postNewMeasurement); server.post({path : PATH +'/:boxId/data' , version : '0.1.0'}, postNewMeasurements); server.post({path : PATH +'/data', version : '0.1.0'}, getDataMulti); // PUT server.put({path: PATH + '/:boxId' , version: '0.1.0'} , updateBox); // DELETE server.del({path: PATH + '/:boxId' , version: '0.1.0'} , deleteBox); // helper function to determine the requested format function getFormat (req, allowed_formats, default_format) { if (typeof req.params["format"] === "undefined") { return default_format; } else if (allowed_formats.indexOf(req.params["format"].toLowerCase()) !== -1) { return req.params["format"]; } } function unknownMethodHandler(req, res) { if (req.method.toLowerCase() === 'options') { var allowHeaders = ['Accept', 'X-ApiKey', 'Accept-Version', 'Content-Type', 'Api-Version', 'Origin', 'X-Requested-With']; // added Origin & X-Requested-With if (res.methods.indexOf('OPTIONS') === -1) res.methods.push('OPTIONS'); res.header('Access-Control-Allow-Credentials', true); res.header('Access-Control-Allow-Headers', allowHeaders.join(', ')); res.header('Access-Control-Allow-Methods', res.methods.join(', ')); res.header('Access-Control-Allow-Origin', req.headers.origin); return res.send(204); } else { return res.send(new restify.MethodNotAllowedError()); } } server.on('MethodNotAllowed', unknownMethodHandler); /** * @api {get} /boxes/users/:boxId Check for valid API key * @apiDescription Check for valid API key. Will return status code 400 if invalid, 200 if valid. * @apiParam {ID} boxId senseBox unique ID. * @apiHeader {ObjectId} x-apikey senseBox specific apikey * @apiHeaderExample {json} Request-Example: * { * 'X-ApiKey':54d3a96d5438b4440913434b * } * @apiError {String} ApiKey is invalid! * @apiError {String} ApiKey not existing! * @apiSuccess {String} ApiKey is valid! * @apiVersion 0.0.1 * @apiGroup Boxes * @apiName validApiKey */ function validApiKey (req,res,next) { User.findOne({apikey:req.headers['x-apikey']}, function (error, user) { if (error) { res.send(400, "ApiKey does not exist"); } if (user && user.boxes.length > 0 && user.boxes.indexOf(req.params.boxId) != -1) { res.send(200, "ApiKey is valid"); } else { res.send(400, "ApiKey is invalid"); } }); } function decodeBase64Image(dataString) { var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/), response = {}; if (matches.length !== 3) { return new Error('Invalid input string'); } response.type = matches[1]; response.data = new Buffer(matches[2], 'base64'); return response; } /** * @api {put} /boxes/:boxId Update a senseBox: Image and sensor names * @apiDescription Modify the specified senseBox. * @apiParam {ID} boxId senseBox unique ID. * @apiHeader {ObjectId} x-apikey senseBox specific apikey * @apiHeaderExample {json} Request-Example: * { * 'X-ApiKey':54d3a96d5438b4440913434b * } * @apiSampleRequest * { * "_id": "56e741ff933e450c0fe2f705", * "name": "MeineBox", * "sensors": [ * { * "_id": "56e741ff933e450c0fe2f707", * "title": "UV-Intensität", * "unit": "μW/cm²", * "sensorType": "VEML6070", * } * ], * "grouptag": "vcxyxsdf", * "exposure": "outdoor", * "loc": { * "lng": 8.6956, * "lat": 50.0430 * } * } * @apiVersion 0.0.1 * @apiGroup Boxes * @apiName updateBox */ function updateBox(req, res, next) { /* var newBoxData = { _id name sensors description weblink grouptag exposure loc image }; */ User.findOne({apikey:req.headers["x-apikey"]}, function (error, user) { if (error) { res.send(400, "ApiKey does not exist"); } var qrys = []; if (user.boxes.indexOf(req.params.boxId) !== -1) { Box.findById(req.params.boxId, function (err, box) { if (err) return handleError(err); if (typeof req.params.name !== 'undefined' && req.params.name !== "") { if(box.name !== req.params.name) qrys.push(box.set({name: req.params.name})); } if (typeof req.params.exposure !== 'undefined' && req.params.exposure !== "") { if(box.exposure !== req.params.exposure) qrys.push(box.set({exposure: req.params.exposure})); } if (typeof req.params.grouptag !== 'undefined' && req.params.grouptag !== "") { if(box.grouptag !== req.params.grouptag) qrys.push(box.set({grouptag: req.params.grouptag})); } if (typeof req.params.weblink !== 'undefined' && req.params.weblink !== "") { if(box.weblink !== req.params.weblink) qrys.push(box.set({weblink: req.params.weblink})); } if (typeof req.params.description !== 'undefined' && req.params.description !== "") { if(box.description !== req.params.description) qrys.push(box.set({description: req.params.description})); } if (typeof req.params.loc !== 'undefined' && req.params.loc !== "") { if(String(box.loc[0].geometry.coordinates[0]) !== req.params.loc.lng || String(box.loc[0].geometry.coordinates[1]) !== req.params.loc.lat){ box.loc[0].geometry.coordinates = [req.params.loc.lng, req.params.loc.lat]; } } if (typeof req.params.image !== 'undefined' && req.params.image !== "") { var data = req.params.image.toString(); var imageBuffer = decodeBase64Image(data); var extension = (imageBuffer.type === 'image/jpeg') ? '.jpg' : '.png'; try { fs.writeFileSync(cfg.imageFolder+""+req.params.boxId+extension, imageBuffer.data); qrys.push(box.set({image: req.params.boxId+extension+'?'+(new Date().getTime())})); } catch(e) { if (err) return handleError(e); } } if (typeof req.params.sensors !== 'undefined' && req.params.sensors.length>0) { req.params.sensors.forEach(function(updatedsensor){ if(updatedsensor.deleted){ qrys.push(Measurement.find({ sensor_id: updatedsensor._id }).remove()); qrys.push(Box.update({'sensors._id': mongoose.Types.ObjectId(updatedsensor._id)}, { $pull: { 'sensors': { _id: mongoose.Types.ObjectId(updatedsensor._id) } } })); } else if(updatedsensor.edited && updatedsensor.new) { var newsensor = new Sensor({ 'title': updatedsensor.title, 'unit': updatedsensor.unit, 'sensorType': updatedsensor.sensorType, 'icon' : updatedsensor.icon }); box.sensors.push(newsensor); }else if(updatedsensor.edited && !updatedsensor.deleted){ qrys.push(Box.update({'sensors._id': mongoose.Types.ObjectId(updatedsensor._id)}, {'$set': { 'sensors.$.title': updatedsensor.title, 'sensors.$.unit': updatedsensor.unit, 'sensors.$.sensorType': updatedsensor.sensorType, 'sensors.$.icon': updatedsensor.icon }})); } }); } qrys.push(box.save()); Promise.all(qrys).then(function(){ genScript(box, box.model); res.send(200, box); }); }); } else { res.send(400, "ApiKey does not match senseBoxID"); } }); } /** * @api {get} /boxes/:boxId/sensors Get all last measurements * @apiDescription Get last measurements of all sensors of the secified senseBox. * @apiVersion 0.0.1 * @apiGroup Measurements * @apiName getMeasurements * @apiParam {ID} boxId senseBox unique ID. */ function getMeasurements(req, res, next) { Box.findOne({_id: req.params.boxId},{sensors:1}).populate('sensors.lastMeasurement').lean().exec(function(error,sensors){ if (error) { return next(new restify.InvalidArgumentError(JSON.stringify(error.errors))); } else { res.send(200, sensors); } }); } /** * @api {get} /boxes/:boxId/data/:sensorId?from-date=:fromDate&to-date:toDate Get last n measurements for a sensor * @apiDescription Get up to 1000 measurements from a sensor for a specific time frame, parameters `from-date` and `to-date` are optional. If not set, the last 24 hours are used. The maximum time frame is 1 month. A maxmimum of 1000 values wil be returned for each request. * @apiVersion 0.0.1 * @apiGroup Measurements * @apiName getData * @apiParam {ID} boxId senseBox unique ID. * @apiParam {ID} sensorId Sensor unique ID. * @apiParam {String} from-date Beginning date of measurement data (default: 24 hours ago from now) * @apiParam {String} to-date End date of measurement data (default: now) * @apiParam {String} download If set, offer download to the user (default: false, always on if CSV is used) * @apiParam {String} format Can be 'JSON' (default) or 'CSV' (default: JSON) */ function getData(req, res, next) { 'use strict' // default to now var toDate = (typeof req.params["to-date"] == 'undefined' || req.params["to-date"] == "") ? new Date() : new Date(req.params["to-date"]); // default to 48 hours earlier var fromDate = (typeof req.params["from-date"] == 'undefined' || req.params["from-date"] == "") ? new Date(toDate.valueOf() - TIME_AGO_48_H) : new Date(req.params["from-date"]); var format = getFormat(req, ["json", "csv"], "json"); if (typeof format === "undefined") { return next(new restify.InvalidArgumentError("Invalid format: " + req.params['format'])); } if (toDate.valueOf() < fromDate.valueOf()) { return next(new restify.InvalidArgumentError(JSON.stringify('Invalid time frame specified'))); } if (toDate.valueOf()-fromDate.valueOf() > TIME_AGO_MAX) { return next(new restify.InvalidArgumentError(JSON.stringify('Please choose a time frame up to 31 days maximum'))); } var queryLimit = 10000; var qry = { sensor_id: req.params.sensorId, createdAt: { $gte: new Date(fromDate), $lte: new Date(toDate) } }; if (format === "csv") { var stringifier = csvstringify({ columns: ['createdAt', 'value'], header: 1, delimiter: ';' }); var transformer = csvtransform(function (data) { data.createdAt = new Date(data.createdAt).toISOString(); return data; }); transformer.on('error', function(err){ console.log(err.message); _postToSlack(err.message); return next(new restify.InternalServerError(JSON.stringify(err.message))); }); res.header('Content-Type', 'text/csv'); res.header('Content-Disposition', 'attachment; filename='+req.params.sensorId+'.csv'); Measurement.find(qry,{"createdAt":1, "value":1, "_id": 0}) // do not send _id column .limit(queryLimit) .lean() .cursor() .pipe(transformer) .pipe(stringifier) .pipe(res); } else if (format === "json") { res.header('Content-Type', 'application/json; charset=utf-8'); if (typeof req.params["download"] !== "undefined" && req.params["download"] === "true"){ // offer download to browser res.header('Content-Disposition', 'attachment; filename='+req.params.sensorId+'.'+format); } let returnlength = 0; let index = 0; Measurement.find(qry, {"createdAt":1, "value":1, "_id": 0}) // do not send _id column .limit(queryLimit) .lean() .cursor() .eachAsync((doc) => { returnlength = 1; doc.__v = undefined; // !(index++) is true the first time because !(0) evaluates to true // http://stackoverflow.com/a/34485539/1781026 res.write((!(index++) ? '[' : ',') + JSON.stringify(doc)) }) .then(() => { if (returnlength === 0) { res.status(404); res.end("[]"); } else { res.end("]"); } }) .catch(function (err) { console.log(err); _postToSlack(err.errors); return next(new restify.InternalServerError(JSON.stringify(err.errors))); }); } } /** * @api {get,post} /boxes/data?boxid=:boxIdsfrom-date=:fromDate&to-date:toDate&phenomenon=:phenomenon Get last n measurements for a sensor * @apiDescription Download data from multiple boxes as CSV * @apiVersion 0.1.0 * @apiGroup Measurements * @apiName getDataMulti * @apiParam {ID} boxId Comma separated list of senseBox unique IDs. */ function getDataMulti(req, res, next) { 'use strict' // default to now var toDate = (typeof req.params["to-date"] == 'undefined' || req.params["to-date"] == "") ? new Date() : new Date(req.params["to-date"]); // default to 15 days earlier var fromDate = (typeof req.params["from-date"] == 'undefined' || req.params["from-date"] == "") ? new Date(toDate.valueOf() - TIME_AGO_15_D) : new Date(req.params["from-date"]); if (toDate.valueOf() < fromDate.valueOf()) { return next(new restify.InvalidArgumentError(JSON.stringify('Invalid time frame specified'))); } if (toDate.valueOf()-fromDate.valueOf() > TIME_AGO_MAX) { return next(new restify.InvalidArgumentError(JSON.stringify('Please choose a time frame up to 31 days maximum'))); } log.debug(fromDate, "to", toDate); if(req.params["phenomenon"] && req.params["boxid"]) { //var generator = csvstringify({columns: ['createdAt', 'value']}); var phenom = req.params["phenomenon"].toString(); var boxId = req.params["boxid"].toString(); var boxIds = boxId.split(','); Box.find({ '_id': { '$in': boxIds }, 'sensors.title': req.params["phenomenon"].toString() }) .lean() .exec() .then(function (boxData) { var sensors = Object.create(null); for (var i = 0, len = boxData.length; i < len; i++) { for (var j = 0, sensorslen = boxData[i].sensors.length; j < sensorslen; j++) { if (boxData[i].sensors[j].title === phenom) { sensors[boxData[i].sensors[j]['_id']] = Object.create(null); sensors[boxData[i].sensors[j]['_id']].lat = boxData[i].loc[0].geometry.coordinates[0]; sensors[boxData[i].sensors[j]['_id']].lng = boxData[i].loc[0].geometry.coordinates[1]; } } } var stringifier = csvstringify({ columns: ['createdAt', 'value', 'lat', 'lng'], header: 1, delimiter: ';' }); var transformer = csvtransform(function (data) { data.createdAt = new Date(data.createdAt).toISOString(); data.lat = sensors[data.sensor_id].lat; data.lng = sensors[data.sensor_id].lng; return data; }); transformer.on('error', function(err){ console.log(err.message); _postToSlack(err.message); return next(new restify.InternalServerError(JSON.stringify(err.message))); }); Measurement.find({ 'sensor_id': { '$in': Object.keys(sensors) }, createdAt: { "$gt": fromDate, "$lt": toDate } }, {"createdAt":1, "value":1, "_id": 0, "sensor_id":1}) .lean() .cursor() .pipe(transformer) .pipe(stringifier) .pipe(res) }) .catch(function (err) { console.log(err); _postToSlack(err.errors); return next(new restify.InternalServerError(JSON.stringify(err.errors))); }); } else { return next(new restify.InvalidArgumentError(JSON.stringify('Invalid parameters'))); } } /** * @api {post} /boxes/:boxId/:sensorId Post new measurement * @apiDescription Posts a new measurement to a specific sensor of a box. * @apiVersion 0.0.1 * @apiGroup Measurements * @apiName postNewMeasurement * @apiParam {ID} boxId senseBox unique ID. * @apiParam {ID} sensorId Sensors unique ID. * @apiParamExample Request-Example: * curl --data value=22 localhost:8000/boxes/56ccb342eda956582a88e48c/56ccb342eda956582a88e490 */ function postNewMeasurement(req, res, next) { Box.findOne({_id: req.params.boxId}, function(error,box){ if (error) { return next(new restify.InvalidArgumentError(JSON.stringify(error.message))); } else { if (!box) { return next(new restify.NotFoundError("box not found")); } saveMeasurement(box, req.params.sensorId, req.params.value, req.params.createdAt).then(function(result){ if(result){ res.send(201, "Measurement saved in box"); } else { return next(new restify.BadRequestError("Measurement could not be saved")); } }) .catch(function (err) { if (err === "sensor not found") { return next(new restify.NotFoundError("sensor not found in box")); } var errmsg = "Measurement could not be saved"; if (err.message) { errmsg += ": " + err.message; } return next(new restify.BadRequestError(errmsg)); }); } }); } function saveMeasurement(box, sensorId, value, createdAt){ for (var i = box.sensors.length - 1; i >= 0; i--) { if (box.sensors[i]._id.equals(sensorId)) { var measurementData = { value: value, _id: mongoose.Types.ObjectId(), sensor_id: sensorId }; if (typeof createdAt !== "undefined") { try { measurementData.createdAt = new Date(createdAt); } catch (e) { return Promise.reject(e); } } var measurement = new Measurement(measurementData); box.sensors[i].lastMeasurement = measurement._id; var qrys = [ box.save(), measurement.save() ]; return Promise.all(qrys); } else if (i === 0) { return Promise.reject("sensor not found"); } }; } /** * @api {post} /boxes/:boxId/data Post multiple new measurements * @apiDescription Post multiple new measurements as an JSON array to a box. * @apiVersion 0.1.0 * @apiGroup Measurements * @apiName postNewMeasurements * @apiParam {ID} boxId senseBox unique ID. * @apiSampleRequest * [{ "sensor": "56cb7c25b66992a02fe389de", "value": "3" },{ "sensor": "56cb7c25b66992a02fe389df", "value": "2" }] * curl -X POST -H 'Content-type:application/json' -d "[{ \"sensor\": \"56cb7c25b66992a02fe389de\", \"value\": \"3\" },{ \"sensor\": \"56cb7c25b66992a02fe389df\", \"value\": \"2\" }]" localhost:8000/boxes/56cb7c25b66992a02fe389d9/data */ function postNewMeasurements(req, res, next) { // when the body is an array, restify overwrites the req.params with the given array. // to get the boxId, try to extract it from the path var boxId = req.path().split("/")[2]; Box.findOne({ _id: boxId }) .then(function (box) { if (!box) { return next(new restify.NotFoundError("no senseBox found")); } saveMeasurementArray(box, req.body) .then(function () { res.send(201, "Measurements saved in box"); }) .catch(function (err) { console.log(err); _postToSlack(err); return next(new restify.InternalServerError(JSON.stringify(err))); }); }) .catch(function (err) { console.log(err); _postToSlack(err); return next(new restify.InternalServerError(JSON.stringify(err))); }); } function saveMeasurementArray (box, data) { if (!Array.isArray(data)) { return Promise.reject("array expected"); } if (data.length > 2000) { return Promise.reject("array too big. Please stay below 2000 items"); } var qrys = []; data.forEach(function (measurement) { for (var i = box.sensors.length - 1; i >= 0; i--) { if (box.sensors[i]._id.equals(measurement.sensor)) { var measurementData = { value: measurement.value, _id: mongoose.Types.ObjectId(), sensor_id: measurement.sensor }; if (typeof measurement.createdAt !== "undefined") { try { measurementData.createdAt = new Date(measurement.createdAt); } catch (e) { return Promise.reject(e); } } var measurement = new Measurement(measurementData); box.sensors[i].lastMeasurement = measurement._id; qrys.push(box.save()); qrys.push(measurement.save()); } } }); return Promise.all(qrys); } /** * @api {get} /boxes?date=:date&phenomenon=:phenomenon Get all senseBoxes. With the optional `date` and `phenomenon` parameters you can find senseBoxes that have submitted data around that time, +/- 2 hours, or specify two dates separated by a comma. * @apiName findAllBoxes * @apiGroup Boxes * @apiVersion 0.1.0 * @apiParam {String} date A date or datetime (UTC) where a station should provide measurements. Use in combination with `phenomenon`. * @apiParam {String} phenomenon A sensor phenomenon (determined by sensor name) such as temperature, humidity or UV intensity. Use in combination with `date`. * @apiSampleRequest http://opensensemap.org:8000/boxes * @apiSampleRequest http://opensensemap.org:8000/boxes?date=2015-03-07T02:50Z&phenomenon=Temperatur * @apiSampleRequest http://opensensemap.org:8000/boxes?date=2015-03-07T02:50Z,2015-04-07T02:50Z&phenomenon=Temperatur */ function findAllBoxes(req, res , next){ var activityAroundDate = (typeof req.params["date"] === 'undefined' || req.params["date"] === "") ? undefined : req.params["date"]; var phenomenon = (typeof req.params["phenomenon"] === 'undefined' || req.params["phenomenon"] === "") ? undefined : req.params["phenomenon"]; var format = getFormat(req, ["json", "geojson"], "json"); if (typeof format === "undefined") { return next(new restify.InvalidArgumentError("Invalid format: " + req.params['format'])); } var fromDate, toDate, dates; if(activityAroundDate && (dates = activityAroundDate.split(',')) && dates.length===2 && moment(dates[0]).isBefore(dates[1])){ // moment().isBefore() will check the date's validities as well fromDate = moment.utc(dates[0]).toDate(); toDate = moment.utc(dates[1]).toDate(); } else if(moment(activityAroundDate).isValid()) { fromDate = moment.utc(activityAroundDate).subtract(4, 'hours').toDate(); toDate = moment.utc(activityAroundDate).add(4, 'hours').toDate(); } // prepare query & callback var boxQry = Box.find({}).populate('sensors.lastMeasurement'); var boxQryCallback = function(err, boxes){ // extend/update 'lastMeasurement' to the queried date var sensorQrys = []; if(typeof activityAroundDate !== 'undefined') { boxes.forEach(function(box){ box.sensors.forEach(function(sensor){ sensorQrys.push( Measurement.findOne({ sensor_id: sensor._id, createdAt: { "$gt": fromDate, "$lt": toDate } }).lean().exec() ); }); }); } Promise.all(sensorQrys).then(function(thatresult){ // merge 'old' data that was queried according to the date/timestamp into the box result set // by replacing the "lastMeasurement" attribute's values with one fitting the query if(typeof activityAroundDate !== 'undefined'/* && typeof phenomenon !== 'undefined'*/) { var _boxes = boxes.slice(); // TODO: too many loops _boxes.forEach(function(box){ box.sensors.forEach(function(sensor){ thatresult.forEach(function(thisresult){ if(thisresult !== null){ if(sensor.lastMeasurement){ if(thisresult.sensor_id.toString() == sensor._id.toString()) { sensor.lastMeasurement = thisresult; } } } }); }); }); return(_boxes); } return(boxes); }) .then(function (result_boxes) { // clean up result.. return result_boxes.map(function (box) { box.__v = undefined; box.sensor = box.sensors.map(function (sensor) { sensor.__v = undefined; if (sensor.lastMeasurement) { sensor.lastMeasurement.__v = undefined; } return sensor; }); box.loc[0]._id = undefined; return box; }); }) .then(function(resultset){ if (format === "json") { res.send(resultset); } else if (format === "geojson") { tmp = JSON.stringify(resultset); tmp = JSON.parse(tmp); var geojson = _.transform(tmp, function(result, n) { lat = n.loc[0].geometry.coordinates[1]; lng = n.loc[0].geometry.coordinates[0]; n["loc"] = undefined; n["lat"] = lat; n["lng"] = lng; return result.push(n); }); res.send(GeoJSON.parse(geojson, {Point: ['lat','lng']})); } }).catch(function (err) { console.log(err); _postToSlack(err); return next(new restify.InternalServerError(JSON.stringify(err))); }); }; // if date and phenom. are specified then filter boxes, // otherwise show all boxes if(typeof activityAroundDate !== 'undefined') { Measurement.find({ createdAt: { "$gt": fromDate, "$lt": toDate } }).lean().distinct('sensor_id', function(err,measurements){ var qry = { "sensors._id": { "$in": measurements } }; if(typeof phenomenon !== 'undefined'){ qry = { "sensors._id": { "$in": measurements }, "sensors.title": phenomenon }; } boxQry = Box.find(qry).populate('sensors.lastMeasurement'); boxQry.exec(boxQryCallback); }); } else { boxQry.exec(boxQryCallback); } } /** * @api {get} /boxes/:boxId Get one senseBox * @apiName findBox * @apiVersion 0.0.1 * @apiGroup Boxes * @apiParam {ID} boxId senseBox unique ID. * @apiSuccess {String} _id senseBox unique ID. * @apiSuccess {String} boxType senseBox type (fixed or mobile). * @apiSuccess {Array} sensors All attached sensors. * @apiSuccess {Array} loc Location of senseBox. * @apiSuccessExample Example data on success: * { "_id": "5386e44d5f08822009b8b614", "name": "PHOBOS", "boxType": "fixed", "sensors": [ { "_id": "5386e44d5f08822009b8b615", "boxes_id": "5386e44d5f08822009b8b614", "lastMeasurement": { "_id": "5388d07f5f08822009b937b7", "createdAt": "2014-05-30T18:39:59.353Z", "updatedAt": "2014-05-30T18:39:59.353Z", "value": "584", "sensor_id": "5386e44d5f08822009b8b615", }, "sensorType": "GL5528", "title": "Helligkeit", "unit": "Pegel" } ], "loc": [ { "_id": "5386e44d5f08822009b8b61a", "geometry": { "coordinates": [ 10.54555893642828, 49.61361673283691 ], "type": "Point" }, "type": "feature" } ] } */ function findBox(req, res, next) { var id = req.params['boxId'].toString(); var format = getFormat(req, ["json", "geojson"], "json"); if (typeof format === "undefined") { return next(new restify.InvalidArgumentError("Invalid format: " + req.params['format'])); } if (mongoose.Types.ObjectId.isValid(id)) { Box.findOne({_id: id}).exec().then(function(box){ if (box) { box.populate('sensors.lastMeasurement'); // clean up box box.__v = undefined; box.sensor = box.sensors.map(function (sensor) { sensor.__v = undefined; if (sensor.lastMeasurement) { sensor.lastMeasurement.__v = undefined; } return sensor; }); box.loc[0]._id = undefined; if (format === "json") { res.send(box); } else if (format === "geojson") { var tmp = JSON.stringify(box); tmp = JSON.parse(tmp); var lat = tmp.loc[0].geometry.coordinates[1]; var lng = tmp.loc[0].geometry.coordinates[0]; tmp["loc"] = undefined; tmp["lat"] = lat; tmp["lng"] = lng; var geojson = [tmp]; res.send(GeoJSON.parse(geojson, {Point: ['lat','lng']})); } } else { return next(new restify.NotFoundError("No senseBox found")); } }).catch(function (error) { var e = error.errors; _postToSlack(e); return next(new restify.InternalServerError(e)); }); } else{ return next(new restify.NotFoundError("No senseBox found")); } } function createNewUser (req) { var userData = { firstname: req.params.user.firstname, lastname: req.params.user.lastname, email: req.params.user.email, apikey: req.params.orderID, boxes: [] } var user = new User(userData); return user; } function createNewBox (req) { var boxData = { name: req.params.name, boxType: req.params.boxType, loc: req.params.loc, grouptag: req.params.tag, exposure: req.params.exposure, _id: mongoose.Types.ObjectId(), model: req.params.model, sensors: [] }; var box = new Box(boxData); if (req.params.model) { switch(req.params.model){ case 'homeEthernet': req.params.sensors = products.senseboxhome; break; case 'homeWifi': req.params.sensors = products.senseboxhome; break; case 'basicEthernet': req.params.sensors = products.senseboxbasic; break; default: break; } } for (var i = req.params.sensors.length - 1; i >= 0; i--) { var id = mongoose.Types.ObjectId(); var sensorData = { _id: id, title: req.params.sensors[i].title, unit: req.params.sensors[i].unit, sensorType: req.params.sensors[i].sensorType, icon: req.params.sensors[i].icon }; box.sensors.push(sensorData); }; return box; } /** * @api {post} /boxes Post new senseBox * @apiDescription Create a new senseBox. * @apiVersion 0.0.1 * @apiGroup Boxes * @apiName postNewBox */ function postNewBox(req, res, next) { User.findOne({apikey:req.params.orderID}, function (err, user) { if (err) { log.error(err); return res.send(400, "An error occured"); } else { log.debug("A new sensebox is being submitted"); if (!user) { var newUser = createNewUser(req); var newBox = createNewBox(req); var savedBox = {}; newUser._doc.boxes.push(newBox._doc._id.toString()); newBox.save( function (err, box) { if (err) { return next(new restify.InvalidArgumentError(JSON.stringify(error.errors))); } try { genScript(box, box.model); savedBox = box; newUser.save( function (err, user) { if (err) { return next(new restify.InvalidArgumentError(JSON.stringify(error.errors))); } else { if(cfg.email_host!==''){ sendWelcomeMail(user, newBox); sendYeahMail(user, newBox); _postToSlack("Eine neue <https://opensensemap.org/explore/" + newBox._id + "|senseBox> wurde registriert (" + newBox.name + ")"); } return res.send(201, user); } }); } catch (e) { log.error(e); return res.send(400, "An error occured"); } }); } else { log.error(err); return res.send(400, "An error occured"); } } }); next(); } // generate Arduino script function genScript(box, model) { var output = cfg.targetFolder+""+box._id+".ino"; try { if(fs.statSync(output)){ fs.unlinkSync(output); } } catch(e){} var isCustom = false; switch(model){ case 'homeEthernet': filename = "files/template_home/template_home.ino"; break; case 'basicEthernet': filename = "files/template_basic/template_basic.ino"; break; case 'homeWifi': filename = "files/template_home_wifi/template_home_wifi.ino"; break; default: isCustom = true; filename = "files/template_custom_setup/template_custom_setup.ino"; break; } fs.readFileSync(filename).toString().split('\n').forEach(function (line) { if (line.indexOf("//senseBox ID") != -1) { fs.appendFileSync(output, line.toString() + "\n"); fs.appendFileSync(output, '#define SENSEBOX_ID "'+box._id+'"\n'); } else if (line.indexOf("//Sensor IDs") != -1) { fs.appendFileSync(output, line.toString() + "\n"); var customSensorindex = 1; for (var i = box.sensors.length - 1; i >= 0; i--) { var sensor = box.sensors[i]; log.debug(sensor); if (!isCustom && sensor.title == "Temperatur") { fs.appendFileSync(output, '#define TEMPSENSOR_ID "'+sensor._id+'"\n'); } else if(!isCustom && sensor.title == "rel. Luftfeuchte") { fs.appendFileSync(output, '#define HUMISENSOR_ID "'+sensor._id+'"\n'); } else if(!isCustom && sensor.title == "Luftdruck") { fs.appendFileSync(output, '#define PRESSURESENSOR_ID "'+sensor._id+'"\n'); } else if(!isCustom && sensor.title == "Lautstärke") { fs.appendFileSync(output, '#define NOISESENSOR_ID "'+sensor._id+'"\n'); } else if(!isCustom && sensor.title == "Helligkeit") { fs.appendFileSync(output, '#define LIGHTSENSOR_ID "'+sensor._id+'"\n'); } else if (!isCustom && sensor.title == "Beleuchtungsstärke") { fs.appendFileSync(output, '#define LUXSENSOR_ID "'+sensor._id+'"\n'); } else if (!isCustom && sensor.title == "UV-Intensität") { fs.appendFileSync(output, '#define UVSENSOR_ID "'+sensor._id+'"\n'); } else { fs.appendFileSync(output, '#define SENSOR'+customSensorindex+'_ID "'+sensor._id+'" \/\/ '+sensor.title+'\n'); customSensorindex++; } } } else { fs.appendFileSync(output, line.toString() + "\n"); } }); } /** * @api {get} /boxes/:boxId/script Download the Arduino script for your senseBox * @apiName getScript * @apiGroup Boxes * @apiVersion 0.1.0 */ function getScript(req, res, next) { if (!req.headers["x-apikey"]) { return next(new restify.NotAuthorizedError()); } User.findOne({ apikey: req.headers["x-apikey"], boxes: { $in: [ req.params.boxId ] } }) .lean() .then(function (user) { if (user.boxes.indexOf(req.params.boxId) !== -1) { Box.findById(req.params.boxId).then(function (box) { var file = cfg.targetFolder+""+box._id+".ino"; if (!fs.existsSync(file)) { genScript(box, box.model); } return res.send(200, fs.readFileSync(file, 'utf-8')); }) .catch(function (err) { return next(new restify.NotFoundError(err.message)); }); } else { return next(new restify.NotAuthorizedError()); } }). catch(function (error) { console.log(error); return next(new restify.NotAuthorizedError()); }); } /** * @api {delete} /boxes/:boxId Delete a senseBox and its measurements * @apiName deleteBox * @apiGroup Boxes * @apiVersion 0.1.0 */ function deleteBox(req, res, next) { User.findOne({apikey:req.headers["x-apikey"]}, function (findusererror, user) { if (findusererror) { res.send(400, "ApiKey does not exist"); } if (user.boxes.indexOf(req.params.boxId) !== -1) { qrys = []; Box.findById(req.params.boxId, function (findboxerr, box) { box.sensors.forEach(function(sensor){ qrys.push(Measurement.find({ sensor_id: sensor._id }).remove()); }); qrys.push(box.remove()); qrys.push(user.remove()); }); Promise.all(qrys).then(function(thatresult){ }).then(function(){ res.send(200, "Box deleted"); }); } }); } /** * @api {get} /boxes/stats Get some statistics about the database * @apiName getStatistics * @apiGroup misc * @apiVersion 0.1.0 * @apiSuccessExample {json} [8,13, 2] // 8 boxes, 13 measurements in the database, 2 in the last minute */ function getStatistics(req, res, next){ var qrys = [ Box.count({}), Measurement.count({}), Measurement.count({ createdAt: { "$gt": new Date(Date.now() - 60000), "$lt": new Date() } }) ]; Promise.all(qrys).then(function(results){ res.send(200, results); }); } // Send box script to user via email function sendWelcomeMail(user, box) { var templatePath = './templates/registration.html'; var templateContent = fs.readFileSync(templatePath, encoding = 'utf8'); var template = _.template(templateContent); var compiled = template({ 'user': user, 'box': box }); var transporter = nodemailer.createTransport(smtpTransport({ host: cfg.email_host, port: cfg.email_port, secure: cfg.email_secure, auth: { user: cfg.email_user, pass: cfg.email_pass } })); transporter.use('compile', htmlToText()); transporter.sendMail({ from: { name: cfg.email_fromName, address: cfg.email_fromEmail }, replyTo: { name: cfg.email_fromName, address: cfg.email_replyTo }, to: { name: user.firstname+" "+user.lastname, address: user.email }, subject: cfg.email_subject, template: 'registration', html: compiled, attachments: [ { filename: "sensebox.ino", path: cfg.targetFolder + box._id + ".ino" } ] }, function(err, info){ if(err){ log.error("Email error"); log.error(err); } if(info){ log.debug("Email sent successfully"); } }); } // Send Yeah Mail to senseBox Team function sendYeahMail(user, box) { var templatePath = './templates/yeah.html'; var templateContent = fs.readFileSync(templatePath, encoding = 'utf8'); var template = _.template(templateContent); var compiled = template({ 'user': user, 'box': box }); var transporter = nodemailer.createTransport(smtpTransport({ host: cfg.email_host, port: cfg.email_port, secure: cfg.email_secure, auth: { user: cfg.email_user, pass: cfg.email_pass } })); transporter.use('compile', htmlToText()); transporter.sendMail({ from: { name: cfg.email_fromName, address: cfg.email_fromEmail }, replyTo: { name: cfg.email_fromName, address: cfg.email_replyTo }, to: { name: user.firstname+" "+user.lastname, address: "[email protected]" }, subject: cfg.email_subject, template: 'yeah', html: compiled }, function(err, info){ if(err){ log.error("Email error"); log.error(err); } if(info){ log.debug("Email sent successfully"); } }); } function _postToSlack (text) { if (cfg.slack_url) { request.post({ url: cfg.slack_url, json: { text: text }}); } } function isEmptyObject(obj) { return !Object.keys(obj).length; } server.listen(cfg.port, function () { console.log('%s listening at %s', server.name, server.url); }); server.on('uncaughtException', function (req, res, route, err) { _postToSlack("Error in API (" + route.spec.method + " " + route.spec.path + ", " + req.href() + "): " + err); log.error('Uncaught error', err); console.log(err.stack); return res.send(500, "An error occured"); });
add moderate batchSize to cursor
app.js
add moderate batchSize to cursor
<ide><path>pp.js <ide> Measurement.find(qry,{"createdAt":1, "value":1, "_id": 0}) // do not send _id column <ide> .limit(queryLimit) <ide> .lean() <del> .cursor() <add> .cursor({ batchSize: 500 }) <ide> .pipe(transformer) <ide> .pipe(stringifier) <ide> .pipe(res); <ide> Measurement.find(qry, {"createdAt":1, "value":1, "_id": 0}) // do not send _id column <ide> .limit(queryLimit) <ide> .lean() <del> .cursor() <add> .cursor({ batchSize: 500 }) <ide> .eachAsync((doc) => { <ide> returnlength = 1; <ide> doc.__v = undefined; <ide> } <ide> }, {"createdAt":1, "value":1, "_id": 0, "sensor_id":1}) <ide> .lean() <del> .cursor() <add> .cursor({ batchSize: 500 }) <ide> .pipe(transformer) <ide> .pipe(stringifier) <ide> .pipe(res)
Java
apache-2.0
6ecb27f3a13fef9aae7e83b1370729a5ad86992c
0
michael-rapp/AndroidMaterialPreferences
/* * Copyright 2014 - 2019 Michael Rapp * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package de.mrapp.android.preference; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Typeface; import android.os.Build; import android.util.AttributeSet; import androidx.annotation.ArrayRes; import androidx.annotation.AttrRes; import androidx.annotation.CallSuper; import androidx.annotation.ColorInt; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StyleRes; import de.mrapp.android.dialog.ScrollableArea; import de.mrapp.android.dialog.builder.AbstractButtonBarDialogBuilder; import de.mrapp.android.dialog.builder.AbstractListDialogBuilder; import de.mrapp.util.Condition; /** * An abstract base class for all preferences, which provide a list of selectable items. * * @author Michael Rapp * @since 1.7.0 */ public abstract class AbstractListPreference extends DialogPreference { /** * The color of the items of the preference's dialog. */ private int dialogItemColor; /** * The typeface of the items of the preference's dialog. */ private Typeface dialogItemTypeface; /** * An array, which contains the entries, which are shown in the list. */ private CharSequence[] entries; /** * An array, which contains the values, which correspond to the entries, which are shown in the * list. */ private CharSequence[] entryValues; /** * Initializes the list preference. * * @param attributeSet * The attribute set, which should be used to initialize the list preferences, as an * instance of the type {@link AttributeSet} or null, if no attributes should be * obtained * @param defaultStyle * The default style to apply to this preference. If 0, no style will be applied (beyond * what is included in the theme). This may either be an attribute resource, whose value * will be retrieved from the current theme, or an explicit style resource * @param defaultStyleResource * A resource identifier of a style resource that supplies default values for the * preference, used only if the default style is 0 or can not be found in the theme. Can * be 0 to not look for defaults */ private void initialize(@Nullable final AttributeSet attributeSet, @AttrRes final int defaultStyle, @StyleRes final int defaultStyleResource) { entries = new CharSequence[0]; entryValues = new CharSequence[0]; obtainStyledAttributes(attributeSet, defaultStyle, defaultStyleResource); } /** * Obtains all attributes from a specific attribute set. * * @param attributeSet * The attribute set, the attributes should be obtained from, as an instance of the type * {@link AttributeSet} or null, if no attributes should be obtained * @param defaultStyle * The default style to apply to this preference. If 0, no style will be applied (beyond * what is included in the theme). This may either be an attribute resource, whose value * will be retrieved from the current theme, or an explicit style resource * @param defaultStyleResource * A resource identifier of a style resource that supplies default values for the * preference, used only if the default style is 0 or can not be found in the theme. Can * be 0 to not look for defaults */ private void obtainStyledAttributes(@Nullable final AttributeSet attributeSet, @AttrRes final int defaultStyle, @StyleRes final int defaultStyleResource) { TypedArray typedArray = getContext() .obtainStyledAttributes(attributeSet, R.styleable.AbstractListPreference, defaultStyle, defaultStyleResource); try { obtainDialogItemColor(typedArray); obtainEntries(typedArray); obtainEntryValues(typedArray); obtainDialogScrollableArea(typedArray); } finally { typedArray.recycle(); } } /** * Obtains the item color of the preference's dialog from a specific typed array. * * @param typedArray * The typed array, the item color should be obtained from, as an instance of the class * {@link TypedArray}. The typed array may not be null */ private void obtainDialogItemColor(@NonNull final TypedArray typedArray) { setDialogItemColor( typedArray.getColor(R.styleable.AbstractListPreference_dialogItemColor, -1)); } /** * Obtains the the entries of the list preference from a specific typed array. * * @param typedArray * The typed array, the entries should be obtained from, as an instance of the class * {@link TypedArray}. The typed array may not be null */ private void obtainEntries(@NonNull final TypedArray typedArray) { CharSequence[] obtainedEntries = typedArray.getTextArray(R.styleable.AbstractListPreference_android_entries); if (obtainedEntries != null) { setEntries(obtainedEntries); } } /** * Obtains the the values, which correspond to the entries of the list preference from a * specific typed array. * * @param typedArray * The typed array, the entry values should be obtained from, as an instance of the * class {@link TypedArray}. The typed array may not be null */ private void obtainEntryValues(@NonNull final TypedArray typedArray) { CharSequence[] obtainedEntryValues = typedArray.getTextArray(R.styleable.AbstractListPreference_android_entryValues); if (obtainedEntryValues != null) { setEntryValues(obtainedEntryValues); } } /** * Obtains the scrollable area of the preference's dialog from a specific typed array. * * @param typedArray * The typed array, the scrollable area should be obtained from, as an instance of the * class {@link TypedArray}. The typed array may not be null */ private void obtainDialogScrollableArea(@NonNull final TypedArray typedArray) { int topIndex = typedArray.getInt(R.styleable.DialogPreference_dialogScrollableAreaTop, -1); ScrollableArea.Area top = null; ScrollableArea.Area bottom = null; if (topIndex != -1) { top = ScrollableArea.Area.fromIndex(topIndex); int bottomIndex = typedArray.getInt(R.styleable.DialogPreference_dialogScrollableAreaBottom, -1); if (bottomIndex != -1) { bottom = ScrollableArea.Area.fromIndex(bottomIndex); } } setDialogScrollableArea(top, bottom != null ? bottom : top); } /** * Return the index of the entry, a specific value corresponds to. * * @param value * The value of the entry, whose index should be returned, as an instance of the type * {@link CharSequence} * @return The index of the entry, the given value corresponds to, as an {@link Integer} value * or -1 if there is no such entry */ protected final int indexOf(@Nullable final CharSequence value) { if (value != null && entryValues != null) { for (int i = entryValues.length - 1; i >= 0; i--) { CharSequence entryValue = entryValues[i]; if ((entryValue == value) || (entryValue != null && entryValue.equals(value))) { return i; } } } return -1; } /** * Creates a new preference, which provides a list of selectable items. * * @param context * The context, which should be used by the preference, as an instance of the class * {@link Context}. The context may not be null */ public AbstractListPreference(@NonNull final Context context) { this(context, null); } /** * Creates a new preference, which provides a list of selectable items. * * @param context * The context, which should be used by the preference, as an instance of the class * {@link Context}. The context may not be null * @param attributeSet * The attributes of the XML tag that is inflating the preference, as an instance of the * type {@link AttributeSet} or null, if no attributes are available */ public AbstractListPreference(@NonNull final Context context, @Nullable final AttributeSet attributeSet) { this(context, attributeSet, 0); } /** * Creates a new preference, which provides a list of selectable items. * * @param context * The context, which should be used by the preference, as an instance of the class * {@link Context}. The context may not be null * @param attributeSet * The attributes of the XML tag that is inflating the preference, as an instance of the * type {@link AttributeSet} or null, if no attributes are available * @param defaultStyle * The default style to apply to this preference. If 0, no style will be applied (beyond * what is included in the theme). This may either be an attribute resource, whose value * will be retrieved from the current theme, or an explicit style resource */ public AbstractListPreference(@NonNull final Context context, @Nullable final AttributeSet attributeSet, @AttrRes final int defaultStyle) { super(context, attributeSet, defaultStyle); initialize(attributeSet, defaultStyle, 0); } /** * Creates a new preference, which provides a list of selectable items. * * @param context * The context, which should be used by the preference, as an instance of the class * {@link Context}. The context may not be null * @param attributeSet * The attributes of the XML tag that is inflating the preference, as an instance of the * type {@link AttributeSet} or null, if no attributes are available * @param defaultStyle * The default style to apply to this preference. If 0, no style will be applied (beyond * what is included in the theme). This may either be an attribute resource, whose value * will be retrieved from the current theme, or an explicit style resource * @param defaultStyleResource * A resource identifier of a style resource that supplies default values for the * preference, used only if the default style is 0 or can not be found in the theme. Can * be 0 to not look for defaults */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) public AbstractListPreference(@NonNull final Context context, @Nullable final AttributeSet attributeSet, @AttrRes final int defaultStyle, @StyleRes final int defaultStyleResource) { super(context, attributeSet, defaultStyle, defaultStyleResource); initialize(attributeSet, defaultStyle, defaultStyleResource); } /** * Returns the color of the items of the preference's dialog. * * @return The color of the items as an {@link Integer} value or -1, if no custom item color is * set */ public final int getDialogItemColor() { return dialogItemColor; } /** * Sets the color of the items of the preference's dialog. * * @param color * The color, which should be set, as an {@link Integer} value or -1, if no custom item * color should be set */ public final void setDialogItemColor(@ColorInt final int color) { this.dialogItemColor = color; } /** * Returns the typeface of the items of the preference's dialog. * * @return The typeface of the items of the preference's dialog as an instance of the class * {@link Typeface} or null, if the default typeface is used */ @Nullable public final Typeface getDialogItemTypeface() { return dialogItemTypeface; } /** * Sets the typeface of the items of the preference's dialog. * * @param typeface * The typeface, which should be set, as an instance of the class {@link Typeface} or * null, if the default typeface should be used */ public final void setDialogItemTypeface(@Nullable final Typeface typeface) { this.dialogItemTypeface = typeface; } /** * Returns the entries of the list, which is shown by the preference. * * @return The entries of the list, which is shown by the preference, as a {@link CharSequence} * array or null, if no entries have been set */ public final CharSequence[] getEntries() { return entries; } /** * Sets the entries of the list, which is shown by the preference. * * @param entries * The entries, which should be set, as an {@link CharSequence} array. The entries may * not be null */ public final void setEntries(@NonNull final CharSequence[] entries) { Condition.INSTANCE.ensureNotNull(entries, "The entries may not be null"); this.entries = entries; } /** * Sets the entries of the list, which is shown by the preference. * * @param resourceId * The resource id of the entries, which should be set, as an {@link Integer} value. The * resource id must correspond to a valid array resource */ public final void setEntries(@ArrayRes final int resourceId) { setEntries(getContext().getResources().getTextArray(resourceId)); } /** * Sets the values, which correspond to the entries of the list, which is shown by the * preference. * * @param entryValues * The values, which should be set, as a {@link CharSequence} array. The values may not * be null and the array's length must be equal to the number of list items */ public final void setEntryValues(@NonNull final CharSequence[] entryValues) { Condition.INSTANCE.ensureNotNull(entryValues, "The entry values may not be null"); this.entryValues = entryValues; } /** * Returns the values, which correspond to the entries of the list, which is shown by the * preference. * * @return The values, which correspond to the entries of the list, which is shown by the * preference, as a {@link CharSequence} array */ public final CharSequence[] getEntryValues() { return entryValues; } /** * Sets the values, which correspond to the entries of the list, which is shown by the * preference. * * @param resourceId * The resource id of the values, which should be set, as an {@link Integer} value. The * resource id must correspond to a valid array resource. The array's length must be * equal to the number of list items */ public final void setEntryValues(@ArrayRes final int resourceId) { setEntryValues(getContext().getResources().getTextArray(resourceId)); } @CallSuper @Override protected void onPrepareDialog( @NonNull final AbstractButtonBarDialogBuilder<?, ?> dialogBuilder) { AbstractListDialogBuilder<?, ?> listDialogBuilder = (AbstractListDialogBuilder<?, ?>) dialogBuilder; if (getDialogItemColor() != -1) { listDialogBuilder.setItemColor(getDialogItemColor()); } if (getDialogItemTypeface() != null) { listDialogBuilder.setItemTypeface(getDialogItemTypeface()); } } }
library/src/main/java/de/mrapp/android/preference/AbstractListPreference.java
/* * Copyright 2014 - 2019 Michael Rapp * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package de.mrapp.android.preference; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Typeface; import android.os.Build; import android.util.AttributeSet; import androidx.annotation.ArrayRes; import androidx.annotation.AttrRes; import androidx.annotation.CallSuper; import androidx.annotation.ColorInt; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.StyleRes; import de.mrapp.android.dialog.ScrollableArea; import de.mrapp.android.dialog.builder.AbstractButtonBarDialogBuilder; import de.mrapp.android.dialog.builder.AbstractListDialogBuilder; import de.mrapp.util.Condition; /** * An abstract base class for all preferences, which provide a list of selectable items. * * @author Michael Rapp * @since 1.7.0 */ public abstract class AbstractListPreference extends DialogPreference { /** * The color of the items of the preference's dialog. */ private int dialogItemColor; /** * The typeface of the items of the preference's dialog. */ private Typeface dialogItemTypeface; /** * An array, which contains the entries, which are shown in the list. */ private CharSequence[] entries; /** * An array, which contains the values, which correspond to the entries, which are shown in the * list. */ private CharSequence[] entryValues; /** * Initializes the list preference. * * @param attributeSet * The attribute set, which should be used to initialize the list preferences, as an * instance of the type {@link AttributeSet} or null, if no attributes should be * obtained * @param defaultStyle * The default style to apply to this preference. If 0, no style will be applied (beyond * what is included in the theme). This may either be an attribute resource, whose value * will be retrieved from the current theme, or an explicit style resource * @param defaultStyleResource * A resource identifier of a style resource that supplies default values for the * preference, used only if the default style is 0 or can not be found in the theme. Can * be 0 to not look for defaults */ private void initialize(@Nullable final AttributeSet attributeSet, @AttrRes final int defaultStyle, @StyleRes final int defaultStyleResource) { entries = new CharSequence[0]; entryValues = new CharSequence[0]; obtainStyledAttributes(attributeSet, defaultStyle, defaultStyleResource); } /** * Obtains all attributes from a specific attribute set. * * @param attributeSet * The attribute set, the attributes should be obtained from, as an instance of the type * {@link AttributeSet} or null, if no attributes should be obtained * @param defaultStyle * The default style to apply to this preference. If 0, no style will be applied (beyond * what is included in the theme). This may either be an attribute resource, whose value * will be retrieved from the current theme, or an explicit style resource * @param defaultStyleResource * A resource identifier of a style resource that supplies default values for the * preference, used only if the default style is 0 or can not be found in the theme. Can * be 0 to not look for defaults */ private void obtainStyledAttributes(@Nullable final AttributeSet attributeSet, @AttrRes final int defaultStyle, @StyleRes final int defaultStyleResource) { TypedArray typedArray = getContext() .obtainStyledAttributes(attributeSet, R.styleable.AbstractListPreference, defaultStyle, defaultStyleResource); try { obtainDialogItemColor(typedArray); obtainEntries(typedArray); obtainEntryValues(typedArray); obtainDialogScrollableArea(typedArray); } finally { typedArray.recycle(); } } /** * Obtains the item color of the preference's dialog from a specific typed array. * * @param typedArray * The typed array, the item color should be obtained from, as an instance of the class * {@link TypedArray}. The typed array may not be null */ private void obtainDialogItemColor(@NonNull final TypedArray typedArray) { setDialogItemColor( typedArray.getColor(R.styleable.AbstractListPreference_dialogItemColor, -1)); } /** * Obtains the the entries of the list preference from a specific typed array. * * @param typedArray * The typed array, the entries should be obtained from, as an instance of the class * {@link TypedArray}. The typed array may not be null */ private void obtainEntries(@NonNull final TypedArray typedArray) { CharSequence[] obtainedEntries = typedArray.getTextArray(R.styleable.AbstractListPreference_android_entries); if (obtainedEntries != null) { setEntries(obtainedEntries); } } /** * Obtains the the values, which correspond to the entries of the list preference from a * specific typed array. * * @param typedArray * The typed array, the entry values should be obtained from, as an instance of the * class {@link TypedArray}. The typed array may not be null */ private void obtainEntryValues(@NonNull final TypedArray typedArray) { CharSequence[] obtainedEntryValues = typedArray.getTextArray(R.styleable.AbstractListPreference_android_entryValues); if (obtainedEntryValues != null) { setEntryValues(obtainedEntryValues); } } /** * Obtains the scrollable area of the preference's dialog from a specific typed array. * * @param typedArray * The typed array, the scrollable area should be obtained from, as an instance of the * class {@link TypedArray}. The typed array may not be null */ private void obtainDialogScrollableArea(@NonNull final TypedArray typedArray) { int topIndex = typedArray.getInt(R.styleable.DialogPreference_dialogScrollableAreaTop, -1); ScrollableArea.Area top = null; ScrollableArea.Area bottom = null; if (topIndex != -1) { top = ScrollableArea.Area.fromIndex(topIndex); int bottomIndex = typedArray.getInt(R.styleable.DialogPreference_dialogScrollableAreaBottom, -1); if (bottomIndex != -1) { bottom = ScrollableArea.Area.fromIndex(bottomIndex); } } setDialogScrollableArea(top, bottom != null ? bottom : top); } /** * Return the index of the entry, a specific value corresponds to. * * @param value * The value of the entry, whose index should be returned, as an instance of the type * {@link CharSequence} * @return The index of the entry, the given value corresponds to, as an {@link Integer} value * or -1 if there is no such entry */ protected final int indexOf(@Nullable final CharSequence value) { if (value != null && getEntryValues() != null) { for (int i = getEntryValues().length - 1; i >= 0; i--) { if (getEntryValues()[i].equals(value)) { return i; } } } return -1; } /** * Creates a new preference, which provides a list of selectable items. * * @param context * The context, which should be used by the preference, as an instance of the class * {@link Context}. The context may not be null */ public AbstractListPreference(@NonNull final Context context) { this(context, null); } /** * Creates a new preference, which provides a list of selectable items. * * @param context * The context, which should be used by the preference, as an instance of the class * {@link Context}. The context may not be null * @param attributeSet * The attributes of the XML tag that is inflating the preference, as an instance of the * type {@link AttributeSet} or null, if no attributes are available */ public AbstractListPreference(@NonNull final Context context, @Nullable final AttributeSet attributeSet) { this(context, attributeSet, 0); } /** * Creates a new preference, which provides a list of selectable items. * * @param context * The context, which should be used by the preference, as an instance of the class * {@link Context}. The context may not be null * @param attributeSet * The attributes of the XML tag that is inflating the preference, as an instance of the * type {@link AttributeSet} or null, if no attributes are available * @param defaultStyle * The default style to apply to this preference. If 0, no style will be applied (beyond * what is included in the theme). This may either be an attribute resource, whose value * will be retrieved from the current theme, or an explicit style resource */ public AbstractListPreference(@NonNull final Context context, @Nullable final AttributeSet attributeSet, @AttrRes final int defaultStyle) { super(context, attributeSet, defaultStyle); initialize(attributeSet, defaultStyle, 0); } /** * Creates a new preference, which provides a list of selectable items. * * @param context * The context, which should be used by the preference, as an instance of the class * {@link Context}. The context may not be null * @param attributeSet * The attributes of the XML tag that is inflating the preference, as an instance of the * type {@link AttributeSet} or null, if no attributes are available * @param defaultStyle * The default style to apply to this preference. If 0, no style will be applied (beyond * what is included in the theme). This may either be an attribute resource, whose value * will be retrieved from the current theme, or an explicit style resource * @param defaultStyleResource * A resource identifier of a style resource that supplies default values for the * preference, used only if the default style is 0 or can not be found in the theme. Can * be 0 to not look for defaults */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) public AbstractListPreference(@NonNull final Context context, @Nullable final AttributeSet attributeSet, @AttrRes final int defaultStyle, @StyleRes final int defaultStyleResource) { super(context, attributeSet, defaultStyle, defaultStyleResource); initialize(attributeSet, defaultStyle, defaultStyleResource); } /** * Returns the color of the items of the preference's dialog. * * @return The color of the items as an {@link Integer} value or -1, if no custom item color is * set */ public final int getDialogItemColor() { return dialogItemColor; } /** * Sets the color of the items of the preference's dialog. * * @param color * The color, which should be set, as an {@link Integer} value or -1, if no custom item * color should be set */ public final void setDialogItemColor(@ColorInt final int color) { this.dialogItemColor = color; } /** * Returns the typeface of the items of the preference's dialog. * * @return The typeface of the items of the preference's dialog as an instance of the class * {@link Typeface} or null, if the default typeface is used */ @Nullable public final Typeface getDialogItemTypeface() { return dialogItemTypeface; } /** * Sets the typeface of the items of the preference's dialog. * * @param typeface * The typeface, which should be set, as an instance of the class {@link Typeface} or * null, if the default typeface should be used */ public final void setDialogItemTypeface(@Nullable final Typeface typeface) { this.dialogItemTypeface = typeface; } /** * Returns the entries of the list, which is shown by the preference. * * @return The entries of the list, which is shown by the preference, as a {@link CharSequence} * array or null, if no entries have been set */ public final CharSequence[] getEntries() { return entries; } /** * Sets the entries of the list, which is shown by the preference. * * @param entries * The entries, which should be set, as an {@link CharSequence} array. The entries may * not be null */ public final void setEntries(@NonNull final CharSequence[] entries) { Condition.INSTANCE.ensureNotNull(entries, "The entries may not be null"); this.entries = entries; } /** * Sets the entries of the list, which is shown by the preference. * * @param resourceId * The resource id of the entries, which should be set, as an {@link Integer} value. The * resource id must correspond to a valid array resource */ public final void setEntries(@ArrayRes final int resourceId) { setEntries(getContext().getResources().getTextArray(resourceId)); } /** * Returns the values, which correspond to the entries of the list, which is shown by the * preference. * * @return The values, which correspond to the entries of the list, which is shown by the * preference, as a {@link CharSequence} array */ public final CharSequence[] getEntryValues() { return entryValues; } /** * Sets the values, which correspond to the entries of the list, which is shown by the * preference. * * @param entryValues * The values, which should be set, as a {@link CharSequence} array. The values may not * be null and the array's length must be equal to the number of list items */ public final void setEntryValues(@NonNull final CharSequence[] entryValues) { Condition.INSTANCE.ensureNotNull(entryValues, "The entry values may not be null"); this.entryValues = entryValues; } /** * Sets the values, which correspond to the entries of the list, which is shown by the * preference. * * @param resourceId * The resource id of the values, which should be set, as an {@link Integer} value. The * resource id must correspond to a valid array resource. The array's length must be * equal to the number of list items */ public final void setEntryValues(@ArrayRes final int resourceId) { setEntryValues(getContext().getResources().getTextArray(resourceId)); } @CallSuper @Override protected void onPrepareDialog( @NonNull final AbstractButtonBarDialogBuilder<?, ?> dialogBuilder) { AbstractListDialogBuilder<?, ?> listDialogBuilder = (AbstractListDialogBuilder<?, ?>) dialogBuilder; if (getDialogItemColor() != -1) { listDialogBuilder.setItemColor(getDialogItemColor()); } if (getDialogItemTypeface() != null) { listDialogBuilder.setItemTypeface(getDialogItemTypeface()); } } }
Fix possible NPE.
library/src/main/java/de/mrapp/android/preference/AbstractListPreference.java
Fix possible NPE.
<ide><path>ibrary/src/main/java/de/mrapp/android/preference/AbstractListPreference.java <ide> * or -1 if there is no such entry <ide> */ <ide> protected final int indexOf(@Nullable final CharSequence value) { <del> if (value != null && getEntryValues() != null) { <del> for (int i = getEntryValues().length - 1; i >= 0; i--) { <del> if (getEntryValues()[i].equals(value)) { <add> if (value != null && entryValues != null) { <add> for (int i = entryValues.length - 1; i >= 0; i--) { <add> CharSequence entryValue = entryValues[i]; <add> <add> if ((entryValue == value) || (entryValue != null && entryValue.equals(value))) { <ide> return i; <ide> } <ide> } <ide> } <ide> <ide> /** <del> * Returns the values, which correspond to the entries of the list, which is shown by the <del> * preference. <del> * <del> * @return The values, which correspond to the entries of the list, which is shown by the <del> * preference, as a {@link CharSequence} array <del> */ <del> public final CharSequence[] getEntryValues() { <del> return entryValues; <del> } <del> <del> /** <ide> * Sets the values, which correspond to the entries of the list, which is shown by the <ide> * preference. <ide> * <ide> public final void setEntryValues(@NonNull final CharSequence[] entryValues) { <ide> Condition.INSTANCE.ensureNotNull(entryValues, "The entry values may not be null"); <ide> this.entryValues = entryValues; <add> } <add> <add> /** <add> * Returns the values, which correspond to the entries of the list, which is shown by the <add> * preference. <add> * <add> * @return The values, which correspond to the entries of the list, which is shown by the <add> * preference, as a {@link CharSequence} array <add> */ <add> public final CharSequence[] getEntryValues() { <add> return entryValues; <ide> } <ide> <ide> /**
Java
apache-2.0
75a423a3581bf8c68a63531f9a5432f9d33f5b17
0
efsavage/ajah
/* * Copyright 2011 Eric F. Savage, [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ajah.html.element; import java.io.IOException; import java.io.Writer; import lombok.Data; import lombok.EqualsAndHashCode; import com.ajah.html.dtd.InputType; import com.ajah.util.StringUtils; /** * Basic Input class. May become obsolete as other Input classes are implmented. * * @author <a href="http://efsavage.com">Eric F. Savage</a>, <a * href="mailto:[email protected]">[email protected]</a>. * */ @Data @EqualsAndHashCode(callSuper = false) public class InputImpl extends AbstractNestableHtmlCoreElement<InputImpl> implements Input<InputImpl> { private final String name; private Label label; private final InputType type; private String value; /** * @param name * Name attribute. * @param value * Value attribute. * @param type * Type attribute. */ public InputImpl(final String name, final String value, final InputType type) { this.id = name; this.name = name; this.value = value; this.type = type; setCssClass(type.name().toLowerCase()); } /** * Will create a {@link Label} element as a sibling. * * @param label * Text to use to create a sibling Label. * @param name * Name attribute. * @param value * Value attribute. * @param type * Type attribute. */ public InputImpl(final String label, final String name, final String value, final InputType type) { this(name, value, type); if (!StringUtils.isBlank(label)) { this.label = new Label(this, label).css(type.name().toLowerCase()); } } @Override public InputImpl getThis() { return this; } /** * Renders attributes and also the sibling Label. * * @see com.ajah.html.element.AbstractNestableHtmlCoreElement#render(java.io.Writer, * int) */ @Override public void render(final Writer out, final int depth) throws IOException { if (this.label != null) { this.label.render(out, depth); } for (int i = 0; i < depth; i++) { out.write("\t"); } out.write("<input"); writeCore(out); write(out, "name", this.name); write(out, "value", this.value); write(out, "type", this.type.name().toLowerCase()); out.write(" />"); if (depth >= 0) { out.write("\r\n"); } } }
ajah-html/src/main/java/com/ajah/html/element/InputImpl.java
/* * Copyright 2011 Eric F. Savage, [email protected] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ajah.html.element; import java.io.IOException; import java.io.Writer; import lombok.Data; import lombok.EqualsAndHashCode; import com.ajah.html.dtd.InputType; /** * Basic Input class. May become obsolete as other Input classes are implmented. * * @author <a href="http://efsavage.com">Eric F. Savage</a>, <a * href="mailto:[email protected]">[email protected]</a>. * */ @Data @EqualsAndHashCode(callSuper = false) public class InputImpl extends AbstractNestableHtmlCoreElement<InputImpl> implements Input<InputImpl> { private final String name; private Label label; private final InputType type; private String value; /** * @param name * Name attribute. * @param value * Value attribute. * @param type * Type attribute. */ public InputImpl(final String name, final String value, final InputType type) { this.id = name; this.name = name; this.value = value; this.type = type; setCssClass(type.name().toLowerCase()); } /** * Will create a {@link Label} element as a sibling. * * @param label * Text to use to create a sibling Label. * @param name * Name attribute. * @param value * Value attribute. * @param type * Type attribute. */ public InputImpl(final String label, final String name, final String value, final InputType type) { this(name, value, type); this.label = new Label(this, label).css(type.name().toLowerCase()); } @Override public InputImpl getThis() { return this; } /** * Renders attributes and also the sibling Label. * * @see com.ajah.html.element.AbstractNestableHtmlCoreElement#render(java.io.Writer, * int) */ @Override public void render(final Writer out, final int depth) throws IOException { if (this.label != null) { this.label.render(out, depth); } for (int i = 0; i < depth; i++) { out.write("\t"); } out.write("<input"); writeCore(out); write(out, "name", this.name); write(out, "value", this.value); write(out, "type", this.type.name().toLowerCase()); out.write(" />"); if (depth >= 0) { out.write("\r\n"); } } }
Skip the label when blank
ajah-html/src/main/java/com/ajah/html/element/InputImpl.java
Skip the label when blank
<ide><path>jah-html/src/main/java/com/ajah/html/element/InputImpl.java <ide> import lombok.EqualsAndHashCode; <ide> <ide> import com.ajah.html.dtd.InputType; <add>import com.ajah.util.StringUtils; <ide> <ide> /** <ide> * Basic Input class. May become obsolete as other Input classes are implmented. <ide> */ <ide> public InputImpl(final String label, final String name, final String value, final InputType type) { <ide> this(name, value, type); <del> this.label = new Label(this, label).css(type.name().toLowerCase()); <add> if (!StringUtils.isBlank(label)) { <add> this.label = new Label(this, label).css(type.name().toLowerCase()); <add> } <ide> } <ide> <ide> @Override
JavaScript
mit
f3b8c44ebb8fcfed4125bbd490ee8f1473b23527
0
formio/formio.js,formio/formio.js,formio/formio.js
/* global ace, Quill */ import TextFieldComponent from '../textfield/TextField'; import Formio from '../../Formio'; import _ from 'lodash'; import { uniqueName } from '../../utils/utils'; export default class TextAreaComponent extends TextFieldComponent { static schema(...extend) { return TextFieldComponent.schema({ type: 'textarea', label: 'Text Area', key: 'textArea', rows: 3, wysiwyg: false, editor: '', inputFormat: 'html', validate: { minWords: '', maxWords: '' } }, ...extend); } static get builderInfo() { return { title: 'Text Area', group: 'basic', icon: 'font', documentation: 'http://help.form.io/userguide/#textarea', weight: 20, schema: TextAreaComponent.schema() }; } init() { super.init(); // Never submit on enter for text areas. this.options.submitOnEnter = false; } get defaultSchema() { return TextAreaComponent.schema(); } get inputInfo() { const info = super.inputInfo; info.type = this.component.wysiwyg ? 'div' : 'textarea'; if (this.component.rows) { info.attr.rows = this.component.rows; } return info; } get wysiwygDefault() { return { theme: 'snow', placeholder: this.t(this.component.placeholder), modules: { toolbar: [ [{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown [{ 'header': [1, 2, 3, 4, 5, 6, false] }], [{ 'font': [] }], ['bold', 'italic', 'underline', 'strike', { 'script': 'sub' }, { 'script': 'super' }, 'clean'], [{ 'color': [] }, { 'background': [] }], [{ 'list': 'ordered' }, { 'list': 'bullet' }, { 'indent': '-1' }, { 'indent': '+1' }, { 'align': [] }], ['blockquote', 'code-block'], ['link', 'image', 'video', 'formula', 'source'] ] } }; } setupValueElement(element) { let value = this.getValue(); value = this.isEmpty(value) ? this.defaultViewOnlyValue : this.getView(value); if (this.component.wysiwyg) { value = this.interpolate(value); } if (element) { this.setContent(element, value); } } acePlaceholder() { if (!this.component.placeholder || !this.editor) { return; } const shouldShow = !this.editor.session.getValue().length; let node = this.editor.renderer.emptyMessageNode; if (!shouldShow && node) { this.editor.renderer.scroller.removeChild(this.editor.renderer.emptyMessageNode); this.editor.renderer.emptyMessageNode = null; } else if (shouldShow && !node) { node = this.editor.renderer.emptyMessageNode = this.ce('div'); node.textContent = this.t(this.component.placeholder); node.className = 'ace_invisible ace_emptyMessage'; node.style.padding = '0 9px'; this.editor.renderer.scroller.appendChild(node); } } renderElement(value, index) { const info = this.inputInfo; info.attr = info.attr || {}; info.content = value; if (this.options.readOnly || this.disabled) { return this.renderTemplate('well', { children: value, nestedKey: this.key, value }); } // Editors work better on divs. if (this.component.editor || this.component.wysiwyg) { return '<div ref="input"></div>'; } return this.renderTemplate('input', { input: info, value, index }); } attachElement(element, index) { if (this.options.readOnly) { return element; } // Normalize the configurations. if (this.component.wysiwyg && this.component.wysiwyg.toolbarGroups) { console.warn('The WYSIWYG settings are configured for CKEditor. For this renderer, you will need to use configurations for the Quill Editor. See https://quilljs.com/docs/configuration for more information.'); this.component.wysiwyg = this.wysiwygDefault; } if (this.component.wysiwyg && !this.component.editor) { this.component.editor = 'ckeditor'; } const settings = _.isEmpty(this.component.wysiwyg) ? this.wysiwygDefault : this.component.wysiwyg; const mode = this.component.as || 'javascript'; // Attempt to add a wysiwyg editor. In order to add one, it must be included on the global scope. switch (this.component.editor) { case 'ace': this.editorReady = Formio.requireLibrary('ace', 'ace', 'https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.1/ace.js', true) .then((editor) => { this.editor = editor.edit(element); this.editor.setOptions({ maxLines: 12, minLines: 12 }); this.editor.on('change', () => { const newValue = this.getConvertedValue(this.editor.getValue()); // Do not bother to update if they are both empty. if (!_.isEmpty(newValue) || !_.isEmpty(this.dataValue)) { this.updateValue(null, newValue, index); } }); this.editor.getSession().setTabSize(2); this.editor.getSession().setMode(`ace/mode/${mode}`); this.editor.on('input', () => this.acePlaceholder()); setTimeout(() => this.acePlaceholder(), 100); this.editor.setValue(this.setConvertedValue(this.dataValue)); return this.editor; }); break; case 'quill': Formio.requireLibrary(`quill-css-${settings.theme}`, 'Quill', [ { type: 'styles', src: `https://cdn.quilljs.com/1.3.6/quill.${settings.theme}.css` } ], true); this.editorReady = Formio.requireLibrary('quill', 'Quill', 'https://cdn.quilljs.com/1.3.6/quill.min.js', true) .then((Editor) => { this.editor = new Editor(element, settings); this.editor.root.spellcheck = this.component.spellcheck; if (this.component.isUploadEnabled) { this.editor.getModule('toolbar').addHandler('image', () => this.imageHandler()); } /** This block of code adds the [source] capabilities. See https://codepen.io/anon/pen/ZyEjrQ **/ // const txtArea = document.createElement('textarea'); // txtArea.setAttribute('class', 'quill-source-code'); // this.editor.addContainer('ql-custom').appendChild(txtArea); // const qlSource = element.parentNode.querySelector('.ql-source'); // if (qlSource) { // this.addEventListener(qlSource, 'click', (event) => { // event.preventDefault(); // if (txtArea.style.display === 'inherit') { // this.editor.setContents(this.editor.clipboard.convert(txtArea.value)); // } // txtArea.style.display = (txtArea.style.display === 'none') ? 'inherit' : 'none'; // }); // } /** END CODEBLOCK **/ // Allows users to skip toolbar items when tabbing though form const elm = document.querySelectorAll('.ql-formats > button'); for (let i = 0; i < elm.length; i++) { elm[i].setAttribute('tabindex', '-1'); } if (this.options.readOnly || this.disabled) { this.editor.disable(); } this.editor.on('text-change', () => { this.updateValue(null, this.getConvertedValue(this.sanitize(this.editor.root.innerHTML))); }); this.editor.setContents(this.editor.clipboard.convert(this.setConvertedValue(this.dataValue))); return this.editor; }); break; case 'ckeditor': this.editorReady = Formio.requireLibrary('ckeditor', 'ClassicEditor', 'https://cdn.staticaly.com/gh/formio/ckeditor5-build-classic/v12.3.0-formio.1/build/ckeditor.js', true) .then((ClassicEditor) => { settings = settings || {}; settings.base64Upload = true; return ClassicEditor.create(element, settings).then(editor => { editor.model.document.on('change', () => this.updateValue(null, editor.data.get())); this.editor = editor; this.editor.data.set(this.setConvertedValue(this.dataValue)); return this.editor; }); }); break; default: this.addEventListener(element, this.inputInfo.changeEvent, () => { this.updateValue(null, null, index); }); } return element; } imageHandler() { let fileInput = this.container.querySelector('input.ql-image[type=file]'); if (fileInput == null) { fileInput = document.createElement('input'); fileInput.setAttribute('type', 'file'); fileInput.setAttribute('accept', 'image/*'); fileInput.classList.add('ql-image'); fileInput.addEventListener('change', () => { const files = fileInput.files; const range = this.editor.getSelection(true); if (!files || !files.length) { console.warn('No files selected'); return; } this.editor.enable(false); const { uploadStorage, uploadUrl, uploadOptions, uploadDir } = this.component; this.root.formio .uploadFile( uploadStorage, files[0], uniqueName(files[0].name), uploadDir || '', //should pass empty string if undefined null, uploadUrl, uploadOptions ) .then((result) => { return this.root.formio.downloadFile(result); }) .then(result => { this.editor.enable(true); const Delta = Quill.import('delta'); this.editor.updateContents(new Delta() .retain(range.index) .delete(range.length) .insert({ image: result.url }) , Quill.sources.USER); fileInput.value = ''; }).catch(error => { console.warn('Quill image upload failed'); console.warn(error); this.editor.enable(true); }); }); this.container.appendChild(fileInput); } fileInput.click(); } get isPlain() { return (!this.component.wysiwyg && !this.component.editor); } get htmlView() { return this.options.readOnly && this.component.wysiwyg; } setConvertedValue(value) { if (this.component.as && this.component.as === 'json' && !_.isNil(value)) { try { value = JSON.stringify(value, null, 2); } catch (err) { console.warn(err); } } return value; } removeBlanks(value) { if (!value) { return value; } const removeBlanks = function(input) { if (typeof input !== 'string') { return input; } return input.replace(/<p>&nbsp;<\/p>/g, '').replace(/<p><br><\/p>/g, ''); }; if (Array.isArray(value)) { value.forEach((input, index) => { value[index] = removeBlanks(input); }); } else { value = removeBlanks(value); } return value; } hasChanged(before, after) { return super.hasChanged(this.removeBlanks(before), this.removeBlanks(after)); } isEmpty(value) { return super.isEmpty(this.removeBlanks(value)); } get defaultValue() { let defaultValue = super.defaultValue; if (this.component.editor === 'quill' && !defaultValue) { defaultValue = '<p><br></p>'; } return defaultValue; } setValue(value, flags) { const shouldSetValue = !_.isEqual(value, this.getValue()); value = value || ''; if (this.isPlain) { return super.setValue(this.setConvertedValue(value), flags); } if (!this.editorReady) { return false; } // Set the value when the editor is ready. const newValue = (value === undefined || value === null) ? this.getValue() : value; const changed = (newValue !== undefined) ? this.hasChanged(newValue, this.dataValue) : false; this.dataValue = newValue; if (this.htmlView) { // For HTML view, just view the contents. if (this.input) { this.setContent(this.input, this.interpolate(value)); } } else if (this.editorReady) { this.editorReady.then((editor) => { switch (this.component.editor) { case 'ace': if (shouldSetValue) { editor.setValue(this.setConvertedValue(value)); } break; case 'quill': if (shouldSetValue) { editor.setContents(editor.clipboard.convert(this.setConvertedValue(value))); } break; case 'ckeditor': if (shouldSetValue) { editor.data.set(this.setConvertedValue(value)); } break; } }); } // Update on change. this.updateOnChange(flags, changed); // Return if the value has changed. return changed; } getConvertedValue(value) { if (this.component.as && this.component.as === 'json' && value) { try { value = JSON.parse(value); } catch (err) { // console.warn(err); } } return value; } getValue() { if (this.viewOnly || this.htmlView || this.options.readOnly) { return this.dataValue; } if (this.isPlain) { return this.getConvertedValue(super.getValue()); } if (this.editor) { return this.dataValue; } return this.component.multiple ? [] : ''; } }
src/components/textarea/TextArea.js
/* global ace, Quill */ import TextFieldComponent from '../textfield/TextField'; import Formio from '../../Formio'; import _ from 'lodash'; import { uniqueName } from '../../utils/utils'; export default class TextAreaComponent extends TextFieldComponent { static schema(...extend) { return TextFieldComponent.schema({ type: 'textarea', label: 'Text Area', key: 'textArea', rows: 3, wysiwyg: false, editor: '', inputFormat: 'html', validate: { minWords: '', maxWords: '' } }, ...extend); } static get builderInfo() { return { title: 'Text Area', group: 'basic', icon: 'font', documentation: 'http://help.form.io/userguide/#textarea', weight: 20, schema: TextAreaComponent.schema() }; } init() { super.init(); // Never submit on enter for text areas. this.options.submitOnEnter = false; } get defaultSchema() { return TextAreaComponent.schema(); } get inputInfo() { const info = super.inputInfo; info.type = this.component.wysiwyg ? 'div' : 'textarea'; if (this.component.rows) { info.attr.rows = this.component.rows; } return info; } get wysiwygDefault() { return { theme: 'snow', placeholder: this.t(this.component.placeholder), modules: { toolbar: [ [{ 'size': ['small', false, 'large', 'huge'] }], // custom dropdown [{ 'header': [1, 2, 3, 4, 5, 6, false] }], [{ 'font': [] }], ['bold', 'italic', 'underline', 'strike', { 'script': 'sub' }, { 'script': 'super' }, 'clean'], [{ 'color': [] }, { 'background': [] }], [{ 'list': 'ordered' }, { 'list': 'bullet' }, { 'indent': '-1' }, { 'indent': '+1' }, { 'align': [] }], ['blockquote', 'code-block'], ['link', 'image', 'video', 'formula', 'source'] ] } }; } setupValueElement(element) { let value = this.getValue(); value = this.isEmpty(value) ? this.defaultViewOnlyValue : this.getView(value); if (this.component.wysiwyg) { value = this.interpolate(value); } if (element) { this.setContent(element, value); } } acePlaceholder() { if (!this.component.placeholder || !this.editor) { return; } const shouldShow = !this.editor.session.getValue().length; let node = this.editor.renderer.emptyMessageNode; if (!shouldShow && node) { this.editor.renderer.scroller.removeChild(this.editor.renderer.emptyMessageNode); this.editor.renderer.emptyMessageNode = null; } else if (shouldShow && !node) { node = this.editor.renderer.emptyMessageNode = this.ce('div'); node.textContent = this.t(this.component.placeholder); node.className = 'ace_invisible ace_emptyMessage'; node.style.padding = '0 9px'; this.editor.renderer.scroller.appendChild(node); } } renderElement(value, index) { const info = this.inputInfo; info.attr = info.attr || {}; info.content = value; if (this.options.readOnly || this.disabled) { return this.renderTemplate('well', { children: value, nestedKey: this.key, value }); } // Editors work better on divs. if (this.component.editor || this.component.wysiwyg) { return '<div ref="input"></div>'; } return this.renderTemplate('input', { input: info, value, index }); } attachElement(element, index) { if (this.options.readOnly) { return element; } // Normalize the configurations. if (this.component.wysiwyg && this.component.wysiwyg.toolbarGroups) { console.warn('The WYSIWYG settings are configured for CKEditor. For this renderer, you will need to use configurations for the Quill Editor. See https://quilljs.com/docs/configuration for more information.'); this.component.wysiwyg = this.wysiwygDefault; } if (this.component.wysiwyg && !this.component.editor) { this.component.editor = 'ckeditor'; } const settings = _.isEmpty(this.component.wysiwyg) ? this.wysiwygDefault : this.component.wysiwyg; const mode = this.component.as || 'javascript'; // Attempt to add a wysiwyg editor. In order to add one, it must be included on the global scope. switch (this.component.editor) { case 'ace': this.editorReady = Formio.requireLibrary('ace', 'ace', 'https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.1/ace.js', true) .then((editor) => { this.editor = editor.edit(element); this.editor.setOptions({ maxLines: 12, minLines: 12 }); this.editor.on('change', () => { const newValue = this.getConvertedValue(this.editor.getValue()); // Do not bother to update if they are both empty. if (!_.isEmpty(newValue) || !_.isEmpty(this.dataValue)) { this.updateValue(null, newValue, index); } }); this.editor.getSession().setTabSize(2); this.editor.getSession().setMode(`ace/mode/${mode}`); this.editor.on('input', () => this.acePlaceholder()); setTimeout(() => this.acePlaceholder(), 100); this.editor.setValue(this.setConvertedValue(this.dataValue)); return this.editor; }); break; case 'quill': Formio.requireLibrary(`quill-css-${settings.theme}`, 'Quill', [ { type: 'styles', src: `https://cdn.quilljs.com/1.3.6/quill.${settings.theme}.css` } ], true); this.editorReady = Formio.requireLibrary('quill', 'Quill', 'https://cdn.quilljs.com/1.3.6/quill.min.js', true) .then((Editor) => { this.editor = new Editor(element, settings); this.editor.root.spellcheck = this.component.spellcheck; if (this.component.isUploadEnabled) { this.editor.getModule('toolbar').addHandler('image', () => this.imageHandler()); } /** This block of code adds the [source] capabilities. See https://codepen.io/anon/pen/ZyEjrQ **/ // const txtArea = document.createElement('textarea'); // txtArea.setAttribute('class', 'quill-source-code'); // this.editor.addContainer('ql-custom').appendChild(txtArea); // const qlSource = element.parentNode.querySelector('.ql-source'); // if (qlSource) { // this.addEventListener(qlSource, 'click', (event) => { // event.preventDefault(); // if (txtArea.style.display === 'inherit') { // this.editor.setContents(this.editor.clipboard.convert(txtArea.value)); // } // txtArea.style.display = (txtArea.style.display === 'none') ? 'inherit' : 'none'; // }); // } /** END CODEBLOCK **/ // Allows users to skip toolbar items when tabbing though form const elm = document.querySelectorAll('.ql-formats > button'); for (let i = 0; i < elm.length; i++) { elm[i].setAttribute('tabindex', '-1'); } if (this.options.readOnly || this.disabled) { this.editor.disable(); } this.editor.on('text-change', () => { this.updateValue(null, this.getConvertedValue(this.sanitize(this.editor.root.innerHTML))); }); this.editor.setContents(this.editor.clipboard.convert(this.setConvertedValue(this.dataValue))); return this.editor; }); break; case 'ckeditor': this.editorReady = Formio.requireLibrary('ckeditor', 'ClassicEditor', 'https://cdn.ckeditor.com/ckeditor5/11.2.0/classic/ckeditor.js', true) .then((ClassicEditor) => { return ClassicEditor.create(element, settings).then(editor => { editor.model.document.on('change', () => this.updateValue(null, editor.data.get())); this.editor = editor; this.editor.data.set(this.setConvertedValue(this.dataValue)); return this.editor; }); }); break; default: this.addEventListener(element, this.inputInfo.changeEvent, () => { this.updateValue(null, null, index); }); } return element; } imageHandler() { let fileInput = this.container.querySelector('input.ql-image[type=file]'); if (fileInput == null) { fileInput = document.createElement('input'); fileInput.setAttribute('type', 'file'); fileInput.setAttribute('accept', 'image/*'); fileInput.classList.add('ql-image'); fileInput.addEventListener('change', () => { const files = fileInput.files; const range = this.editor.getSelection(true); if (!files || !files.length) { console.warn('No files selected'); return; } this.editor.enable(false); const { uploadStorage, uploadUrl, uploadOptions, uploadDir } = this.component; this.root.formio .uploadFile( uploadStorage, files[0], uniqueName(files[0].name), uploadDir || '', //should pass empty string if undefined null, uploadUrl, uploadOptions ) .then((result) => { return this.root.formio.downloadFile(result); }) .then(result => { this.editor.enable(true); const Delta = Quill.import('delta'); this.editor.updateContents(new Delta() .retain(range.index) .delete(range.length) .insert({ image: result.url }) , Quill.sources.USER); fileInput.value = ''; }).catch(error => { console.warn('Quill image upload failed'); console.warn(error); this.editor.enable(true); }); }); this.container.appendChild(fileInput); } fileInput.click(); } get isPlain() { return (!this.component.wysiwyg && !this.component.editor); } get htmlView() { return this.options.readOnly && this.component.wysiwyg; } setConvertedValue(value) { if (this.component.as && this.component.as === 'json' && !_.isNil(value)) { try { value = JSON.stringify(value, null, 2); } catch (err) { console.warn(err); } } return value; } removeBlanks(value) { if (!value) { return value; } const removeBlanks = function(input) { if (typeof input !== 'string') { return input; } return input.replace(/<p>&nbsp;<\/p>/g, '').replace(/<p><br><\/p>/g, ''); }; if (Array.isArray(value)) { value.forEach((input, index) => { value[index] = removeBlanks(input); }); } else { value = removeBlanks(value); } return value; } hasChanged(before, after) { return super.hasChanged(this.removeBlanks(before), this.removeBlanks(after)); } isEmpty(value) { return super.isEmpty(this.removeBlanks(value)); } get defaultValue() { let defaultValue = super.defaultValue; if (this.component.editor === 'quill' && !defaultValue) { defaultValue = '<p><br></p>'; } return defaultValue; } setValue(value, flags) { const shouldSetValue = !_.isEqual(value, this.getValue()); value = value || ''; if (this.isPlain) { return super.setValue(this.setConvertedValue(value), flags); } if (!this.editorReady) { return false; } // Set the value when the editor is ready. const newValue = (value === undefined || value === null) ? this.getValue() : value; const changed = (newValue !== undefined) ? this.hasChanged(newValue, this.dataValue) : false; this.dataValue = newValue; if (this.htmlView) { // For HTML view, just view the contents. if (this.input) { this.setContent(this.input, this.interpolate(value)); } } else if (this.editorReady) { this.editorReady.then((editor) => { switch (this.component.editor) { case 'ace': if (shouldSetValue) { editor.setValue(this.setConvertedValue(value)); } break; case 'quill': if (shouldSetValue) { editor.setContents(editor.clipboard.convert(this.setConvertedValue(value))); } break; case 'ckeditor': if (shouldSetValue) { editor.data.set(this.setConvertedValue(value)); } break; } }); } // Update on change. this.updateOnChange(flags, changed); // Return if the value has changed. return changed; } getConvertedValue(value) { if (this.component.as && this.component.as === 'json' && value) { try { value = JSON.parse(value); } catch (err) { // console.warn(err); } } return value; } getValue() { if (this.viewOnly || this.htmlView || this.options.readOnly) { return this.dataValue; } if (this.isPlain) { return this.getConvertedValue(super.getValue()); } if (this.editor) { return this.dataValue; } return this.component.multiple ? [] : ''; } }
4.x - FOR-2379 - Add CKE image support
src/components/textarea/TextArea.js
4.x - FOR-2379 - Add CKE image support
<ide><path>rc/components/textarea/TextArea.js <ide> }); <ide> break; <ide> case 'ckeditor': <del> this.editorReady = Formio.requireLibrary('ckeditor', 'ClassicEditor', 'https://cdn.ckeditor.com/ckeditor5/11.2.0/classic/ckeditor.js', true) <add> this.editorReady = Formio.requireLibrary('ckeditor', 'ClassicEditor', 'https://cdn.staticaly.com/gh/formio/ckeditor5-build-classic/v12.3.0-formio.1/build/ckeditor.js', true) <ide> .then((ClassicEditor) => { <add> settings = settings || {}; <add> settings.base64Upload = true; <ide> return ClassicEditor.create(element, settings).then(editor => { <ide> editor.model.document.on('change', () => this.updateValue(null, editor.data.get())); <ide> this.editor = editor;
Java
apache-2.0
error: pathspec 'annotation-rest/src/main/java/uk/ac/ebi/quickgo/annotation/download/http/GenericHttpMessageConverter.java' did not match any file(s) known to git
fa821c98bb6ed8b008c9fb1a4adf73479467eafe
1
ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE,ebi-uniprot/QuickGOBE
package uk.ac.ebi.quickgo.annotation.download.http; import uk.ac.ebi.quickgo.annotation.model.Annotation; import uk.ac.ebi.quickgo.rest.ResponseExceptionHandler; import uk.ac.ebi.quickgo.rest.search.results.QueryResult; import java.io.IOException; import java.io.OutputStream; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.AbstractHttpMessageConverter; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotWritableException; /** * Writes a stream of {@link QueryResult}s containing {@link Annotation} instances to a response's output stream, * using the provided converter to format the output. * * @author Tony Wardell * Date: 26/04/2017 * Time: 14:49 * Created with IntelliJ IDEA. */ public class GenericHttpMessageConverter extends AbstractHttpMessageConverter<Object> { private static final Logger LOGGER = LoggerFactory.getLogger(GenericHttpMessageConverter.class); private static final int FLUSH_INTERVAL = 1000; private final Function<Annotation, List<String>> converter; private final MediaType type; public GenericHttpMessageConverter(Function<Annotation, List<String>> converter, MediaType mediaType) { super(mediaType); this.converter = converter; this.type = mediaType; } @Override protected boolean supports(Class<?> clazz) { return true; } @Override protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { return null; } @Override protected void writeInternal(Object annotationStream, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { OutputStream out = outputMessage.getBody(); dispatchWriting(annotationStream, out); } @SuppressWarnings("unchecked") private void dispatchWriting(Object object, OutputStream out) throws IOException { if (object instanceof ResponseExceptionHandler.ErrorInfo) { writeError(out, (ResponseExceptionHandler.ErrorInfo) object); } else { writeAnnotations(out, (Stream<QueryResult<Annotation>>) object); } } private void writeError(OutputStream out, ResponseExceptionHandler.ErrorInfo errorInfo) throws IOException { out.write(("URL:\n\t" + errorInfo.getUrl() + "\n").getBytes()); out.write(("Messages:\n\t" + errorInfo.getMessages().stream().collect(Collectors.joining(",\n"))).getBytes()); } private void writeAnnotations(OutputStream out, Stream<QueryResult<Annotation>> annotationStream) { AtomicInteger counter = new AtomicInteger(0); AtomicInteger batchCount = new AtomicInteger(0); try { annotationStream.forEach(annotationResult -> annotationResult.getResults() .forEach(annotation -> converter.apply(annotation) .forEach(content -> stream(out, counter, batchCount, content)))); } catch (StopStreamException e) { LOGGER.error("Client aborted streaming: closing stream.", e); annotationStream.close(); } LOGGER.info("Written " + counter.get() + type.getType() + " annotations"); } private void stream(OutputStream out, AtomicInteger counter, AtomicInteger batchCount, String content) { try { out.write((content + "\n").getBytes()); updateCountersAndFlushStreamWhenRequired(out, counter, batchCount); } catch (IOException e) { throw new StopStreamException("Could not write OutputStream whilst writing " + type.getType() + " annotation: " + content, e); } } private void updateCountersAndFlushStreamWhenRequired(OutputStream out, AtomicInteger counter, AtomicInteger batchCount) throws IOException { counter.getAndIncrement(); batchCount.getAndIncrement(); if (batchCount.get() >= FLUSH_INTERVAL) { out.flush(); LOGGER.info("Flushed " + type.getType() + " http message converter output stream after: " + counter.get() + " annotations."); batchCount.set(0); } } }
annotation-rest/src/main/java/uk/ac/ebi/quickgo/annotation/download/http/GenericHttpMessageConverter.java
Writes a stream of QueryResults containing Annotation instances to a response's output stream, using the provided converter to format the output.
annotation-rest/src/main/java/uk/ac/ebi/quickgo/annotation/download/http/GenericHttpMessageConverter.java
Writes a stream of QueryResults containing Annotation instances to a response's output stream, using the provided converter to format the output.
<ide><path>nnotation-rest/src/main/java/uk/ac/ebi/quickgo/annotation/download/http/GenericHttpMessageConverter.java <add>package uk.ac.ebi.quickgo.annotation.download.http; <add> <add>import uk.ac.ebi.quickgo.annotation.model.Annotation; <add>import uk.ac.ebi.quickgo.rest.ResponseExceptionHandler; <add>import uk.ac.ebi.quickgo.rest.search.results.QueryResult; <add> <add>import java.io.IOException; <add>import java.io.OutputStream; <add>import java.util.List; <add>import java.util.concurrent.atomic.AtomicInteger; <add>import java.util.function.Function; <add>import java.util.stream.Collectors; <add>import java.util.stream.Stream; <add>import org.slf4j.Logger; <add>import org.slf4j.LoggerFactory; <add>import org.springframework.http.HttpInputMessage; <add>import org.springframework.http.HttpOutputMessage; <add>import org.springframework.http.MediaType; <add>import org.springframework.http.converter.AbstractHttpMessageConverter; <add>import org.springframework.http.converter.HttpMessageNotReadableException; <add>import org.springframework.http.converter.HttpMessageNotWritableException; <add> <add>/** <add> * Writes a stream of {@link QueryResult}s containing {@link Annotation} instances to a response's output stream, <add> * using the provided converter to format the output. <add> * <add> * @author Tony Wardell <add> * Date: 26/04/2017 <add> * Time: 14:49 <add> * Created with IntelliJ IDEA. <add> */ <add>public class GenericHttpMessageConverter extends AbstractHttpMessageConverter<Object> { <add> <add> private static final Logger LOGGER = LoggerFactory.getLogger(GenericHttpMessageConverter.class); <add> private static final int FLUSH_INTERVAL = 1000; <add> private final Function<Annotation, List<String>> converter; <add> private final MediaType type; <add> <add> public GenericHttpMessageConverter(Function<Annotation, List<String>> converter, MediaType mediaType) { <add> super(mediaType); <add> this.converter = converter; <add> this.type = mediaType; <add> } <add> <add> @Override protected boolean supports(Class<?> clazz) { <add> return true; <add> } <add> <add> @Override protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) <add> throws IOException, HttpMessageNotReadableException { <add> return null; <add> } <add> <add> @Override protected void writeInternal(Object annotationStream, HttpOutputMessage outputMessage) <add> throws IOException, HttpMessageNotWritableException { <add> OutputStream out = outputMessage.getBody(); <add> dispatchWriting(annotationStream, out); <add> } <add> <add> @SuppressWarnings("unchecked") <add> private void dispatchWriting(Object object, OutputStream out) throws IOException { <add> if (object instanceof ResponseExceptionHandler.ErrorInfo) { <add> writeError(out, (ResponseExceptionHandler.ErrorInfo) object); <add> } else { <add> writeAnnotations(out, (Stream<QueryResult<Annotation>>) object); <add> } <add> } <add> <add> private void writeError(OutputStream out, ResponseExceptionHandler.ErrorInfo errorInfo) throws IOException { <add> out.write(("URL:\n\t" + errorInfo.getUrl() + "\n").getBytes()); <add> out.write(("Messages:\n\t" + errorInfo.getMessages().stream().collect(Collectors.joining(",\n"))).getBytes()); <add> } <add> <add> private void writeAnnotations(OutputStream out, Stream<QueryResult<Annotation>> annotationStream) { <add> AtomicInteger counter = new AtomicInteger(0); <add> AtomicInteger batchCount = new AtomicInteger(0); <add> try { <add> annotationStream.forEach(annotationResult -> <add> annotationResult.getResults() <add> .forEach(annotation -> converter.apply(annotation) <add> .forEach(content -> stream(out, <add> counter, <add> batchCount, <add> content)))); <add> } catch (StopStreamException e) { <add> LOGGER.error("Client aborted streaming: closing stream.", e); <add> annotationStream.close(); <add> } <add> LOGGER.info("Written " + counter.get() + type.getType() + " annotations"); <add> } <add> <add> private void stream(OutputStream out, AtomicInteger counter, AtomicInteger batchCount, String content) { <add> try { <add> out.write((content + "\n").getBytes()); <add> updateCountersAndFlushStreamWhenRequired(out, counter, batchCount); <add> } catch (IOException e) { <add> throw new StopStreamException("Could not write OutputStream whilst writing " + type.getType() + " annotation: " + <add> content, e); <add> } <add> } <add> <add> private void updateCountersAndFlushStreamWhenRequired(OutputStream out, AtomicInteger counter, <add> AtomicInteger batchCount) throws IOException { <add> counter.getAndIncrement(); <add> batchCount.getAndIncrement(); <add> if (batchCount.get() >= FLUSH_INTERVAL) { <add> out.flush(); <add> LOGGER.info("Flushed " + type.getType() + " http message converter output stream after: " + <add> counter.get() + " annotations."); <add> batchCount.set(0); <add> } <add> } <add>}
JavaScript
mit
5b5c95590e72b2f13f8727e7c6461221224263a8
0
cars10/elasticvue,cars10/elasticvue,cars10/elasticvue,cars10/elasticvue
const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'] }) const page = await browser.newPage() page.setViewport({ width: 1920, height: 1080 }) await page.goto('http://localhost:8080') await page.click('#theme_select') await connectWithServer(page) await removeSnackbar(page) await clickToNavigateAndScreenshot(page, '#navbar_home', 'screenshot_0_home_white.jpg') await page.click('#theme_select') await clickToNavigateAndScreenshot(page, '#navbar_nodes', 'screenshot_1_nodes.jpg') await clickToNavigateAndScreenshot(page, ['#navbar_indices', 'button[title="Options"]'], 'screenshot_2_indices.jpg') await page.reload() await page.click('#theme_select') await clickToNavigateAndScreenshot(page, '#navbar_search', 'screenshot_4_search_dark.jpg', async page => { await page.click('#index-pattern') await page.waitFor(50) await page.click('input[type="checkbox"]') await page.click('#search_submit') await page.waitFor(250) await page.click('th[aria-label="author_name (author_name.keyword): Not sorted. Activate to sort ascending."') await page.waitFor(250) }) await clickToNavigateAndScreenshot(page, '#navbar_query_rest', 'screenshot_5_query_dark.jpg', async page => { await page.click('#execute_query') await page.waitFor(500) }) await clickToNavigateAndScreenshot(page, ['#navbar_snapshots', '#navbar_snapshots_repositories', 'table tbody tr.tr--clickable'], 'screenshot_6_snapshots_dark.jpg') await clickToNavigateAndScreenshot(page, '#navbar_utilities', 'screenshot_7_utilities_dark.jpg') await browser.close() })() async function connectWithServer (page) { await page.waitFor('#test_connection') await page.click('#test_connection') await page.waitFor('#connect:not(.v-btn--disabled)') await page.click('#connect') await page.waitFor(50) } async function removeSnackbar (page) { await page.waitFor('.v-snack') await page.evaluate(() => { let div = document.querySelector('.v-snack') div.parentNode.removeChild(div) }) } async function clickToNavigateAndScreenshot (page, selectors, screenshot, callback) { console.log(screenshot) if (Array.isArray(selectors)) { for (let selector of selectors) { await page.waitFor(200) try { await page.click(selector) } catch (e) { console.log('error.', e) await page.screenshot({ path: 'scripts/website_screenshots/error.jpg' }) } } } else { await page.waitFor(200) await page.click(selectors) } await page.waitFor(500) if (typeof callback === 'function') await callback(page) await page.screenshot({ path: 'scripts/website_screenshots/' + screenshot }) }
scripts/website_screenshots.js
const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox'] }) const page = await browser.newPage() page.setViewport({ width: 1920, height: 1080 }) await page.goto('http://localhost:8080') await page.click('#theme_select') await connectWithServer(page) await removeSnackbar(page) await clickToNavigateAndScreenshot(page, '#navbar_home', 'screenshot_0_home_white.jpg') await page.click('#theme_select') await clickToNavigateAndScreenshot(page, '#navbar_nodes', 'screenshot_1_nodes.jpg') await clickToNavigateAndScreenshot(page, ['#navbar_indices', 'button[title="Options"]'], 'screenshot_2_indices.jpg') await page.reload() await page.click('#theme_select') await clickToNavigateAndScreenshot(page, '#navbar_search', 'screenshot_4_search_dark.jpg', async page => { await page.click('#index-pattern') await page.waitFor(50) await page.click('input[type="checkbox"]') await page.click('#search_submit') await page.waitFor(250) await page.click('th[aria-label="author_name: Not sorted. Activate to sort ascending."') await page.waitFor(250) }) await clickToNavigateAndScreenshot(page, ['#navbar_query', '#navbar_query_rest'], 'screenshot_5_query_dark.jpg', async page => { await page.click('#execute_query') await page.waitFor(500) }) await clickToNavigateAndScreenshot(page, ['#navbar_snapshots', '#navbar_snapshots_repositories', 'table tbody tr.tr--clickable'], 'screenshot_6_snapshots_dark.jpg') await clickToNavigateAndScreenshot(page, '#navbar_utilities', 'screenshot_7_utilities_dark.jpg') await browser.close() })() async function connectWithServer (page) { await page.waitFor('#test_connection') await page.click('#test_connection') await page.waitFor('#connect:not(.v-btn--disabled)') await page.click('#connect') await page.waitFor(50) } async function removeSnackbar (page) { await page.waitFor('.v-snack') await page.evaluate(() => { let div = document.querySelector('.v-snack') div.parentNode.removeChild(div) }) } async function clickToNavigateAndScreenshot (page, selectors, screenshot, callback) { console.log(screenshot) if (Array.isArray(selectors)) { for (let selector of selectors) { await page.waitFor(200) try { await page.click(selector) } catch (e) { console.log('error.') await page.screenshot({ path: 'scripts/website_screenshots/error.jpg' }) } } } else { await page.waitFor(200) await page.click(selectors) } await page.waitFor(500) if (typeof callback === 'function') await callback(page) await page.screenshot({ path: 'scripts/website_screenshots/' + screenshot }) }
fix website_screenshots script
scripts/website_screenshots.js
fix website_screenshots script
<ide><path>cripts/website_screenshots.js <ide> await page.click('input[type="checkbox"]') <ide> await page.click('#search_submit') <ide> await page.waitFor(250) <del> await page.click('th[aria-label="author_name: Not sorted. Activate to sort ascending."') <add> await page.click('th[aria-label="author_name (author_name.keyword): Not sorted. Activate to sort ascending."') <ide> await page.waitFor(250) <ide> }) <del> await clickToNavigateAndScreenshot(page, ['#navbar_query', '#navbar_query_rest'], 'screenshot_5_query_dark.jpg', async page => { <add> await clickToNavigateAndScreenshot(page, '#navbar_query_rest', 'screenshot_5_query_dark.jpg', async page => { <ide> await page.click('#execute_query') <ide> await page.waitFor(500) <ide> }) <ide> try { <ide> await page.click(selector) <ide> } catch (e) { <del> console.log('error.') <add> console.log('error.', e) <ide> await page.screenshot({ path: 'scripts/website_screenshots/error.jpg' }) <ide> } <ide> }
Java
lgpl-2.1
ee514bccc2e355cd70e91b1077c6c3aa348bb630
0
gallardo/opencms-core,alkacon/opencms-core,gallardo/opencms-core,alkacon/opencms-core,serrapos/opencms-core,mediaworx/opencms-core,ggiudetti/opencms-core,victos/opencms-core,gallardo/opencms-core,serrapos/opencms-core,MenZil/opencms-core,MenZil/opencms-core,sbonoc/opencms-core,victos/opencms-core,victos/opencms-core,ggiudetti/opencms-core,ggiudetti/opencms-core,gallardo/opencms-core,MenZil/opencms-core,serrapos/opencms-core,sbonoc/opencms-core,alkacon/opencms-core,victos/opencms-core,it-tavis/opencms-core,sbonoc/opencms-core,mediaworx/opencms-core,serrapos/opencms-core,mediaworx/opencms-core,serrapos/opencms-core,ggiudetti/opencms-core,sbonoc/opencms-core,alkacon/opencms-core,it-tavis/opencms-core,it-tavis/opencms-core,serrapos/opencms-core,serrapos/opencms-core,mediaworx/opencms-core,MenZil/opencms-core,it-tavis/opencms-core
/* * File : $Source: /alkacon/cvs/opencms/src/com/opencms/core/Attic/OpenCms.java,v $ * Date : $Date: 2000/06/20 11:47:11 $ * Version: $Revision: 1.28 $ * * Copyright (C) 2000 The OpenCms Group * * This File is part of OpenCms - * the Open Source Content Mananagement System * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * For further information about OpenCms, please see the * OpenCms Website: http://www.opencms.com * * You should have received a copy of the GNU General Public License * long with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package com.opencms.core; import java.io.*; import java.util.*; import java.lang.reflect.*; import javax.servlet.*; import javax.servlet.http.*; import source.org.apache.java.io.*; import source.org.apache.java.util.*; import com.opencms.file.*; import com.opencms.launcher.*; /** * This class is the main class of the OpenCms system. * <p> * It is used to read a requested resource from the OpenCms System and forward it to * a launcher, which is performs the output of the requested resource. <br> * * The OpenCms class is independent of access module to the OpenCms (e.g. Servlet, * Command Shell), therefore this class is <b>not</b> responsible for user authentification. * This is done by the access module to the OpenCms. * * @author Michael Emmerich * @author Alexander Lucas * @version $Revision: 1.28 $ $Date: 2000/06/20 11:47:11 $ * * */ public class OpenCms extends A_OpenCms implements I_CmsConstants, I_CmsLogChannels { /** * Definition of the index page */ private static String C_INDEX ="index.html"; /** * The default mimetype */ //private static String C_DEFAULT_MIMETYPE="application/octet-stream"; private static String C_DEFAULT_MIMETYPE="text/html"; /** * The session storage for all active users. */ private CmsSession m_sessionStorage; /** * Reference to the OpenCms launcer manager */ private CmsLauncherManager m_launcherManager; /** * Hashtable with all available Mimetypes. */ private Hashtable m_mt=new Hashtable(); /** * Constructor, creates a new OpenCms object. * * It gets the configurations and inits a rb via the CmsRbManager. * * @param conf The configurations from the property-file. */ OpenCms(Configurations conf) { // invoke the ResourceBroker via the initalizer try { if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCms] creating first cms-object"); } CmsObject cms=new CmsObject(); if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCms] initializing the cms-object and the main resource-broker"); } // init the rb via the manager with the configuration // and init the cms-object with the rb. cms.init(CmsRbManager.init(conf)); printCopyrightInformation(cms); // initalize the Hashtable with all available mimetypes if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCms] read mime types"); } m_mt=cms.readMimeTypes(); if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCms] found " + m_mt.size() + " mime-type entrys"); } } catch (Exception e) { if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCms] " + e.getMessage()); } } // try to initialize the launchers. try { if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCms] initialize launchers..."); } m_launcherManager = new CmsLauncherManager(); } catch (Exception e) { if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCms] " + e.getMessage()); } } } /** * This method gets the requested document from the OpenCms and returns it to the * calling module. * * @param cms The CmsObject containing all information about the requested document * and the requesting user. * @return CmsFile object. */ CmsFile initResource(CmsObject cms) throws CmsException, IOException { CmsFile file=null; //check if the requested resource is a folder // if this is the case, redirect to the according index.html String resourceName=cms.getRequestContext().getUri(); if (resourceName.endsWith("/")) { resourceName+=C_INDEX; cms.getRequestContext().getResponse().sendCmsRedirect(resourceName); } try { //read the requested file file =cms.readFile(cms.getRequestContext().getUri()); } catch (CmsException e ) { if (e.getType() == CmsException.C_NOT_FOUND) { // there was no file found with this name. // it is possible that the requested resource was a folder, so try to access an // index.html there resourceName=cms.getRequestContext().getUri(); // test if the requested file is already the index.html if (!resourceName.endsWith(C_INDEX)) { // check if the requested file ends with an "/" if (!resourceName.endsWith("/")) { resourceName+="/"; } //redirect the request to the index.html resourceName+=C_INDEX; cms.getRequestContext().getResponse().sendCmsRedirect(resourceName); } else { // throw the CmsException. throw e; } } else { // throw the CmsException. throw e; } } if (file != null) { // test if this file is only available for internal access operations if ((file.getAccessFlags() & C_ACCESS_INTERNAL_READ) >0) { throw new CmsException (CmsException.C_EXTXT[CmsException.C_INTERNAL_FILE]+cms.getRequestContext().getUri(), CmsException.C_INTERNAL_FILE); } } return file; } /** * Selects the appropriate launcher for a given file by analyzing the * file's launcher id and calls the initlaunch() method to initiate the * generating of the output. * * @param cms CmsObject containing all document and user information * @param file CmsFile object representing the selected file. * @exception CmsException */ public void showResource(CmsObject cms, CmsFile file) throws CmsException { int launcherId = file.getLauncherType(); String startTemplateClass = file.getLauncherClassname(); I_CmsLauncher launcher = m_launcherManager.getLauncher(launcherId); if(launcher == null) { String errorMessage = "Could not launch file " + file.getName() + ". Launcher for requested launcher ID " + launcherId + " could not be found."; if(A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_INFO, "[OpenCms] " + errorMessage); } throw new CmsException(errorMessage, CmsException.C_UNKNOWN_EXCEPTION); } launcher.initlaunch(cms, file, startTemplateClass, this); } /** * Sets the mimetype of the response.<br> * The mimetype is selected by the file extension of the requested document. * If no available mimetype is found, it is set to the default * "application/octet-stream". * * @param cms The actual OpenCms object. * @param file The requested document. * */ void setResponse(CmsObject cms, CmsFile file){ String ext=null; String mimetype=null; int lastDot=file.getName().lastIndexOf("."); // check if there was a file extension if ((lastDot>0) && (!file.getName().endsWith("."))){ ext=file.getName().substring(lastDot+1,file.getName().length()); mimetype=(String)m_mt.get(ext); // was there a mimetype fo this extension? if (mimetype != null) { cms.getRequestContext().getResponse().setContentType(mimetype); } else { cms.getRequestContext().getResponse().setContentType(C_DEFAULT_MIMETYPE); } } else { cms.getRequestContext().getResponse().setContentType(C_DEFAULT_MIMETYPE); } } /** * Prints a copyright information to all log-files. */ private void printCopyrightInformation(CmsObject cms) { System.err.println(cms.version()); System.out.println(cms.version()); if(c_servletLogging) { this.log(C_OPENCMS_INFO, cms.version()); } String copy[] = cms.copyright(); for(int i = 0; i < copy.length; i++) { System.err.println(copy[i]); System.out.println(copy[i]); if(c_servletLogging) { this.log(C_OPENCMS_INFO, copy[i]); } } } /** * Destructor, called when the the servlet is shut down. * @exception CmsException Throws CmsException if something goes wrong. */ public void destroy() throws CmsException { CmsObject cms=new CmsObject(); cms.destroy(); } }
src/com/opencms/core/OpenCms.java
/* * File : $Source: /alkacon/cvs/opencms/src/com/opencms/core/Attic/OpenCms.java,v $ * Date : $Date: 2000/06/06 13:21:01 $ * Version: $Revision: 1.27 $ * * Copyright (C) 2000 The OpenCms Group * * This File is part of OpenCms - * the Open Source Content Mananagement System * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * For further information about OpenCms, please see the * OpenCms Website: http://www.opencms.com * * You should have received a copy of the GNU General Public License * long with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package com.opencms.core; import java.io.*; import java.util.*; import java.lang.reflect.*; import javax.servlet.*; import javax.servlet.http.*; import source.org.apache.java.io.*; import source.org.apache.java.util.*; import com.opencms.file.*; import com.opencms.launcher.*; /** * This class is the main class of the OpenCms system. * <p> * It is used to read a requested resource from the OpenCms System and forward it to * a launcher, which is performs the output of the requested resource. <br> * * The OpenCms class is independent of access module to the OpenCms (e.g. Servlet, * Command Shell), therefore this class is <b>not</b> responsible for user authentification. * This is done by the access module to the OpenCms. * * @author Michael Emmerich * @author Alexander Lucas * @version $Revision: 1.27 $ $Date: 2000/06/06 13:21:01 $ * * */ class OpenCms extends A_OpenCms implements I_CmsConstants, I_CmsLogChannels { /** * Definition of the index page */ private static String C_INDEX ="index.html"; /** * The default mimetype */ //private static String C_DEFAULT_MIMETYPE="application/octet-stream"; private static String C_DEFAULT_MIMETYPE="text/html"; /** * The session storage for all active users. */ private CmsSession m_sessionStorage; /** * Reference to the OpenCms launcer manager */ private CmsLauncherManager m_launcherManager; /** * Hashtable with all available Mimetypes. */ private Hashtable m_mt=new Hashtable(); /** * Constructor, creates a new OpenCms object. * * It gets the configurations and inits a rb via the CmsRbManager. * * @param conf The configurations from the property-file. */ OpenCms(Configurations conf) { // invoke the ResourceBroker via the initalizer try { if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCms] creating first cms-object"); } CmsObject cms=new CmsObject(); if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCms] initializing the cms-object and the main resource-broker"); } // init the rb via the manager with the configuration // and init the cms-object with the rb. cms.init(CmsRbManager.init(conf)); printCopyrightInformation(cms); // initalize the Hashtable with all available mimetypes if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCms] read mime types"); } m_mt=cms.readMimeTypes(); if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCms] found " + m_mt.size() + " mime-type entrys"); } } catch (Exception e) { if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCms] " + e.getMessage()); } } // try to initialize the launchers. try { if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCms] initialize launchers..."); } m_launcherManager = new CmsLauncherManager(); } catch (Exception e) { if(A_OpenCms.isLogging()) { A_OpenCms.log(I_CmsLogChannels.C_OPENCMS_INIT, "[OpenCms] " + e.getMessage()); } } } /** * This method gets the requested document from the OpenCms and returns it to the * calling module. * * @param cms The CmsObject containing all information about the requested document * and the requesting user. * @return CmsFile object. */ CmsFile initResource(CmsObject cms) throws CmsException, IOException { CmsFile file=null; //check if the requested resource is a folder // if this is the case, redirect to the according index.html String resourceName=cms.getRequestContext().getUri(); if (resourceName.endsWith("/")) { resourceName+=C_INDEX; cms.getRequestContext().getResponse().sendCmsRedirect(resourceName); } try { //read the requested file file =cms.readFile(cms.getRequestContext().getUri()); } catch (CmsException e ) { if (e.getType() == CmsException.C_NOT_FOUND) { // there was no file found with this name. // it is possible that the requested resource was a folder, so try to access an // index.html there resourceName=cms.getRequestContext().getUri(); // test if the requested file is already the index.html if (!resourceName.endsWith(C_INDEX)) { // check if the requested file ends with an "/" if (!resourceName.endsWith("/")) { resourceName+="/"; } //redirect the request to the index.html resourceName+=C_INDEX; cms.getRequestContext().getResponse().sendCmsRedirect(resourceName); } else { // throw the CmsException. throw e; } } else { // throw the CmsException. throw e; } } if (file != null) { // test if this file is only available for internal access operations if ((file.getAccessFlags() & C_ACCESS_INTERNAL_READ) >0) { throw new CmsException (CmsException.C_EXTXT[CmsException.C_INTERNAL_FILE]+cms.getRequestContext().getUri(), CmsException.C_INTERNAL_FILE); } } return file; } /** * Selects the appropriate launcher for a given file by analyzing the * file's launcher id and calls the initlaunch() method to initiate the * generating of the output. * * @param cms CmsObject containing all document and user information * @param file CmsFile object representing the selected file. * @exception CmsException */ public void showResource(CmsObject cms, CmsFile file) throws CmsException { int launcherId = file.getLauncherType(); String startTemplateClass = file.getLauncherClassname(); I_CmsLauncher launcher = m_launcherManager.getLauncher(launcherId); if(launcher == null) { String errorMessage = "Could not launch file " + file.getName() + ". Launcher for requested launcher ID " + launcherId + " could not be found."; if(A_OpenCms.isLogging()) { A_OpenCms.log(C_OPENCMS_INFO, "[OpenCms] " + errorMessage); } throw new CmsException(errorMessage, CmsException.C_UNKNOWN_EXCEPTION); } launcher.initlaunch(cms, file, startTemplateClass, this); } /** * Sets the mimetype of the response.<br> * The mimetype is selected by the file extension of the requested document. * If no available mimetype is found, it is set to the default * "application/octet-stream". * * @param cms The actual OpenCms object. * @param file The requested document. * */ void setResponse(CmsObject cms, CmsFile file){ String ext=null; String mimetype=null; int lastDot=file.getName().lastIndexOf("."); // check if there was a file extension if ((lastDot>0) && (!file.getName().endsWith("."))){ ext=file.getName().substring(lastDot+1,file.getName().length()); mimetype=(String)m_mt.get(ext); // was there a mimetype fo this extension? if (mimetype != null) { cms.getRequestContext().getResponse().setContentType(mimetype); } else { cms.getRequestContext().getResponse().setContentType(C_DEFAULT_MIMETYPE); } } else { cms.getRequestContext().getResponse().setContentType(C_DEFAULT_MIMETYPE); } } /** * Prints a copyright information to all log-files. */ private void printCopyrightInformation(CmsObject cms) { System.err.println(cms.version()); System.out.println(cms.version()); if(c_servletLogging) { this.log(C_OPENCMS_INFO, cms.version()); } String copy[] = cms.copyright(); for(int i = 0; i < copy.length; i++) { System.err.println(copy[i]); System.out.println(copy[i]); if(c_servletLogging) { this.log(C_OPENCMS_INFO, copy[i]); } } } /** * Destructor, called when the the servlet is shut down. * @exception CmsException Throws CmsException if something goes wrong. */ public void destroy() throws CmsException { CmsObject cms=new CmsObject(); cms.destroy(); } }
make OpenCms public
src/com/opencms/core/OpenCms.java
make OpenCms public
<ide><path>rc/com/opencms/core/OpenCms.java <ide> /* <ide> * File : $Source: /alkacon/cvs/opencms/src/com/opencms/core/Attic/OpenCms.java,v $ <del> * Date : $Date: 2000/06/06 13:21:01 $ <del> * Version: $Revision: 1.27 $ <add> * Date : $Date: 2000/06/20 11:47:11 $ <add> * Version: $Revision: 1.28 $ <ide> * <ide> * Copyright (C) 2000 The OpenCms Group <ide> * <ide> * <ide> * @author Michael Emmerich <ide> * @author Alexander Lucas <del>* @version $Revision: 1.27 $ $Date: 2000/06/06 13:21:01 $ <add>* @version $Revision: 1.28 $ $Date: 2000/06/20 11:47:11 $ <ide> * <ide> * */ <ide> <del>class OpenCms extends A_OpenCms implements I_CmsConstants, I_CmsLogChannels <add>public class OpenCms extends A_OpenCms implements I_CmsConstants, I_CmsLogChannels <ide> { <ide> <ide> /**
Java
apache-2.0
8d428148732e9e7b15bb121543ad6a377c6680fb
0
dinithis/stratos,pkdevbox/stratos,agentmilindu/stratos,anuruddhal/stratos,pubudu538/stratos,agentmilindu/stratos,Thanu/stratos,pubudu538/stratos,gayangunarathne/stratos,Thanu/stratos,hsbhathiya/stratos,ravihansa3000/stratos,pubudu538/stratos,agentmilindu/stratos,gayangunarathne/stratos,Thanu/stratos,Thanu/stratos,dinithis/stratos,agentmilindu/stratos,hsbhathiya/stratos,lasinducharith/stratos,lasinducharith/stratos,dinithis/stratos,hsbhathiya/stratos,pkdevbox/stratos,gayangunarathne/stratos,pkdevbox/stratos,lasinducharith/stratos,gayangunarathne/stratos,pubudu538/stratos,pkdevbox/stratos,dinithis/stratos,ravihansa3000/stratos,dinithis/stratos,gayangunarathne/stratos,gayangunarathne/stratos,anuruddhal/stratos,dinithis/stratos,ravihansa3000/stratos,asankasanjaya/stratos,apache/stratos,asankasanjaya/stratos,lasinducharith/stratos,apache/stratos,pubudu538/stratos,pkdevbox/stratos,pkdevbox/stratos,apache/stratos,hsbhathiya/stratos,apache/stratos,anuruddhal/stratos,Thanu/stratos,lasinducharith/stratos,anuruddhal/stratos,gayangunarathne/stratos,pubudu538/stratos,asankasanjaya/stratos,apache/stratos,ravihansa3000/stratos,pkdevbox/stratos,agentmilindu/stratos,ravihansa3000/stratos,pubudu538/stratos,anuruddhal/stratos,Thanu/stratos,ravihansa3000/stratos,dinithis/stratos,anuruddhal/stratos,hsbhathiya/stratos,lasinducharith/stratos,ravihansa3000/stratos,Thanu/stratos,lasinducharith/stratos,agentmilindu/stratos,agentmilindu/stratos,apache/stratos,asankasanjaya/stratos,hsbhathiya/stratos,asankasanjaya/stratos,asankasanjaya/stratos,hsbhathiya/stratos,anuruddhal/stratos,apache/stratos,asankasanjaya/stratos
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.stratos.messaging.util; public class Constants { /* Message broker topic names */ public static final String TOPOLOGY_TOPIC = "topology"; public static final String HEALTH_STAT_TOPIC = "summarized-health-stats"; public static final String INSTANCE_STATUS_TOPIC = "instance-status"; public static final String ARTIFACT_SYNCHRONIZATION_TOPIC = "artifact-synchronization"; public static final String TENANT_TOPIC = "tenant"; public static final String TENANT_RANGE_DELIMITER = "-"; public static final String EVENT_CLASS_NAME = "event-class-name"; /* Topology filter constants */ public static final String FILTER_VALUE_ASSIGN_OPERATOR="="; public static final String FILTER_KEY_VALUE_PAIR_SEPARATOR = "|"; public static final String FILTER_VALUE_SEPARATOR = ","; public static final String TOPOLOGY_SERVICE_FILTER = "stratos.topology.service.filter"; public static final String TOPOLOGY_SERVICE_FILTER_SERVICE_NAME = "service-name"; public static final String TOPOLOGY_CLUSTER_FILTER = "stratos.topology.cluster.filter"; public static final String TOPOLOGY_CLUSTER_FILTER_CLUSTER_ID = "cluster-id"; public static final String TOPOLOGY_MEMBER_FILTER = "stratos.topology.member.filter"; public static final String TOPOLOGY_MEMBER_FILTER_LB_CLUSTER_ID = "lb-cluster-id"; // to identify a lb cluster public static final String IS_LOAD_BALANCER = "load.balancer"; public static final String LOAD_BALANCER_REF = "load.balancer.ref"; public static final String SERVICE_AWARE_LOAD_BALANCER = "service.aware.load.balancer"; public static final String DEFAULT_LOAD_BALANCER = "default.load.balancer"; public static final String NO_LOAD_BALANCER = "no.load.balancer"; public static final String EXISTING_LOAD_BALANCERS = "existing.load.balancers"; }
components/org.apache.stratos.messaging/src/main/java/org/apache/stratos/messaging/util/Constants.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.stratos.messaging.util; public class Constants { /* Message broker topic names */ public static final String TOPOLOGY_TOPIC = "topology"; public static final String HEALTH_STAT_TOPIC = "summarized-health-stats"; public static final String INSTANCE_STATUS_TOPIC = "instance-status"; public static final String ARTIFACT_SYNCHRONIZATION_TOPIC = "artifact-synchronization"; public static final String TENANT_TOPIC = "tenant"; public static final String TENANT_RANGE_DELIMITER = "-"; public static final String EVENT_CLASS_NAME = "event-class-name"; /* Topology filter constants */ public static final String FILTER_VALUE_ASSIGN_OPERATOR="="; public static final String FILTER_KEY_VALUE_PAIR_SEPARATOR = "|"; public static final String FILTER_VALUE_SEPARATOR = ","; public static final String TOPOLOGY_SERVICE_FILTER = "stratos.topology.service.filter"; public static final String TOPOLOGY_SERVICE_FILTER_SERVICE_NAME = "service-name"; public static final String TOPOLOGY_CLUSTER_FILTER = "stratos.topology.cluster.filter"; public static final String TOPOLOGY_CLUSTER_FILTER_CLUSTER_ID = "cluster-id"; public static final String TOPOLOGY_MEMBER_FILTER = "stratos.topology.member.filter"; public static final String TOPOLOGY_MEMBER_FILTER_LB_CLUSTER_ID = "lb-cluster-id"; // to identify a lb cluster public static final String IS_LOAD_BALANCER = "load.balancer"; }
moving lb config constants
components/org.apache.stratos.messaging/src/main/java/org/apache/stratos/messaging/util/Constants.java
moving lb config constants
<ide><path>omponents/org.apache.stratos.messaging/src/main/java/org/apache/stratos/messaging/util/Constants.java <ide> <ide> // to identify a lb cluster <ide> public static final String IS_LOAD_BALANCER = "load.balancer"; <add> public static final String LOAD_BALANCER_REF = "load.balancer.ref"; <add> public static final String SERVICE_AWARE_LOAD_BALANCER = "service.aware.load.balancer"; <add> public static final String DEFAULT_LOAD_BALANCER = "default.load.balancer"; <add> public static final String NO_LOAD_BALANCER = "no.load.balancer"; <add> public static final String EXISTING_LOAD_BALANCERS = "existing.load.balancers"; <ide> }
Java
mpl-2.0
befca816b3c37ccd1d943a925d20bfdc27a6fc09
0
projectdanube/xdi2-tools
package xdi2.tools.commands; import java.util.Iterator; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import xdi2.core.Graph; import xdi2.core.impl.memory.MemoryGraphFactory; import xdi2.core.util.CopyUtil; import xdi2.messaging.exceptions.Xdi2MessagingException; import xdi2.messaging.target.MessagingTarget; import xdi2.messaging.target.impl.graph.GraphMessagingTarget; import xdi2.server.exceptions.Xdi2ServerException; import xdi2.server.factory.MessagingTargetFactory; import xdi2.server.factory.impl.RegistryGraphMessagingTargetFactory; import xdi2.server.registry.HttpEndpointRegistry; import xdi2.tools.annotations.CommandArgs; import xdi2.tools.annotations.CommandName; import xdi2.tools.annotations.CommandUsage; @CommandName("migrate-graphs") @CommandUsage("path-to-input-applicationContext.xml path-to-output-applicationContext.xml") @CommandArgs(min=2,max=2) public class CommandMigrateGraphs implements Command { @Override public void execute(String[] commandArgs) throws Exception { String inputApplicationContextPath; String outputApplicationContextPath; if (commandArgs.length == 2) { inputApplicationContextPath = commandArgs[0]; outputApplicationContextPath = commandArgs[1]; } else { return; } HttpEndpointRegistry inputHttpEndpointRegistry = CommandUtil.getHttpEndpointRegistry(inputApplicationContextPath); HttpEndpointRegistry outputHttpEndpointRegistry = CommandUtil.getHttpEndpointRegistry(outputApplicationContextPath); if (inputHttpEndpointRegistry == null) throw new NoSuchBeanDefinitionException("Required bean 'HttpEndpointRegistry' not found in " + inputApplicationContextPath); if (outputHttpEndpointRegistry == null) throw new NoSuchBeanDefinitionException("Required bean 'HttpEndpointRegistry' not found in " + outputApplicationContextPath); migrateMessagingTargets(inputHttpEndpointRegistry, outputHttpEndpointRegistry); migrateMessagingTargetFactorys(inputHttpEndpointRegistry, outputHttpEndpointRegistry); } private static void migrateMessagingTargets(HttpEndpointRegistry inputHttpEndpointRegistry, HttpEndpointRegistry outputHttpEndpointRegistry) { for (String messagingTargetPath : inputHttpEndpointRegistry.getMessagingTargetPaths()) { MessagingTarget inputMessagingTarget = inputHttpEndpointRegistry.getMessagingTarget(messagingTargetPath); MessagingTarget outputMessagingTarget = outputHttpEndpointRegistry.getMessagingTarget(messagingTargetPath); migrateMessagingTarget(messagingTargetPath, inputMessagingTarget, outputMessagingTarget); } } private static void migrateMessagingTargetFactorys(HttpEndpointRegistry inputHttpEndpointRegistry, HttpEndpointRegistry outputHttpEndpointRegistry) throws Xdi2ServerException, Xdi2MessagingException { for (String messagingTargetFactoryPath : inputHttpEndpointRegistry.getMessagingTargetFactoryPaths()) { MessagingTargetFactory inputMessagingTargetFactory = inputHttpEndpointRegistry.getMessagingTargetFactory(messagingTargetFactoryPath); MessagingTargetFactory outputMessagingTargetFactory = outputHttpEndpointRegistry.getMessagingTargetFactory(messagingTargetFactoryPath); migrateMessagingTargetFactory(messagingTargetFactoryPath, inputMessagingTargetFactory, outputMessagingTargetFactory, inputHttpEndpointRegistry, outputHttpEndpointRegistry); } } private static void migrateMessagingTarget(String messagingTargetPath, MessagingTarget inputMessagingTarget, MessagingTarget outputMessagingTarget) { if (inputMessagingTarget == null || ! (inputMessagingTarget instanceof GraphMessagingTarget)) return; if (outputMessagingTarget == null || ! (outputMessagingTarget instanceof GraphMessagingTarget)) return; Graph inputGraph = ((GraphMessagingTarget) inputMessagingTarget).getGraph(); Graph outputGraph = ((GraphMessagingTarget) outputMessagingTarget).getGraph(); Graph tempGraph = MemoryGraphFactory.getInstance().openGraph(); CopyUtil.copyGraph(inputGraph, tempGraph, null); inputGraph.close(); outputGraph.clear(); CopyUtil.copyGraph(tempGraph, outputGraph, null); outputGraph.close(); System.out.println("At path " + messagingTargetPath + " copied " + inputGraph.getRootContextNode().getAllStatementCount() + " statements from " + inputGraph.getClass().getSimpleName() + " to " + outputGraph.getRootContextNode().getAllStatementCount() + " statements in " + outputGraph.getClass().getSimpleName()); } private static void migrateMessagingTargetFactory(String messagingTargetFactoryPath, MessagingTargetFactory inputMessagingTargetFactory, MessagingTargetFactory outputMessagingTargetFactory, HttpEndpointRegistry inputHttpEndpointRegistry, HttpEndpointRegistry outputHttpEndpointRegistry) throws Xdi2ServerException, Xdi2MessagingException { if (inputMessagingTargetFactory == null || ! (inputMessagingTargetFactory instanceof RegistryGraphMessagingTargetFactory)) return; if (outputMessagingTargetFactory == null || ! (outputMessagingTargetFactory instanceof RegistryGraphMessagingTargetFactory)) return; if (! (((RegistryGraphMessagingTargetFactory) inputMessagingTargetFactory).getPrototypeMessagingTarget() instanceof GraphMessagingTarget)) return; if (! (((RegistryGraphMessagingTargetFactory) outputMessagingTargetFactory).getPrototypeMessagingTarget() instanceof GraphMessagingTarget)) return; Iterator<String> requestPaths = ((RegistryGraphMessagingTargetFactory) inputMessagingTargetFactory).getRequestPaths(messagingTargetFactoryPath); while (requestPaths.hasNext()) { String requestPath = requestPaths.next(); String messagingTargetPath = requestPath; MessagingTarget inputMessagingTarget = inputMessagingTargetFactory.mountMessagingTarget(inputHttpEndpointRegistry, messagingTargetFactoryPath, requestPath); MessagingTarget outputMessagingTarget = outputMessagingTargetFactory.mountMessagingTarget(outputHttpEndpointRegistry, messagingTargetFactoryPath, requestPath); migrateMessagingTarget(messagingTargetPath, inputMessagingTarget, outputMessagingTarget); } System.out.println("At path " + messagingTargetFactoryPath + " migrated from " + inputMessagingTargetFactory.getClass().getSimpleName() + " to " + outputMessagingTargetFactory.getClass().getSimpleName()); } }
src/main/java/xdi2/tools/commands/CommandMigrateGraphs.java
package xdi2.tools.commands; import java.util.Iterator; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import xdi2.core.Graph; import xdi2.core.impl.memory.MemoryGraphFactory; import xdi2.core.util.CopyUtil; import xdi2.messaging.exceptions.Xdi2MessagingException; import xdi2.messaging.target.MessagingTarget; import xdi2.messaging.target.impl.graph.GraphMessagingTarget; import xdi2.server.exceptions.Xdi2ServerException; import xdi2.server.factory.MessagingTargetFactory; import xdi2.server.factory.impl.RegistryGraphMessagingTargetFactory; import xdi2.server.registry.HttpEndpointRegistry; import xdi2.tools.annotations.CommandArgs; import xdi2.tools.annotations.CommandName; import xdi2.tools.annotations.CommandUsage; @CommandName("migrate-graphs") @CommandUsage("path-to-input-applicationContext.xml path-to-output-applicationContext.xml") @CommandArgs(min=2,max=2) public class CommandMigrateGraphs implements Command { @Override public void execute(String[] commandArgs) throws Exception { String inputApplicationContextPath; String outputApplicationContextPath; if (commandArgs.length == 2) { inputApplicationContextPath = commandArgs[0]; outputApplicationContextPath = commandArgs[1]; } else { return; } HttpEndpointRegistry inputHttpEndpointRegistry = CommandUtil.getHttpEndpointRegistry(inputApplicationContextPath); HttpEndpointRegistry outputHttpEndpointRegistry = CommandUtil.getHttpEndpointRegistry(outputApplicationContextPath); if (inputHttpEndpointRegistry == null) throw new NoSuchBeanDefinitionException("Required bean 'HttpEndpointRegistry' not found in " + inputApplicationContextPath); if (outputHttpEndpointRegistry == null) throw new NoSuchBeanDefinitionException("Required bean 'HttpEndpointRegistry' not found in " + outputApplicationContextPath); migrateMessagingTargets(inputHttpEndpointRegistry, outputHttpEndpointRegistry); migrateMessagingTargetFactorys(inputHttpEndpointRegistry, outputHttpEndpointRegistry); } private static void migrateMessagingTargets(HttpEndpointRegistry inputHttpEndpointRegistry, HttpEndpointRegistry outputHttpEndpointRegistry) { for (String messagingTargetPath : inputHttpEndpointRegistry.getMessagingTargetPaths()) { MessagingTarget inputMessagingTarget = inputHttpEndpointRegistry.getMessagingTarget(messagingTargetPath); MessagingTarget outputMessagingTarget = outputHttpEndpointRegistry.getMessagingTarget(messagingTargetPath); migrateMessagingTarget(messagingTargetPath, inputMessagingTarget, outputMessagingTarget); } } private static void migrateMessagingTargetFactorys(HttpEndpointRegistry inputHttpEndpointRegistry, HttpEndpointRegistry outputHttpEndpointRegistry) throws Xdi2ServerException, Xdi2MessagingException { for (String messagingTargetFactoryPath : inputHttpEndpointRegistry.getMessagingTargetFactoryPaths()) { MessagingTargetFactory inputMessagingTargetFactory = inputHttpEndpointRegistry.getMessagingTargetFactory(messagingTargetFactoryPath); MessagingTargetFactory outputMessagingTargetFactory = outputHttpEndpointRegistry.getMessagingTargetFactory(messagingTargetFactoryPath); if (inputMessagingTargetFactory == null || ! (inputMessagingTargetFactory instanceof RegistryGraphMessagingTargetFactory)) continue; if (outputMessagingTargetFactory == null || ! (outputMessagingTargetFactory instanceof RegistryGraphMessagingTargetFactory)) continue; if (! (((RegistryGraphMessagingTargetFactory) inputMessagingTargetFactory).getPrototypeMessagingTarget() instanceof GraphMessagingTarget)) continue; if (! (((RegistryGraphMessagingTargetFactory) outputMessagingTargetFactory).getPrototypeMessagingTarget() instanceof GraphMessagingTarget)) continue; Iterator<String> requestPaths = ((RegistryGraphMessagingTargetFactory) inputMessagingTargetFactory).getRequestPaths(messagingTargetFactoryPath); while (requestPaths.hasNext()) { String requestPath = requestPaths.next(); String messagingTargetPath = requestPath; MessagingTarget inputMessagingTarget = inputMessagingTargetFactory.mountMessagingTarget(inputHttpEndpointRegistry, messagingTargetFactoryPath, requestPath); MessagingTarget outputMessagingTarget = outputMessagingTargetFactory.mountMessagingTarget(outputHttpEndpointRegistry, messagingTargetFactoryPath, requestPath); migrateMessagingTarget(messagingTargetPath, inputMessagingTarget, outputMessagingTarget); } System.out.println("At path " + messagingTargetFactoryPath + " migrated from " + inputMessagingTargetFactory.getClass().getSimpleName() + " to " + outputMessagingTargetFactory.getClass().getSimpleName()); } } private static void migrateMessagingTarget(String messagingTargetPath, MessagingTarget inputMessagingTarget, MessagingTarget outputMessagingTarget) { if (inputMessagingTarget == null || ! (inputMessagingTarget instanceof GraphMessagingTarget)) return; if (outputMessagingTarget == null || ! (outputMessagingTarget instanceof GraphMessagingTarget)) return; Graph inputGraph = ((GraphMessagingTarget) inputMessagingTarget).getGraph(); Graph outputGraph = ((GraphMessagingTarget) outputMessagingTarget).getGraph(); Graph tempGraph = MemoryGraphFactory.getInstance().openGraph(); CopyUtil.copyGraph(inputGraph, tempGraph, null); inputGraph.close(); outputGraph.clear(); CopyUtil.copyGraph(tempGraph, outputGraph, null); outputGraph.close(); System.out.println("At path " + messagingTargetPath + " copied " + inputGraph.getRootContextNode().getAllStatementCount() + " statements from " + inputGraph.getClass().getSimpleName() + " to " + outputGraph.getRootContextNode().getAllStatementCount() + " statements in " + outputGraph.getClass().getSimpleName()); } }
work on graph migration
src/main/java/xdi2/tools/commands/CommandMigrateGraphs.java
work on graph migration
<ide><path>rc/main/java/xdi2/tools/commands/CommandMigrateGraphs.java <ide> } <ide> <ide> private static void migrateMessagingTargets(HttpEndpointRegistry inputHttpEndpointRegistry, HttpEndpointRegistry outputHttpEndpointRegistry) { <del> <add> <ide> for (String messagingTargetPath : inputHttpEndpointRegistry.getMessagingTargetPaths()) { <ide> <ide> MessagingTarget inputMessagingTarget = inputHttpEndpointRegistry.getMessagingTarget(messagingTargetPath); <ide> MessagingTargetFactory inputMessagingTargetFactory = inputHttpEndpointRegistry.getMessagingTargetFactory(messagingTargetFactoryPath); <ide> MessagingTargetFactory outputMessagingTargetFactory = outputHttpEndpointRegistry.getMessagingTargetFactory(messagingTargetFactoryPath); <ide> <del> if (inputMessagingTargetFactory == null || ! (inputMessagingTargetFactory instanceof RegistryGraphMessagingTargetFactory)) continue; <del> if (outputMessagingTargetFactory == null || ! (outputMessagingTargetFactory instanceof RegistryGraphMessagingTargetFactory)) continue; <del> <del> if (! (((RegistryGraphMessagingTargetFactory) inputMessagingTargetFactory).getPrototypeMessagingTarget() instanceof GraphMessagingTarget)) continue; <del> if (! (((RegistryGraphMessagingTargetFactory) outputMessagingTargetFactory).getPrototypeMessagingTarget() instanceof GraphMessagingTarget)) continue; <del> <del> Iterator<String> requestPaths = ((RegistryGraphMessagingTargetFactory) inputMessagingTargetFactory).getRequestPaths(messagingTargetFactoryPath); <del> <del> while (requestPaths.hasNext()) { <del> <del> String requestPath = requestPaths.next(); <del> String messagingTargetPath = requestPath; <del> <del> MessagingTarget inputMessagingTarget = inputMessagingTargetFactory.mountMessagingTarget(inputHttpEndpointRegistry, messagingTargetFactoryPath, requestPath); <del> MessagingTarget outputMessagingTarget = outputMessagingTargetFactory.mountMessagingTarget(outputHttpEndpointRegistry, messagingTargetFactoryPath, requestPath); <del> <del> migrateMessagingTarget(messagingTargetPath, inputMessagingTarget, outputMessagingTarget); <del> } <del> <del> System.out.println("At path " + messagingTargetFactoryPath + " migrated from " + inputMessagingTargetFactory.getClass().getSimpleName() + " to " + outputMessagingTargetFactory.getClass().getSimpleName()); <add> migrateMessagingTargetFactory(messagingTargetFactoryPath, inputMessagingTargetFactory, outputMessagingTargetFactory, inputHttpEndpointRegistry, outputHttpEndpointRegistry); <ide> } <ide> } <ide> <ide> <ide> System.out.println("At path " + messagingTargetPath + " copied " + inputGraph.getRootContextNode().getAllStatementCount() + " statements from " + inputGraph.getClass().getSimpleName() + " to " + outputGraph.getRootContextNode().getAllStatementCount() + " statements in " + outputGraph.getClass().getSimpleName()); <ide> } <add> <add> private static void migrateMessagingTargetFactory(String messagingTargetFactoryPath, MessagingTargetFactory inputMessagingTargetFactory, MessagingTargetFactory outputMessagingTargetFactory, HttpEndpointRegistry inputHttpEndpointRegistry, HttpEndpointRegistry outputHttpEndpointRegistry) throws Xdi2ServerException, Xdi2MessagingException { <add> <add> if (inputMessagingTargetFactory == null || ! (inputMessagingTargetFactory instanceof RegistryGraphMessagingTargetFactory)) return; <add> if (outputMessagingTargetFactory == null || ! (outputMessagingTargetFactory instanceof RegistryGraphMessagingTargetFactory)) return; <add> <add> if (! (((RegistryGraphMessagingTargetFactory) inputMessagingTargetFactory).getPrototypeMessagingTarget() instanceof GraphMessagingTarget)) return; <add> if (! (((RegistryGraphMessagingTargetFactory) outputMessagingTargetFactory).getPrototypeMessagingTarget() instanceof GraphMessagingTarget)) return; <add> <add> Iterator<String> requestPaths = ((RegistryGraphMessagingTargetFactory) inputMessagingTargetFactory).getRequestPaths(messagingTargetFactoryPath); <add> <add> while (requestPaths.hasNext()) { <add> <add> String requestPath = requestPaths.next(); <add> String messagingTargetPath = requestPath; <add> <add> MessagingTarget inputMessagingTarget = inputMessagingTargetFactory.mountMessagingTarget(inputHttpEndpointRegistry, messagingTargetFactoryPath, requestPath); <add> MessagingTarget outputMessagingTarget = outputMessagingTargetFactory.mountMessagingTarget(outputHttpEndpointRegistry, messagingTargetFactoryPath, requestPath); <add> <add> migrateMessagingTarget(messagingTargetPath, inputMessagingTarget, outputMessagingTarget); <add> } <add> <add> System.out.println("At path " + messagingTargetFactoryPath + " migrated from " + inputMessagingTargetFactory.getClass().getSimpleName() + " to " + outputMessagingTargetFactory.getClass().getSimpleName()); <add> } <ide> }
Java
mit
7ac74cd54713c6a272f37b237bf68ba2a6ccbd7a
0
jenkinsci/warnings-plugin,jenkinsci/warnings-plugin,jenkinsci/warnings-plugin
package io.jenkins.plugins.analysis.warnings; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.zip.GZIPOutputStream; import org.apache.commons.io.IOUtils; import org.codehaus.plexus.util.Base64; import org.junit.Test; import org.junit.jupiter.api.Tag; import static edu.hm.hafner.analysis.assertj.Assertions.*; import hudson.matrix.AxisList; import hudson.matrix.MatrixBuild; import hudson.matrix.MatrixProject; import hudson.matrix.MatrixRun; import hudson.matrix.TextAxis; import hudson.model.Result; import hudson.plugins.warnings.AggregatedWarningsResultAction; import hudson.plugins.warnings.ConsoleParser; import hudson.plugins.warnings.WarningsPublisher; import hudson.tasks.Shell; /** * Integration tests of the warnings plug-in in matrix jobs. * * @author Ullrich Hafner */ @Tag("IntegrationTest") public class MatrixJobITest extends IntegrationTest { private static final String WARNINGS_FILE = "matrix-warnings.txt"; /** * Build a matrix job with three configurations. For each configuration a different set of warnings will be parsed * with the same parser (GCC). After the successful build the total number of warnings at the root level should be * set to 12 (sum of all three configurations). Moreover, for each configuration the total number of warnings is * also verified (4, 6, and 2 warnings). * * @throws Exception in case of an error */ @Test public void shouldCreateEmptyResult() throws Exception { MatrixProject project = j.createProject(MatrixProject.class); enableWarnings(project); AxisList axis = new AxisList(); TextAxis userAxis = new TextAxis("user_axis", "one two three"); axis.add(userAxis); project.setAxes(axis); project.getBuildersList().add(new Shell(copyResource(WARNINGS_FILE))); project.getBuildersList().add(new Shell("cat " + WARNINGS_FILE + "| grep $user_axis")); Map<String, Integer> warningsPerAxis = new HashMap<>(); warningsPerAxis.put("one", 4); warningsPerAxis.put("two", 6); warningsPerAxis.put("three", 2); MatrixBuild build = project.scheduleBuild2(0).get(); for (MatrixRun run : build.getRuns()) { j.assertBuildStatus(Result.SUCCESS, run); AggregatedWarningsResultAction action = run.getAction(AggregatedWarningsResultAction.class); assertThat(action).isNotNull(); String currentAxis = run.getBuildVariables().values().iterator().next(); assertThat(action.getResult().getNumberOfAnnotations()).isEqualTo(warningsPerAxis.get(currentAxis)); } AggregatedWarningsResultAction action = build.getAction(AggregatedWarningsResultAction.class); assertThat(action).isNotNull(); assertThat(action.getResult().getNumberOfAnnotations()).isEqualTo(12); } private String copyResource(final String fileName) { Resource resource = createResource(fileName); try (InputStream in = resource.asInputStream()) { ByteArrayOutputStream out = new ByteArrayOutputStream(); copy(in, out); // fileName can include path portion like foo/bar/zot return String.format( "(mkdir -p %1$s || true) && rm -r %1$s && base64 --decode << ENDOFFILE | gunzip > %1$s \n%2$s\nENDOFFILE", resource.getName(), new String(Base64.encodeBase64Chunked(out.toByteArray()))); } catch (IOException e) { throw new AssertionError(e); } } private void copy(final InputStream in, final ByteArrayOutputStream out) throws IOException { try (OutputStream gz = new GZIPOutputStream(out)) { IOUtils.copy(in, gz); } } private Resource createResource(final String path) { URL resource = getClass().getResource(path); if (resource == null) { throw new AssertionError("No such resource " + path + " for " + getClass().getName()); } return new Resource(resource); } private WarningsPublisher enableWarnings(final MatrixProject job) { WarningsPublisher publisher = new WarningsPublisher(); publisher.setConsoleParsers(new ConsoleParser[]{new ConsoleParser("GNU C Compiler 4 (gcc)")}); job.getPublishersList().add(publisher); return publisher; } }
src/test/java/io/jenkins/plugins/analysis/warnings/MatrixJobITest.java
package io.jenkins.plugins.analysis.warnings; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.zip.GZIPOutputStream; import org.apache.commons.io.IOUtils; import org.codehaus.plexus.util.Base64; import org.junit.Test; import org.junit.jupiter.api.Tag; import static edu.hm.hafner.analysis.assertj.Assertions.*; import hudson.matrix.AxisList; import hudson.matrix.MatrixBuild; import hudson.matrix.MatrixProject; import hudson.matrix.MatrixRun; import hudson.matrix.TextAxis; import hudson.model.Result; import hudson.plugins.warnings.AggregatedWarningsResultAction; import hudson.plugins.warnings.ConsoleParser; import hudson.plugins.warnings.WarningsPublisher; import hudson.tasks.Shell; /** * Integration tests of the warnings plug-in in matrix jobs. * * @author Ullrich Hafner */ @Tag("IntegrationTest") public class MatrixJobITest extends IntegrationTest { private static final String WARNINGS_FILE = "matrix-warnings.txt"; /** * Build a matrix job with three configurations. For each configuration a different set of warnings will be parsed * with the same parser (GCC). After the successful build the total number of warnings at the root level should be * set to 12 (sum of all three configurations). Moreover, for each configuration the total number of warnings is * also verified (4, 6, and 2 warnings). * * @throws Exception in case of an error */ @Test public void shouldCreateEmptyResult() throws Exception { MatrixProject project = j.createProject(MatrixProject.class); enableWarnings(project); AxisList axis = new AxisList(); TextAxis userAxis = new TextAxis("user_axis", "one two three"); axis.add(userAxis); project.setAxes(axis); project.getBuildersList().add(new Shell(copyResource(resource(WARNINGS_FILE)))); project.getBuildersList().add(new Shell("cat " + WARNINGS_FILE + "| grep $user_axis")); Map<String, Integer> warningsPerAxis = new HashMap<>(); warningsPerAxis.put("one", 4); warningsPerAxis.put("two", 6); warningsPerAxis.put("three", 2); MatrixBuild build = project.scheduleBuild2(0).get(); for (MatrixRun run : build.getRuns()) { j.assertBuildStatus(Result.SUCCESS, run); AggregatedWarningsResultAction action = run.getAction(AggregatedWarningsResultAction.class); assertThat(action).isNotNull(); String currentAxis = run.getBuildVariables().values().iterator().next(); assertThat(action.getResult().getNumberOfAnnotations()).isEqualTo(warningsPerAxis.get(currentAxis)); } AggregatedWarningsResultAction action = build.getAction(AggregatedWarningsResultAction.class); assertThat(action).isNotNull(); assertThat(action.getResult().getNumberOfAnnotations()).isEqualTo(12); } private String copyResource(final Resource resource) { try (InputStream in = resource.asInputStream()) { ByteArrayOutputStream out = new ByteArrayOutputStream(); copy(in, out); // fileName can include path portion like foo/bar/zot return String.format( "(mkdir -p %1$s || true) && rm -r %1$s && base64 --decode << ENDOFFILE | gunzip > %1$s \n%2$s\nENDOFFILE", resource.getName(), new String(Base64.encodeBase64Chunked(out.toByteArray()))); } catch (IOException e) { throw new AssertionError(e); } } private void copy(final InputStream in, final ByteArrayOutputStream out) throws IOException { try (OutputStream gz = new GZIPOutputStream(out)) { IOUtils.copy(in, gz); } } private Resource resource(final String path) { URL resource = getClass().getResource(path); if (resource == null) { throw new AssertionError("No such resource " + path + " for " + getClass().getName()); } return new Resource(resource); } private WarningsPublisher enableWarnings(final MatrixProject job) { WarningsPublisher publisher = new WarningsPublisher(); publisher.setConsoleParsers(new ConsoleParser[]{new ConsoleParser("GNU C Compiler 4 (gcc)")}); job.getPublishersList().add(publisher); return publisher; } }
Cleanup.
src/test/java/io/jenkins/plugins/analysis/warnings/MatrixJobITest.java
Cleanup.
<ide><path>rc/test/java/io/jenkins/plugins/analysis/warnings/MatrixJobITest.java <ide> axis.add(userAxis); <ide> project.setAxes(axis); <ide> <del> project.getBuildersList().add(new Shell(copyResource(resource(WARNINGS_FILE)))); <add> project.getBuildersList().add(new Shell(copyResource(WARNINGS_FILE))); <ide> project.getBuildersList().add(new Shell("cat " + WARNINGS_FILE + "| grep $user_axis")); <ide> <ide> Map<String, Integer> warningsPerAxis = new HashMap<>(); <ide> assertThat(action.getResult().getNumberOfAnnotations()).isEqualTo(12); <ide> } <ide> <del> private String copyResource(final Resource resource) { <add> private String copyResource(final String fileName) { <add> Resource resource = createResource(fileName); <ide> try (InputStream in = resource.asInputStream()) { <ide> ByteArrayOutputStream out = new ByteArrayOutputStream(); <ide> <ide> } <ide> } <ide> <del> private Resource resource(final String path) { <add> private Resource createResource(final String path) { <ide> URL resource = getClass().getResource(path); <ide> if (resource == null) { <ide> throw new AssertionError("No such resource " + path + " for " + getClass().getName());
Java
apache-2.0
2236b8a536046428257c59be1ca602be810de941
0
Starksoft/materialActivityLib,Starksoft/materialActivityLibExample
package com.starksoft.material_activity; import android.content.res.Configuration; import android.os.Bundle; import android.support.annotation.IdRes; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.view.ActionMode; import android.support.v7.view.ActionMode.Callback; import android.text.TextUtils; import android.view.KeyEvent; import android.view.MenuItem; import android.view.View; import android.widget.TextView; public class StarksoftActivityNewDrawer extends AppCompatActivity { private DrawerLayout mDrawerLayout; private NavigationView mNavigationView; private ActionBarDrawerToggle mDrawerToggle; private CharSequence mDrawerTitle; private CharSequence mTitle; // private StarksoftActivity mActivity; private Fragment activeFragment; // Одновременно может быть только один ActionMode в пределах одной Activity private ActionMode mActionMode; ///////////////////////////////////////////////////////////////////////////////////////////////// // ActionMode related methods ///////////////////////////////////////////////////////////////////////////////////////////////// public ActionMode startMyActionMode(Callback mActionModeCallback) { if (mActionModeCallback == null) return mActionMode = null; return mActionMode = startSupportActionMode(mActionModeCallback); } /** * returns true if mode was closed */ public boolean closeActionMode() { boolean isModeEnabled = mActionMode != null; if (isModeEnabled) mActionMode.finish(); return isModeEnabled; } public ActionMode getActionMode() { return mActionMode; } /** * Узнаем запустил ли юзер ActionMode */ public boolean isActionModeRunning() { return getActionMode() != null; } ///////////////////////////////////////////////////////////////////////////////////////////////// // DrawerLayout related methods ///////////////////////////////////////////////////////////////////////////////////////////////// public NavigationView getNavigationView() { return mNavigationView; } public void disableDrawer(int lockMode) { if (mDrawerLayout == null || getSupportActionBar() == null) return; mDrawerLayout.setDrawerLockMode(lockMode, mNavigationView); getSupportActionBar().setDisplayHomeAsUpEnabled(false); } public void enableDrawer() { if (mDrawerLayout == null || getSupportActionBar() == null) return; mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, mNavigationView); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } public boolean closeDrawer() { int lockMode = mDrawerLayout.getDrawerLockMode(mNavigationView); if (lockMode == DrawerLayout.LOCK_MODE_UNLOCKED && isDrawerOpen()) { mDrawerLayout.closeDrawer(mNavigationView); return true; } return false; } public void toggleDrawer() { if (mDrawerLayout == null || mNavigationView == null) return; int lockMode = mDrawerLayout.getDrawerLockMode(mNavigationView); if (lockMode == DrawerLayout.LOCK_MODE_UNLOCKED) { if (mDrawerLayout.isDrawerOpen(mNavigationView)) mDrawerLayout.closeDrawer(mNavigationView); else mDrawerLayout.openDrawer(mNavigationView); } } public void setDrawerClickListener(NavigationView.OnNavigationItemSelectedListener listener) { if (mNavigationView != null) mNavigationView.setNavigationItemSelectedListener(listener); } public void selectDrawerItemAndSetTitle(@IdRes int resId, int optCounter, String optTitle) { selectDrawerItemAndSetTitle(resId, optTitle); setNavigationViewCounter(resId, optCounter); } public void selectDrawerItemAndSetTitle(@IdRes int resId, String optTitle) { if (mDrawerLayout == null || mNavigationView == null) return; MenuItem menuItem = mNavigationView.getMenu().findItem(resId); if (menuItem == null) return; String title = (String) menuItem.getTitle(); mDrawerLayout.closeDrawer(mNavigationView); setTitle(TextUtils.isEmpty(optTitle) ? title : optTitle); } public void setNavigationViewCounter(@IdRes int itemId, int count) { MenuItem item = getNavigationView().getMenu().findItem(itemId); if (item == null) return; TextView view = (TextView) item.getActionView(); if (view == null) return; view.setText(count > 0 ? String.valueOf(count) : null); } /** * узнаем открыто ли боковое меню */ public boolean isDrawerOpen() { return mDrawerLayout.isDrawerOpen(mNavigationView); } ///////////////////////////////////////////////////////////////////////////////////////////////// // FragmentActivity related methods ///////////////////////////////////////////////////////////////////////////////////////////////// public void setActiveFragment(Fragment dest) { setActiveFragment(dest, false, false); } @SuppressWarnings("ResourceType") public void setActiveFragment(@NonNull Fragment dest, boolean addToBackStack, boolean checkIfEqual) { if (getActionMode() != null) getActionMode().finish(); String tag = dest.getClass().getName(); // FIXME Не очень хорошо матчить по тэгу, в тестовой либе как раз используетсяо один фрагмент с разными аргументами для одного элемента Drawer if (checkIfEqual && getActiveFragment() != null && TextUtils.equals(tag, getActiveFragment().getClass().getName())) return; try { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction mFragmentTransaction = fragmentManager.beginTransaction(); mFragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); // mFragmentTransaction.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out); // if (addToBackStack) // mFragmentTransaction.addToBackStack(null); mFragmentTransaction.replace(R.id.content_frame, activeFragment = dest, tag).commit(); } // Ловим ошибку, если в фоне меняем фрагмент, падает именно здесь // java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState catch (Exception e) { e.printStackTrace(); } } public Fragment getActiveFragment() { return activeFragment; } ///////////////////////////////////////////////////////////////////////////////////////////////// // Другие методы ///////////////////////////////////////////////////////////////////////////////////////////////// public boolean isActionModeOrDrawerOpened() { return isActionModeRunning() || isDrawerOpen(); } public interface DrawerStateCallBack { void onDrawerOpened(View view); void onDrawerClosed(View view); } private DrawerStateCallBack mDrawerStateCallBack; public void registerDrawerCallBack(DrawerStateCallBack newDrawerStateCallBack) { mDrawerStateCallBack = newDrawerStateCallBack; } ///////////////////////////////////////////////////////////////////////////////////////////////// @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity_frame_new_drawer); // mActivity = this; mTitle = mDrawerTitle = getTitle(); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mNavigationView = (NavigationView) findViewById(R.id.left_drawer); // set a custom shadow that overlays the main content when the drawer opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // enable ActionBar app icon to behave as action to toggle nav drawer ActionBar b = getSupportActionBar(); if (b != null) { b.setDisplayHomeAsUpEnabled(true); b.setHomeButtonEnabled(true); } // ActionBarDrawerToggle ties together the the proper interactions // between the sliding drawer and the action bar app icon mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) { public void onDrawerClosed(View view) { if (mDrawerStateCallBack != null) mDrawerStateCallBack.onDrawerClosed(view); getSupportActionBar().setTitle(mTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } public void onDrawerOpened(View drawerView) { if (mDrawerStateCallBack != null) mDrawerStateCallBack.onDrawerOpened(drawerView); if (mActionMode != null) mActionMode.finish(); getSupportActionBar().setTitle(mDrawerTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; mDrawerLayout.setDrawerListener(mDrawerToggle); } @Override public boolean onOptionsItemSelected(MenuItem item) { // The action bar home/up action should open or close the drawer. // ActionBarDrawerToggle will take care of this. return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } @Override public void onBackPressed() { if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) mDrawerLayout.closeDrawer(GravityCompat.START); else if (isActionModeRunning()) closeActionMode(); else super.onBackPressed(); } @Override public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) { if (event.getAction() == KeyEvent.ACTION_UP) { toggleDrawer(); return true; } } return super.onKeyUp(keyCode, event); } @Override public void setTitle(CharSequence title) { mTitle = title; if (getSupportActionBar() != null) getSupportActionBar().setTitle(mTitle); } /** * 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. if (mDrawerToggle != null) mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggles if (mDrawerToggle != null) mDrawerToggle.onConfigurationChanged(newConfig); } }
lib_starksoft_material_activity/src/main/java/com/starksoft/material_activity/StarksoftActivityNewDrawer.java
package com.starksoft.material_activity; import android.content.res.Configuration; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.RectF; import android.os.Bundle; import android.support.annotation.IdRes; import android.support.annotation.NonNull; import android.support.design.widget.NavigationView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.support.v7.view.ActionMode; import android.support.v7.view.ActionMode.Callback; import android.text.TextUtils; import android.text.style.ReplacementSpan; import android.view.KeyEvent; import android.view.MenuItem; import android.view.View; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; public class StarksoftActivityNewDrawer extends AppCompatActivity { private DrawerLayout mDrawerLayout; private NavigationView mNavigationView; private ActionBarDrawerToggle mDrawerToggle; private CharSequence mDrawerTitle; private CharSequence mTitle; // private StarksoftActivity mActivity; private Fragment activeFragment; // Одновременно может быть только один ActionMode в пределах одной Activity private ActionMode mActionMode; ///////////////////////////////////////////////////////////////////////////////////////////////// // ActionMode related methods ///////////////////////////////////////////////////////////////////////////////////////////////// public ActionMode startMyActionMode(Callback mActionModeCallback) { if (mActionModeCallback == null) return mActionMode = null; return mActionMode = startSupportActionMode(mActionModeCallback); } /** * returns true if mode was closed */ public boolean closeActionMode() { boolean isModeEnabled = mActionMode != null; if (isModeEnabled) mActionMode.finish(); return isModeEnabled; } public ActionMode getActionMode() { return mActionMode; } /** * Узнаем запустил ли юзер ActionMode */ public boolean isActionModeRunning() { return getActionMode() != null; } ///////////////////////////////////////////////////////////////////////////////////////////////// // DrawerLayout related methods ///////////////////////////////////////////////////////////////////////////////////////////////// public NavigationView getNavigationView() { return mNavigationView; } public void disableDrawer(int lockMode) { if (mDrawerLayout == null || getSupportActionBar() == null) return; mDrawerLayout.setDrawerLockMode(lockMode, mNavigationView); getSupportActionBar().setDisplayHomeAsUpEnabled(false); } public void enableDrawer() { if (mDrawerLayout == null || getSupportActionBar() == null) return; mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED, mNavigationView); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } public boolean closeDrawer() { int lockMode = mDrawerLayout.getDrawerLockMode(mNavigationView); if (lockMode == DrawerLayout.LOCK_MODE_UNLOCKED && isDrawerOpen()) { mDrawerLayout.closeDrawer(mNavigationView); return true; } return false; } public void toggleDrawer() { if (mDrawerLayout == null || mNavigationView == null) return; int lockMode = mDrawerLayout.getDrawerLockMode(mNavigationView); if (lockMode == DrawerLayout.LOCK_MODE_UNLOCKED) { if (mDrawerLayout.isDrawerOpen(mNavigationView)) mDrawerLayout.closeDrawer(mNavigationView); else mDrawerLayout.openDrawer(mNavigationView); } } public void setDrawerClickListener(NavigationView.OnNavigationItemSelectedListener listener) { if (mNavigationView != null) mNavigationView.setNavigationItemSelectedListener(listener); } public void selectDrawerItemAndSetTitle(@IdRes int resId, int optCounter, String optTitle) { selectDrawerItemAndSetTitle(resId, optTitle); setNavigationViewCounter(resId, optCounter); } public void selectDrawerItemAndSetTitle(@IdRes int resId, String optTitle) { if(mDrawerLayout == null || mNavigationView == null) return; MenuItem menuItem = mNavigationView.getMenu().findItem(resId); if(menuItem == null) return; String title = (String) menuItem.getTitle(); mDrawerLayout.closeDrawer(mNavigationView); setTitle(TextUtils.isEmpty(optTitle) ? title : optTitle); } public void setNavigationViewCounter(@IdRes int itemId, int count) { MenuItem item = getNavigationView().getMenu().findItem(itemId); if (item == null) return; TextView view = (TextView) item.getActionView(); if (view == null) return; view.setText(count > 0 ? String.valueOf(count) : null); } /** * узнаем открыто ли боковое меню */ public boolean isDrawerOpen() { return mDrawerLayout.isDrawerOpen(mNavigationView); } ///////////////////////////////////////////////////////////////////////////////////////////////// // FragmentActivity related methods ///////////////////////////////////////////////////////////////////////////////////////////////// @SuppressWarnings("ResourceType") public void setActiveFragment(Fragment dest) { if (getActionMode() != null) getActionMode().finish(); String tag = dest.getClass().getName(); try { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction mFragmentTransaction = fragmentManager.beginTransaction(); mFragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); // mFragmentTransaction.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out); mFragmentTransaction.replace(R.id.content_frame, activeFragment = dest, tag).commit(); } // Ловим ошибку, если в фоне меняем фрагмент, падает именно здесь // java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState catch (Exception e) { e.printStackTrace(); } } public Fragment getActiveFragment() { return activeFragment; } ///////////////////////////////////////////////////////////////////////////////////////////////// // Другие методы ///////////////////////////////////////////////////////////////////////////////////////////////// public boolean isActionModeOrDrawerOpened() { return isActionModeRunning() || isDrawerOpen(); } public interface DrawerStateCallBack { void onDrawerOpened(View view); void onDrawerClosed(View view); } private DrawerStateCallBack mDrawerStateCallBack; public void registerDrawerCallBack(DrawerStateCallBack newDrawerStateCallBack) { mDrawerStateCallBack = newDrawerStateCallBack; } ///////////////////////////////////////////////////////////////////////////////////////////////// @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity_frame_new_drawer); // mActivity = this; mTitle = mDrawerTitle = getTitle(); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mNavigationView = (NavigationView) findViewById(R.id.left_drawer); // set a custom shadow that overlays the main content when the drawer opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // enable ActionBar app icon to behave as action to toggle nav drawer ActionBar b = getSupportActionBar(); if (b != null) { b.setDisplayHomeAsUpEnabled(true); b.setHomeButtonEnabled(true); } // ActionBarDrawerToggle ties together the the proper interactions // between the sliding drawer and the action bar app icon mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) { public void onDrawerClosed(View view) { if (mDrawerStateCallBack != null) mDrawerStateCallBack.onDrawerClosed(view); getSupportActionBar().setTitle(mTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } public void onDrawerOpened(View drawerView) { if (mDrawerStateCallBack != null) mDrawerStateCallBack.onDrawerOpened(drawerView); if (mActionMode != null) mActionMode.finish(); getSupportActionBar().setTitle(mDrawerTitle); invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; mDrawerLayout.setDrawerListener(mDrawerToggle); } @Override public boolean onOptionsItemSelected(MenuItem item) { // The action bar home/up action should open or close the drawer. // ActionBarDrawerToggle will take care of this. return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } @Override public void onBackPressed() { if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) mDrawerLayout.closeDrawer(GravityCompat.START); else if (isActionModeRunning()) closeActionMode(); else super.onBackPressed(); } @Override public boolean onKeyUp(int keyCode, @NonNull KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_MENU) { if (event.getAction() == KeyEvent.ACTION_UP) { toggleDrawer(); return true; } } return super.onKeyUp(keyCode, event); } @Override public void setTitle(CharSequence title) { mTitle = title; if (getSupportActionBar() != null) getSupportActionBar().setTitle(mTitle); } /** * 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. if (mDrawerToggle != null) mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggles if (mDrawerToggle != null) mDrawerToggle.onConfigurationChanged(newConfig); } }
Fixed some code styling, added some extra
lib_starksoft_material_activity/src/main/java/com/starksoft/material_activity/StarksoftActivityNewDrawer.java
Fixed some code styling, added some extra
<ide><path>ib_starksoft_material_activity/src/main/java/com/starksoft/material_activity/StarksoftActivityNewDrawer.java <ide> package com.starksoft.material_activity; <ide> <ide> import android.content.res.Configuration; <del>import android.graphics.Canvas; <del>import android.graphics.Paint; <del>import android.graphics.RectF; <ide> import android.os.Bundle; <ide> import android.support.annotation.IdRes; <ide> import android.support.annotation.NonNull; <ide> import android.support.v7.view.ActionMode; <ide> import android.support.v7.view.ActionMode.Callback; <ide> import android.text.TextUtils; <del>import android.text.style.ReplacementSpan; <ide> import android.view.KeyEvent; <ide> import android.view.MenuItem; <ide> import android.view.View; <del>import android.widget.ListAdapter; <del>import android.widget.ListView; <ide> import android.widget.TextView; <ide> <ide> public class StarksoftActivityNewDrawer extends AppCompatActivity <ide> <ide> public void selectDrawerItemAndSetTitle(@IdRes int resId, String optTitle) <ide> { <del> if(mDrawerLayout == null || mNavigationView == null) <add> if (mDrawerLayout == null || mNavigationView == null) <ide> return; <ide> <ide> MenuItem menuItem = mNavigationView.getMenu().findItem(resId); <ide> <del> if(menuItem == null) <add> if (menuItem == null) <ide> return; <ide> <ide> String title = (String) menuItem.getTitle(); <ide> ///////////////////////////////////////////////////////////////////////////////////////////////// <ide> // FragmentActivity related methods <ide> ///////////////////////////////////////////////////////////////////////////////////////////////// <add> public void setActiveFragment(Fragment dest) <add> { <add> setActiveFragment(dest, false, false); <add> } <add> <ide> @SuppressWarnings("ResourceType") <del> public void setActiveFragment(Fragment dest) <add> public void setActiveFragment(@NonNull Fragment dest, boolean addToBackStack, boolean checkIfEqual) <ide> { <ide> if (getActionMode() != null) <ide> getActionMode().finish(); <ide> <ide> String tag = dest.getClass().getName(); <add> // FIXME Не очень хорошо матчить по тэгу, в тестовой либе как раз используетсяо один фрагмент с разными аргументами для одного элемента Drawer <add> if (checkIfEqual && getActiveFragment() != null && TextUtils.equals(tag, getActiveFragment().getClass().getName())) <add> return; <ide> <ide> try <ide> { <ide> FragmentTransaction mFragmentTransaction = fragmentManager.beginTransaction(); <ide> mFragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); <ide> // mFragmentTransaction.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out); <add>// if (addToBackStack) <add>// mFragmentTransaction.addToBackStack(null); <add> <ide> mFragmentTransaction.replace(R.id.content_frame, activeFragment = dest, tag).commit(); <ide> } <ide> // Ловим ошибку, если в фоне меняем фрагмент, падает именно здесь
Java
apache-2.0
83660b67f8737e99fdac7d7ed00e35f88db7a236
0
galderz/Aeron,EvilMcJerkface/Aeron,galderz/Aeron,real-logic/Aeron,real-logic/Aeron,real-logic/Aeron,galderz/Aeron,EvilMcJerkface/Aeron,mikeb01/Aeron,galderz/Aeron,mikeb01/Aeron,mikeb01/Aeron,EvilMcJerkface/Aeron,real-logic/Aeron,mikeb01/Aeron,EvilMcJerkface/Aeron
/* * Copyright 2014-2018 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.aeron.cluster.service; import io.aeron.*; import io.aeron.archive.client.AeronArchive; import io.aeron.archive.status.RecordingPos; import io.aeron.cluster.codecs.*; import io.aeron.logbuffer.Header; import io.aeron.status.ReadableCounter; import org.agrona.CloseHelper; import org.agrona.DirectBuffer; import org.agrona.collections.Long2ObjectHashMap; import org.agrona.concurrent.*; import org.agrona.concurrent.status.AtomicCounter; import org.agrona.concurrent.status.CountersReader; import java.util.Collection; import static io.aeron.archive.client.AeronArchive.NULL_LENGTH; import static io.aeron.archive.client.AeronArchive.NULL_POSITION; import static io.aeron.cluster.codecs.ClusterAction.READY; import static io.aeron.cluster.codecs.ClusterAction.REPLAY; import static java.util.Collections.unmodifiableCollection; import static org.agrona.concurrent.status.CountersReader.NULL_COUNTER_ID; class ClusteredServiceAgent implements Agent, Cluster, ServiceControlListener { private final int serviceId; private boolean isRecovering; private final boolean shouldCloseResources; private final AeronArchive.Context archiveCtx; private final ClusteredServiceContainer.Context ctx; private final Aeron aeron; private final Long2ObjectHashMap<ClientSession> sessionByIdMap = new Long2ObjectHashMap<>(); private final Collection<ClientSession> readOnlyClientSessions = unmodifiableCollection(sessionByIdMap.values()); private final ClusteredService service; private final ServiceControlPublisher serviceControlPublisher; private final ServiceControlAdapter serviceControlAdapter; private final IdleStrategy idleStrategy; private final RecordingLog recordingLog; private final EpochClock epochClock; private final CachedEpochClock cachedEpochClock = new CachedEpochClock(); private final ClusterMarkFile markFile; private long termBaseLogPosition; private long leadershipTermId; private long timestampMs; private BoundedLogAdapter logAdapter; private NewActiveLogEvent newActiveLogEvent; private ReadableCounter roleCounter; private AtomicCounter heartbeatCounter; private Role role = Role.FOLLOWER; ClusteredServiceAgent(final ClusteredServiceContainer.Context ctx) { this.ctx = ctx; archiveCtx = ctx.archiveContext(); aeron = ctx.aeron(); shouldCloseResources = ctx.ownsAeronClient(); service = ctx.clusteredService(); recordingLog = ctx.recordingLog(); idleStrategy = ctx.idleStrategy(); serviceId = ctx.serviceId(); epochClock = ctx.epochClock(); markFile = ctx.clusterMarkFile(); final String channel = ctx.serviceControlChannel(); final int streamId = ctx.serviceControlStreamId(); serviceControlPublisher = new ServiceControlPublisher(aeron.addPublication(channel, streamId)); serviceControlAdapter = new ServiceControlAdapter(aeron.addSubscription(channel, streamId), this); } public void onStart() { final CountersReader counters = aeron.countersReader(); roleCounter = awaitClusterRoleCounter(counters); findHeartbeatCounter(counters); service.onStart(this); isRecovering = true; final int recoveryCounterId = awaitRecoveryCounter(counters); checkForSnapshot(counters, recoveryCounterId); checkForReplay(counters, recoveryCounterId); isRecovering = false; service.onReady(); } public void onClose() { if (shouldCloseResources) { CloseHelper.close(logAdapter); CloseHelper.close(serviceControlPublisher); CloseHelper.close(serviceControlAdapter); for (final ClientSession session : sessionByIdMap.values()) { session.disconnect(); } } } public int doWork() { int workCount = 0; final long nowMs = epochClock.time(); if (cachedEpochClock.time() != nowMs) { cachedEpochClock.update(nowMs); markFile.updateActivityTimestamp(nowMs); checkHealthAndUpdateHeartbeat(nowMs); workCount += serviceControlAdapter.poll(); if (newActiveLogEvent != null) { joinActiveLog(); } } workCount += null != logAdapter ? logAdapter.poll() : 0; return workCount; } public String roleName() { return ctx.serviceName(); } public Cluster.Role role() { return role; } public Aeron aeron() { return aeron; } public ClientSession getClientSession(final long clusterSessionId) { return sessionByIdMap.get(clusterSessionId); } public Collection<ClientSession> clientSessions() { return readOnlyClientSessions; } public boolean closeSession(final long clusterSessionId) { final ClientSession clientSession = sessionByIdMap.get(clusterSessionId); if (clientSession == null) { throw new IllegalArgumentException("unknown clusterSessionId: " + clusterSessionId); } if (clientSession.isClosing()) { return true; } if (serviceControlPublisher.closeSession(clusterSessionId)) { clientSession.markClosing(); return true; } return false; } public long timeMs() { return timestampMs; } public boolean scheduleTimer(final long correlationId, final long deadlineMs) { return serviceControlPublisher.scheduleTimer(correlationId, deadlineMs); } public boolean cancelTimer(final long correlationId) { return serviceControlPublisher.cancelTimer(correlationId); } public void onJoinLog( final long leadershipTermId, final int commitPositionId, final int logSessionId, final int logStreamId, final boolean ackBeforeImage, final String logChannel) { newActiveLogEvent = new NewActiveLogEvent( leadershipTermId, commitPositionId, logSessionId, logStreamId, ackBeforeImage, logChannel); } void onSessionMessage( final long clusterSessionId, final long correlationId, final long timestampMs, final DirectBuffer buffer, final int offset, final int length, final Header header) { this.timestampMs = timestampMs; service.onSessionMessage( clusterSessionId, correlationId, timestampMs, buffer, offset, length, header); } void onTimerEvent(final long correlationId, final long timestampMs) { this.timestampMs = timestampMs; service.onTimerEvent(correlationId, timestampMs); } void onSessionOpen( final long clusterSessionId, final long timestampMs, final int responseStreamId, final String responseChannel, final byte[] encodedPrincipal) { this.timestampMs = timestampMs; final ClientSession session = new ClientSession( clusterSessionId, responseStreamId, responseChannel, encodedPrincipal, this); if (Role.LEADER == role) { session.connect(aeron); } sessionByIdMap.put(clusterSessionId, session); service.onSessionOpen(session, timestampMs); } void onSessionClose(final long clusterSessionId, final long timestampMs, final CloseReason closeReason) { this.timestampMs = timestampMs; final ClientSession session = sessionByIdMap.remove(clusterSessionId); session.disconnect(); service.onSessionClose(session, timestampMs, closeReason); } void onServiceAction(final long termPosition, final long timestampMs, final ClusterAction action) { this.timestampMs = timestampMs; executeAction(action, termPosition); } void addSession( final long clusterSessionId, final int responseStreamId, final String responseChannel, final byte[] encodedPrincipal) { final ClientSession session = new ClientSession( clusterSessionId, responseStreamId, responseChannel, encodedPrincipal, ClusteredServiceAgent.this); sessionByIdMap.put(clusterSessionId, session); } private void checkHealthAndUpdateHeartbeat(final long nowMs) { if (null == logAdapter || !logAdapter.image().isClosed()) { heartbeatCounter.setOrdered(nowMs); } } private void role(final Role newRole) { if (newRole != role) { role = newRole; service.onRoleChange(newRole); } } private void checkForSnapshot(final CountersReader counters, final int recoveryCounterId) { final long termPosition = RecoveryState.getTermPosition(counters, recoveryCounterId); leadershipTermId = RecoveryState.getLeadershipTermId(counters, recoveryCounterId); timestampMs = RecoveryState.getTimestamp(counters, recoveryCounterId); if (NULL_POSITION != termPosition) { final RecordingLog.Entry snapshot = recordingLog.getSnapshot(leadershipTermId, termPosition, serviceId); if (null == snapshot) { throw new IllegalStateException("no snapshot available for term position: " + termPosition); } termBaseLogPosition = snapshot.termBaseLogPosition + snapshot.termPosition; loadSnapshot(snapshot.recordingId); } serviceControlPublisher.ackAction( termBaseLogPosition, leadershipTermId, serviceId, ClusterAction.INIT); } private void checkForReplay(final CountersReader counters, final int recoveryCounterId) { final long replayTermCount = RecoveryState.getReplayTermCount(counters, recoveryCounterId); if (0 == replayTermCount) { return; } service.onReplayBegin(); for (int i = 0; i < replayTermCount; i++) { awaitActiveLog(); final int counterId = newActiveLogEvent.commitPositionId; leadershipTermId = CommitPos.getLeadershipTermId(counters, counterId); termBaseLogPosition = CommitPos.getTermBaseLogPosition(counters, counterId); if (CommitPos.getLeadershipTermLength(counters, counterId) > 0) { try (Subscription subscription = aeron.addSubscription( newActiveLogEvent.channel, newActiveLogEvent.streamId)) { serviceControlPublisher.ackAction(termBaseLogPosition, leadershipTermId, serviceId, READY); final Image image = awaitImage(newActiveLogEvent.sessionId, subscription); final ReadableCounter limit = new ReadableCounter(counters, counterId); final BoundedLogAdapter adapter = new BoundedLogAdapter(image, limit, this); consumeImage(image, adapter); termBaseLogPosition += image.position(); } } newActiveLogEvent = null; serviceControlPublisher.ackAction(termBaseLogPosition, leadershipTermId, serviceId, REPLAY); } service.onReplayEnd(); } private void awaitActiveLog() { while (null == newActiveLogEvent) { checkInterruptedStatus(); idleStrategy.idle(serviceControlAdapter.poll()); } } private void consumeImage(final Image image, final BoundedLogAdapter adapter) { while (true) { final int workCount = adapter.poll(); if (workCount == 0) { if (image.isClosed()) { if (!image.isEndOfStream()) { throw new IllegalStateException("unexpected close of replay"); } break; } checkInterruptedStatus(); } idleStrategy.idle(workCount); } } private int awaitRecoveryCounter(final CountersReader counters) { idleStrategy.reset(); int counterId = RecoveryState.findCounterId(counters); while (NULL_COUNTER_ID == counterId) { checkInterruptedStatus(); idleStrategy.idle(); counterId = RecoveryState.findCounterId(counters); } return counterId; } private void joinActiveLog() { if (null != logAdapter) { if (!logAdapter.isCaughtUp()) { return; } logAdapter.close(); logAdapter = null; } final CountersReader counters = aeron.countersReader(); final int commitPositionId = newActiveLogEvent.commitPositionId; if (!CommitPos.isActive(counters, commitPositionId)) { throw new IllegalStateException("CommitPos counter not active: " + commitPositionId); } final int logSessionId = newActiveLogEvent.sessionId; leadershipTermId = newActiveLogEvent.leadershipTermId; termBaseLogPosition = CommitPos.getTermBaseLogPosition(counters, commitPositionId); final Subscription logSubscription = aeron.addSubscription( newActiveLogEvent.channel, newActiveLogEvent.streamId); if (newActiveLogEvent.ackBeforeImage) { serviceControlPublisher.ackAction(termBaseLogPosition, leadershipTermId, serviceId, READY); } final Image image = awaitImage(logSessionId, logSubscription); heartbeatCounter.setOrdered(epochClock.time()); if (!newActiveLogEvent.ackBeforeImage) { serviceControlPublisher.ackAction(termBaseLogPosition, leadershipTermId, serviceId, READY); } newActiveLogEvent = null; logAdapter = new BoundedLogAdapter(image, new ReadableCounter(counters, commitPositionId), this); role(Role.get((int)roleCounter.get())); for (final ClientSession session : sessionByIdMap.values()) { if (Role.LEADER == role) { session.connect(aeron); } else { session.disconnect(); } } } private Image awaitImage(final int sessionId, final Subscription subscription) { idleStrategy.reset(); Image image; while ((image = subscription.imageBySessionId(sessionId)) == null) { checkInterruptedStatus(); idleStrategy.idle(); } return image; } private ReadableCounter awaitClusterRoleCounter(final CountersReader counters) { idleStrategy.reset(); int counterId = ClusterNodeRole.findCounterId(counters); while (NULL_COUNTER_ID == counterId) { checkInterruptedStatus(); idleStrategy.idle(); counterId = ClusterNodeRole.findCounterId(counters); } return new ReadableCounter(counters, counterId); } private void loadSnapshot(final long recordingId) { try (AeronArchive archive = AeronArchive.connect(archiveCtx)) { final String channel = ctx.replayChannel(); final int streamId = ctx.replayStreamId(); final int sessionId = (int)archive.startReplay(recordingId, 0, NULL_LENGTH, channel, streamId); final String replaySessionChannel = ChannelUri.addSessionId(channel, sessionId); try (Subscription subscription = aeron.addSubscription(replaySessionChannel, streamId)) { final Image image = awaitImage(sessionId, subscription); loadState(image); service.onLoadSnapshot(image); } } } private void loadState(final Image image) { final ServiceSnapshotLoader snapshotLoader = new ServiceSnapshotLoader(image, this); while (true) { final int fragments = snapshotLoader.poll(); if (snapshotLoader.isDone()) { break; } if (fragments == 0) { checkInterruptedStatus(); if (image.isClosed()) { throw new IllegalStateException("snapshot ended unexpectedly"); } idleStrategy.idle(fragments); } } } private long onTakeSnapshot(final long termPosition) { final long recordingId; final String channel = ctx.snapshotChannel(); final int streamId = ctx.snapshotStreamId(); try (AeronArchive archive = AeronArchive.connect(archiveCtx); Publication publication = archive.addRecordedExclusivePublication(channel, streamId)) { try { final CountersReader counters = aeron.countersReader(); final int counterId = awaitRecordingCounter(publication, counters); recordingId = RecordingPos.getRecordingId(counters, counterId); snapshotState(publication, termBaseLogPosition + termPosition); service.onTakeSnapshot(publication); awaitRecordingComplete(recordingId, publication.position(), counters, counterId, archive); } finally { archive.stopRecording(publication); } } recordingLog.appendSnapshot( recordingId, leadershipTermId, termBaseLogPosition, termPosition, timestampMs, serviceId); return recordingId; } private void awaitRecordingComplete( final long recordingId, final long completePosition, final CountersReader counters, final int counterId, final AeronArchive archive) { idleStrategy.reset(); do { idleStrategy.idle(); checkInterruptedStatus(); if (!RecordingPos.isActive(counters, counterId, recordingId)) { throw new IllegalStateException("recording has stopped unexpectedly: " + recordingId); } archive.checkForErrorResponse(); } while (counters.getCounterValue(counterId) < completePosition); } private void snapshotState(final Publication publication, final long logPosition) { final ServiceSnapshotTaker snapshotTaker = new ServiceSnapshotTaker(publication, idleStrategy, null); snapshotTaker.markBegin(ClusteredServiceContainer.SNAPSHOT_TYPE_ID, logPosition, leadershipTermId, 0); for (final ClientSession clientSession : sessionByIdMap.values()) { snapshotTaker.snapshotSession(clientSession); } snapshotTaker.markEnd(ClusteredServiceContainer.SNAPSHOT_TYPE_ID, logPosition, leadershipTermId, 0); } private void executeAction(final ClusterAction action, final long termPosition) { if (isRecovering) { return; } final long logPosition = termBaseLogPosition + termPosition; switch (action) { case SNAPSHOT: serviceControlPublisher.ackAction( logPosition, leadershipTermId, onTakeSnapshot(termPosition), serviceId, action); break; case SHUTDOWN: serviceControlPublisher.ackAction( logPosition, leadershipTermId, onTakeSnapshot(termPosition), serviceId, action); ctx.terminationHook().run(); break; case ABORT: serviceControlPublisher.ackAction(logPosition, leadershipTermId, serviceId, action); ctx.terminationHook().run(); break; } } private int awaitRecordingCounter(final Publication publication, final CountersReader counters) { idleStrategy.reset(); int counterId = RecordingPos.findCounterIdBySession(counters, publication.sessionId()); while (NULL_COUNTER_ID == counterId) { checkInterruptedStatus(); idleStrategy.idle(); counterId = RecordingPos.findCounterIdBySession(counters, publication.sessionId()); } return counterId; } private void findHeartbeatCounter(final CountersReader counters) { final int heartbeatCounterId = ServiceHeartbeat.findCounterId(counters, ctx.serviceId()); if (NULL_COUNTER_ID == heartbeatCounterId) { throw new IllegalStateException("failed to find heartbeat counter"); } heartbeatCounter = new AtomicCounter(counters.valuesBuffer(), heartbeatCounterId); } private static void checkInterruptedStatus() { if (Thread.currentThread().isInterrupted()) { throw new AgentTerminationException("unexpected interrupt during operation"); } } }
aeron-cluster/src/main/java/io/aeron/cluster/service/ClusteredServiceAgent.java
/* * Copyright 2014-2018 Real Logic Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.aeron.cluster.service; import io.aeron.*; import io.aeron.archive.client.AeronArchive; import io.aeron.archive.status.RecordingPos; import io.aeron.cluster.codecs.*; import io.aeron.logbuffer.Header; import io.aeron.status.ReadableCounter; import org.agrona.CloseHelper; import org.agrona.DirectBuffer; import org.agrona.collections.Long2ObjectHashMap; import org.agrona.concurrent.*; import org.agrona.concurrent.status.AtomicCounter; import org.agrona.concurrent.status.CountersReader; import java.util.Collection; import static io.aeron.archive.client.AeronArchive.NULL_LENGTH; import static io.aeron.archive.client.AeronArchive.NULL_POSITION; import static io.aeron.cluster.codecs.ClusterAction.READY; import static io.aeron.cluster.codecs.ClusterAction.REPLAY; import static java.util.Collections.unmodifiableCollection; import static org.agrona.concurrent.status.CountersReader.NULL_COUNTER_ID; class ClusteredServiceAgent implements Agent, Cluster, ServiceControlListener { private final int serviceId; private boolean isRecovering; private final boolean shouldCloseResources; private final AeronArchive.Context archiveCtx; private final ClusteredServiceContainer.Context ctx; private final Aeron aeron; private final Long2ObjectHashMap<ClientSession> sessionByIdMap = new Long2ObjectHashMap<>(); private final Collection<ClientSession> readOnlyClientSessions = unmodifiableCollection(sessionByIdMap.values()); private final ClusteredService service; private final ServiceControlPublisher serviceControlPublisher; private final ServiceControlAdapter serviceControlAdapter; private final IdleStrategy idleStrategy; private final RecordingLog recordingLog; private final EpochClock epochClock; private final CachedEpochClock cachedEpochClock = new CachedEpochClock(); private final ClusterMarkFile markFile; private long termBaseLogPosition; private long leadershipTermId; private long timestampMs; private BoundedLogAdapter logAdapter; private NewActiveLogEvent newActiveLogEvent; private ReadableCounter roleCounter; private AtomicCounter heartbeatCounter; private Role role = Role.FOLLOWER; ClusteredServiceAgent(final ClusteredServiceContainer.Context ctx) { this.ctx = ctx; archiveCtx = ctx.archiveContext(); aeron = ctx.aeron(); shouldCloseResources = ctx.ownsAeronClient(); service = ctx.clusteredService(); recordingLog = ctx.recordingLog(); idleStrategy = ctx.idleStrategy(); serviceId = ctx.serviceId(); epochClock = ctx.epochClock(); markFile = ctx.clusterMarkFile(); final String channel = ctx.serviceControlChannel(); final int streamId = ctx.serviceControlStreamId(); serviceControlPublisher = new ServiceControlPublisher(aeron.addPublication(channel, streamId)); serviceControlAdapter = new ServiceControlAdapter(aeron.addSubscription(channel, streamId), this); } public void onStart() { final CountersReader counters = aeron.countersReader(); roleCounter = awaitClusterRoleCounter(counters); findHeartbeatCounter(counters); service.onStart(this); isRecovering = true; final int recoveryCounterId = awaitRecoveryCounter(counters); checkForSnapshot(counters, recoveryCounterId); checkForReplay(counters, recoveryCounterId); isRecovering = false; service.onReady(); } public void onClose() { if (shouldCloseResources) { CloseHelper.close(logAdapter); CloseHelper.close(serviceControlPublisher); CloseHelper.close(serviceControlAdapter); for (final ClientSession session : sessionByIdMap.values()) { session.disconnect(); } } } public int doWork() { int workCount = 0; final long nowMs = epochClock.time(); if (cachedEpochClock.time() != nowMs) { cachedEpochClock.update(nowMs); markFile.updateActivityTimestamp(nowMs); checkHealthAndUpdateHeartbeat(nowMs); workCount += serviceControlAdapter.poll(); if (newActiveLogEvent != null) { joinActiveLog(); } } workCount += null != logAdapter ? logAdapter.poll() : 0; return workCount; } public String roleName() { return ctx.serviceName(); } public Cluster.Role role() { return role; } public Aeron aeron() { return aeron; } public ClientSession getClientSession(final long clusterSessionId) { return sessionByIdMap.get(clusterSessionId); } public Collection<ClientSession> clientSessions() { return readOnlyClientSessions; } public boolean closeSession(final long clusterSessionId) { final ClientSession clientSession = sessionByIdMap.get(clusterSessionId); if (clientSession == null) { throw new IllegalArgumentException("unknown clusterSessionId: " + clusterSessionId); } if (clientSession.isClosing()) { return true; } if (serviceControlPublisher.closeSession(clusterSessionId)) { clientSession.markClosing(); return true; } return false; } public long timeMs() { return timestampMs; } public boolean scheduleTimer(final long correlationId, final long deadlineMs) { return serviceControlPublisher.scheduleTimer(correlationId, deadlineMs); } public boolean cancelTimer(final long correlationId) { return serviceControlPublisher.cancelTimer(correlationId); } public void onJoinLog( final long leadershipTermId, final int commitPositionId, final int logSessionId, final int logStreamId, final boolean ackBeforeImage, final String logChannel) { newActiveLogEvent = new NewActiveLogEvent( leadershipTermId, commitPositionId, logSessionId, logStreamId, ackBeforeImage, logChannel); } void onSessionMessage( final long clusterSessionId, final long correlationId, final long timestampMs, final DirectBuffer buffer, final int offset, final int length, final Header header) { this.timestampMs = timestampMs; service.onSessionMessage( clusterSessionId, correlationId, timestampMs, buffer, offset, length, header); } void onTimerEvent(final long correlationId, final long timestampMs) { this.timestampMs = timestampMs; service.onTimerEvent(correlationId, timestampMs); } void onSessionOpen( final long clusterSessionId, final long timestampMs, final int responseStreamId, final String responseChannel, final byte[] encodedPrincipal) { this.timestampMs = timestampMs; final ClientSession session = new ClientSession( clusterSessionId, responseStreamId, responseChannel, encodedPrincipal, this); if (Role.LEADER == role) { session.connect(aeron); } sessionByIdMap.put(clusterSessionId, session); service.onSessionOpen(session, timestampMs); } void onSessionClose(final long clusterSessionId, final long timestampMs, final CloseReason closeReason) { this.timestampMs = timestampMs; final ClientSession session = sessionByIdMap.remove(clusterSessionId); session.disconnect(); service.onSessionClose(session, timestampMs, closeReason); } void onServiceAction(final long termPosition, final long timestampMs, final ClusterAction action) { this.timestampMs = timestampMs; executeAction(action, termPosition); } void addSession( final long clusterSessionId, final int responseStreamId, final String responseChannel, final byte[] encodedPrincipal) { final ClientSession session = new ClientSession( clusterSessionId, responseStreamId, responseChannel, encodedPrincipal, ClusteredServiceAgent.this); sessionByIdMap.put(clusterSessionId, session); } private void checkHealthAndUpdateHeartbeat(final long nowMs) { if (null == logAdapter || !logAdapter.image().isClosed()) { heartbeatCounter.setOrdered(nowMs); } } private void role(final Role newRole) { if (newRole != role) { role = newRole; service.onRoleChange(newRole); } } private void checkForSnapshot(final CountersReader counters, final int recoveryCounterId) { final long termPosition = RecoveryState.getTermPosition(counters, recoveryCounterId); leadershipTermId = RecoveryState.getLeadershipTermId(counters, recoveryCounterId); timestampMs = RecoveryState.getTimestamp(counters, recoveryCounterId); long recordingId = ServiceControlListener.NULL_VALUE; if (NULL_POSITION != termPosition) { final RecordingLog.Entry snapshot = recordingLog.getSnapshot(leadershipTermId, termPosition, serviceId); if (null == snapshot) { throw new IllegalStateException("no snapshot available for term position: " + termPosition); } recordingId = snapshot.recordingId; termBaseLogPosition = snapshot.termBaseLogPosition + snapshot.termPosition; loadSnapshot(recordingId); } serviceControlPublisher.ackAction( termBaseLogPosition, leadershipTermId, recordingId, serviceId, ClusterAction.INIT); } private void checkForReplay(final CountersReader counters, final int recoveryCounterId) { final long replayTermCount = RecoveryState.getReplayTermCount(counters, recoveryCounterId); if (0 == replayTermCount) { return; } service.onReplayBegin(); for (int i = 0; i < replayTermCount; i++) { awaitActiveLog(); final int counterId = newActiveLogEvent.commitPositionId; leadershipTermId = CommitPos.getLeadershipTermId(counters, counterId); termBaseLogPosition = CommitPos.getTermBaseLogPosition(counters, counterId); if (CommitPos.getLeadershipTermLength(counters, counterId) > 0) { try (Subscription subscription = aeron.addSubscription( newActiveLogEvent.channel, newActiveLogEvent.streamId)) { serviceControlPublisher.ackAction(termBaseLogPosition, leadershipTermId, serviceId, READY); final Image image = awaitImage(newActiveLogEvent.sessionId, subscription); final ReadableCounter limit = new ReadableCounter(counters, counterId); final BoundedLogAdapter adapter = new BoundedLogAdapter(image, limit, this); consumeImage(image, adapter); termBaseLogPosition += image.position(); } } newActiveLogEvent = null; serviceControlPublisher.ackAction(termBaseLogPosition, leadershipTermId, serviceId, REPLAY); } service.onReplayEnd(); } private void awaitActiveLog() { while (null == newActiveLogEvent) { checkInterruptedStatus(); idleStrategy.idle(serviceControlAdapter.poll()); } } private void consumeImage(final Image image, final BoundedLogAdapter adapter) { while (true) { final int workCount = adapter.poll(); if (workCount == 0) { if (image.isClosed()) { if (!image.isEndOfStream()) { throw new IllegalStateException("unexpected close of replay"); } break; } checkInterruptedStatus(); } idleStrategy.idle(workCount); } } private int awaitRecoveryCounter(final CountersReader counters) { idleStrategy.reset(); int counterId = RecoveryState.findCounterId(counters); while (NULL_COUNTER_ID == counterId) { checkInterruptedStatus(); idleStrategy.idle(); counterId = RecoveryState.findCounterId(counters); } return counterId; } private void joinActiveLog() { if (null != logAdapter) { if (!logAdapter.isCaughtUp()) { return; } logAdapter.close(); logAdapter = null; } final CountersReader counters = aeron.countersReader(); final int commitPositionId = newActiveLogEvent.commitPositionId; if (!CommitPos.isActive(counters, commitPositionId)) { throw new IllegalStateException("CommitPos counter not active: " + commitPositionId); } final int logSessionId = newActiveLogEvent.sessionId; leadershipTermId = newActiveLogEvent.leadershipTermId; termBaseLogPosition = CommitPos.getTermBaseLogPosition(counters, commitPositionId); final Subscription logSubscription = aeron.addSubscription( newActiveLogEvent.channel, newActiveLogEvent.streamId); if (newActiveLogEvent.ackBeforeImage) { serviceControlPublisher.ackAction(termBaseLogPosition, leadershipTermId, serviceId, READY); } final Image image = awaitImage(logSessionId, logSubscription); heartbeatCounter.setOrdered(epochClock.time()); if (!newActiveLogEvent.ackBeforeImage) { serviceControlPublisher.ackAction(termBaseLogPosition, leadershipTermId, serviceId, READY); } newActiveLogEvent = null; logAdapter = new BoundedLogAdapter(image, new ReadableCounter(counters, commitPositionId), this); role(Role.get((int)roleCounter.get())); for (final ClientSession session : sessionByIdMap.values()) { if (Role.LEADER == role) { session.connect(aeron); } else { session.disconnect(); } } } private Image awaitImage(final int sessionId, final Subscription subscription) { idleStrategy.reset(); Image image; while ((image = subscription.imageBySessionId(sessionId)) == null) { checkInterruptedStatus(); idleStrategy.idle(); } return image; } private ReadableCounter awaitClusterRoleCounter(final CountersReader counters) { idleStrategy.reset(); int counterId = ClusterNodeRole.findCounterId(counters); while (NULL_COUNTER_ID == counterId) { checkInterruptedStatus(); idleStrategy.idle(); counterId = ClusterNodeRole.findCounterId(counters); } return new ReadableCounter(counters, counterId); } private void loadSnapshot(final long recordingId) { try (AeronArchive archive = AeronArchive.connect(archiveCtx)) { final String channel = ctx.replayChannel(); final int streamId = ctx.replayStreamId(); final int sessionId = (int)archive.startReplay(recordingId, 0, NULL_LENGTH, channel, streamId); final String replaySessionChannel = ChannelUri.addSessionId(channel, sessionId); try (Subscription subscription = aeron.addSubscription(replaySessionChannel, streamId)) { final Image image = awaitImage(sessionId, subscription); loadState(image); service.onLoadSnapshot(image); } } } private void loadState(final Image image) { final ServiceSnapshotLoader snapshotLoader = new ServiceSnapshotLoader(image, this); while (true) { final int fragments = snapshotLoader.poll(); if (snapshotLoader.isDone()) { break; } if (fragments == 0) { checkInterruptedStatus(); if (image.isClosed()) { throw new IllegalStateException("snapshot ended unexpectedly"); } idleStrategy.idle(fragments); } } } private void onTakeSnapshot(final long termPosition) { final long recordingId; final String channel = ctx.snapshotChannel(); final int streamId = ctx.snapshotStreamId(); try (AeronArchive archive = AeronArchive.connect(archiveCtx); Publication publication = archive.addRecordedExclusivePublication(channel, streamId)) { try { final CountersReader counters = aeron.countersReader(); final int counterId = awaitRecordingCounter(publication, counters); recordingId = RecordingPos.getRecordingId(counters, counterId); snapshotState(publication, termBaseLogPosition + termPosition); service.onTakeSnapshot(publication); awaitRecordingComplete(recordingId, publication.position(), counters, counterId, archive); } finally { archive.stopRecording(publication); } } recordingLog.appendSnapshot( recordingId, leadershipTermId, termBaseLogPosition, termPosition, timestampMs, serviceId); } private void awaitRecordingComplete( final long recordingId, final long completePosition, final CountersReader counters, final int counterId, final AeronArchive archive) { idleStrategy.reset(); do { idleStrategy.idle(); checkInterruptedStatus(); if (!RecordingPos.isActive(counters, counterId, recordingId)) { throw new IllegalStateException("recording has stopped unexpectedly: " + recordingId); } archive.checkForErrorResponse(); } while (counters.getCounterValue(counterId) < completePosition); } private void snapshotState(final Publication publication, final long logPosition) { final ServiceSnapshotTaker snapshotTaker = new ServiceSnapshotTaker(publication, idleStrategy, null); snapshotTaker.markBegin(ClusteredServiceContainer.SNAPSHOT_TYPE_ID, logPosition, leadershipTermId, 0); for (final ClientSession clientSession : sessionByIdMap.values()) { snapshotTaker.snapshotSession(clientSession); } snapshotTaker.markEnd(ClusteredServiceContainer.SNAPSHOT_TYPE_ID, logPosition, leadershipTermId, 0); } private void executeAction(final ClusterAction action, final long termPosition) { if (isRecovering) { return; } final long logPosition = termBaseLogPosition + termPosition; switch (action) { case SNAPSHOT: onTakeSnapshot(termPosition); serviceControlPublisher.ackAction(logPosition, leadershipTermId, serviceId, action); break; case SHUTDOWN: onTakeSnapshot(termPosition); serviceControlPublisher.ackAction(logPosition, leadershipTermId, serviceId, action); ctx.terminationHook().run(); break; case ABORT: serviceControlPublisher.ackAction(logPosition, leadershipTermId, serviceId, action); ctx.terminationHook().run(); break; } } private int awaitRecordingCounter(final Publication publication, final CountersReader counters) { idleStrategy.reset(); int counterId = RecordingPos.findCounterIdBySession(counters, publication.sessionId()); while (NULL_COUNTER_ID == counterId) { checkInterruptedStatus(); idleStrategy.idle(); counterId = RecordingPos.findCounterIdBySession(counters, publication.sessionId()); } return counterId; } private void findHeartbeatCounter(final CountersReader counters) { final int heartbeatCounterId = ServiceHeartbeat.findCounterId(counters, ctx.serviceId()); if (NULL_COUNTER_ID == heartbeatCounterId) { throw new IllegalStateException("failed to find heartbeat counter"); } heartbeatCounter = new AtomicCounter(counters.valuesBuffer(), heartbeatCounterId); } private static void checkInterruptedStatus() { if (Thread.currentThread().isInterrupted()) { throw new AgentTerminationException("unexpected interrupt during operation"); } } }
[Java] Return the recordingId of a snapshot to the consensus module from the service.
aeron-cluster/src/main/java/io/aeron/cluster/service/ClusteredServiceAgent.java
[Java] Return the recordingId of a snapshot to the consensus module from the service.
<ide><path>eron-cluster/src/main/java/io/aeron/cluster/service/ClusteredServiceAgent.java <ide> final long termPosition = RecoveryState.getTermPosition(counters, recoveryCounterId); <ide> leadershipTermId = RecoveryState.getLeadershipTermId(counters, recoveryCounterId); <ide> timestampMs = RecoveryState.getTimestamp(counters, recoveryCounterId); <del> long recordingId = ServiceControlListener.NULL_VALUE; <ide> <ide> if (NULL_POSITION != termPosition) <ide> { <ide> throw new IllegalStateException("no snapshot available for term position: " + termPosition); <ide> } <ide> <del> recordingId = snapshot.recordingId; <ide> termBaseLogPosition = snapshot.termBaseLogPosition + snapshot.termPosition; <del> loadSnapshot(recordingId); <add> loadSnapshot(snapshot.recordingId); <ide> } <ide> <ide> serviceControlPublisher.ackAction( <del> termBaseLogPosition, leadershipTermId, recordingId, serviceId, ClusterAction.INIT); <add> termBaseLogPosition, leadershipTermId, serviceId, ClusterAction.INIT); <ide> } <ide> <ide> private void checkForReplay(final CountersReader counters, final int recoveryCounterId) <ide> } <ide> } <ide> <del> private void onTakeSnapshot(final long termPosition) <add> private long onTakeSnapshot(final long termPosition) <ide> { <ide> final long recordingId; <ide> final String channel = ctx.snapshotChannel(); <ide> <ide> recordingLog.appendSnapshot( <ide> recordingId, leadershipTermId, termBaseLogPosition, termPosition, timestampMs, serviceId); <add> <add> return recordingId; <ide> } <ide> <ide> private void awaitRecordingComplete( <ide> switch (action) <ide> { <ide> case SNAPSHOT: <del> onTakeSnapshot(termPosition); <del> serviceControlPublisher.ackAction(logPosition, leadershipTermId, serviceId, action); <add> serviceControlPublisher.ackAction( <add> logPosition, leadershipTermId, onTakeSnapshot(termPosition), serviceId, action); <ide> break; <ide> <ide> case SHUTDOWN: <del> onTakeSnapshot(termPosition); <del> serviceControlPublisher.ackAction(logPosition, leadershipTermId, serviceId, action); <add> serviceControlPublisher.ackAction( <add> logPosition, leadershipTermId, onTakeSnapshot(termPosition), serviceId, action); <ide> ctx.terminationHook().run(); <ide> break; <ide>
Java
apache-2.0
4e649ff1f69583493027855f54c65e8207f4f860
0
java110/MicroCommunity,java110/MicroCommunity,java110/MicroCommunity,java110/MicroCommunity
package com.java110.front.smo.assetExport.impl; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.java110.core.component.BaseComponentSMO; import com.java110.core.context.IPageData; import com.java110.entity.component.ComponentValidateResult; import com.java110.front.smo.assetExport.IExportRoomSMO; import com.java110.utils.constant.ServiceConstant; import com.java110.utils.util.Assert; import com.java110.utils.util.DateUtil; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * @ClassName AssetImportSmoImpl * @Description TODO * @Author wuxw * @Date 2019/9/23 23:14 * @Version 1.0 * add by wuxw 2019/9/23 **/ @Service("exportRoomSMOImpl") public class ExportRoomSMOImpl extends BaseComponentSMO implements IExportRoomSMO { private final static Logger logger = LoggerFactory.getLogger(ExportRoomSMOImpl.class); @Autowired private RestTemplate restTemplate; @Override public ResponseEntity<Object> exportExcelData(IPageData pd) throws Exception { ComponentValidateResult result = this.validateStoreStaffCommunityRelationship(pd, restTemplate); Assert.hasKeyAndValue(JSONObject.parseObject(pd.getReqData()), "communityId", "请求中未包含小区"); Workbook workbook = null; //工作簿 //工作表 workbook = new HSSFWorkbook(); //获取楼信息 getRooms(pd, result, workbook); ByteArrayOutputStream os = new ByteArrayOutputStream(); MultiValueMap headers = new HttpHeaders(); headers.add("content-type", "application/octet-stream;charset=UTF-8"); headers.add("Content-Disposition", "attachment;filename=" + DateUtil.getyyyyMMddhhmmssDateString() + ".xls"); headers.add("Pargam", "no-cache"); headers.add("Cache-Control", "no-cache"); //headers.add("Content-Disposition", "attachment; filename=" + outParam.getString("fileName")); headers.add("Accept-Ranges", "bytes"); byte[] context = null; try { workbook.write(os); context = os.toByteArray(); os.close(); workbook.close(); } catch (IOException e) { e.printStackTrace(); // 保存数据 return new ResponseEntity<Object>("导出失败", HttpStatus.INTERNAL_SERVER_ERROR); } // 保存数据 return new ResponseEntity<Object>(context, headers, HttpStatus.OK); } /** * 查询存在的房屋信息 * room.queryRooms * * @param pd * @param result * @return */ private JSONArray getExistsRoom(IPageData pd, ComponentValidateResult result) { String apiUrl = ""; ResponseEntity<String> responseEntity = null; apiUrl = ServiceConstant.SERVICE_API_URL + "/api/room.queryRooms?page=1&row=10000&communityId=" + result.getCommunityId(); responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET); if (responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 return null; } JSONObject savedRoomInfoResults = JSONObject.parseObject(responseEntity.getBody()); if (!savedRoomInfoResults.containsKey("rooms")) { return null; } return savedRoomInfoResults.getJSONArray("rooms"); } private JSONArray getExistsUnit(IPageData pd, ComponentValidateResult result, String floorId) { String apiUrl = ""; ResponseEntity<String> responseEntity = null; apiUrl = ServiceConstant.SERVICE_API_URL + "/api/unit.queryUnits?communityId=" + result.getCommunityId() + "&floorId=" + floorId; responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET); if (responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 return null; } JSONArray savedFloorInfoResults = JSONArray.parseArray(responseEntity.getBody()); return savedFloorInfoResults; } private JSONArray getExistsFloor(IPageData pd, ComponentValidateResult result) { String apiUrl = ""; ResponseEntity<String> responseEntity = null; apiUrl = ServiceConstant.SERVICE_API_URL + "/api/floor.queryFloors?page=1&row=100&communityId=" + result.getCommunityId(); responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET); if (responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 return null; } JSONObject savedFloorInfoResult = JSONObject.parseObject(responseEntity.getBody()); if (!savedFloorInfoResult.containsKey("apiFloorDataVoList")) { return null; } return savedFloorInfoResult.getJSONArray("apiFloorDataVoList"); } /** * 获取 房屋信息 * * @param componentValidateResult * @param workbook */ private void getRooms(IPageData pd, ComponentValidateResult componentValidateResult, Workbook workbook) { Sheet sheet = workbook.createSheet("房屋信息"); Row row = sheet.createRow(0); row.createCell(0).setCellValue("楼栋编号"); row.createCell(1).setCellValue("单元编号"); row.createCell(2).setCellValue("房屋编码"); row.createCell(3).setCellValue("费用名称"); row.createCell(4).setCellValue("开始时间"); row.createCell(5).setCellValue("结束时间"); row.createCell(6).setCellValue("收费金额"); //查询楼栋信息 JSONArray rooms = this.getExistsRoom(pd, componentValidateResult); if (rooms == null) { return; } for (int roomIndex = 0; roomIndex < rooms.size(); roomIndex++) { row = sheet.createRow(roomIndex + 1); row.createCell(0).setCellValue(rooms.getJSONObject(roomIndex).getString("floorNum")); row.createCell(1).setCellValue(rooms.getJSONObject(roomIndex).getString("unitNum")); row.createCell(2).setCellValue(rooms.getJSONObject(roomIndex).getString("roomNum")); row.createCell(3).setCellValue(""); row.createCell(4).setCellValue(""); row.createCell(5).setCellValue(""); row.createCell(6).setCellValue(""); } } /** * 获取小区 * * @param workbook */ private void getFloors(IPageData pd, ComponentValidateResult componentValidateResult, Workbook workbook) { Sheet sheet = workbook.createSheet("楼栋单元"); Row row = sheet.createRow(0); row.createCell(0).setCellValue("楼栋号"); row.createCell(1).setCellValue("单元编号"); row.createCell(2).setCellValue("总层数"); row.createCell(3).setCellValue("是否有电梯"); //查询楼栋信息 JSONArray floors = this.getExistsFloor(pd, componentValidateResult); if (floors == null) { return; } for (int floorIndex = 0; floorIndex < floors.size(); floorIndex++) { JSONArray units = this.getExistsUnit(pd, componentValidateResult, floors.getJSONObject(floorIndex).getString("floorId")); for (int unitIndex = 0; unitIndex < units.size(); unitIndex++) { row = sheet.createRow(floorIndex + 1); row.createCell(0).setCellValue(floors.getJSONObject(floorIndex).getString("floorNum")); row.createCell(1).setCellValue(units.getJSONObject(unitIndex).getString("unitNum")); row.createCell(2).setCellValue(units.getJSONObject(unitIndex).getString("layerCount")); row.createCell(3).setCellValue("1010".equals(units.getJSONObject(unitIndex).getString("lift")) ? "有" : "无"); } } } public RestTemplate getRestTemplate() { return restTemplate; } public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } }
service-front/src/main/java/com/java110/front/smo/assetExport/impl/ExportRoomSMOImpl.java
package com.java110.front.smo.assetExport.impl; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.java110.core.component.BaseComponentSMO; import com.java110.core.context.IPageData; import com.java110.entity.component.ComponentValidateResult; import com.java110.front.smo.assetExport.IExportRoomSMO; import com.java110.utils.constant.ServiceConstant; import com.java110.utils.util.Assert; import com.java110.utils.util.DateUtil; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * @ClassName AssetImportSmoImpl * @Description TODO * @Author wuxw * @Date 2019/9/23 23:14 * @Version 1.0 * add by wuxw 2019/9/23 **/ @Service("exportRoomSMOImpl") public class ExportRoomSMOImpl extends BaseComponentSMO implements IExportRoomSMO { private final static Logger logger = LoggerFactory.getLogger(ExportRoomSMOImpl.class); @Autowired private RestTemplate restTemplate; @Override public ResponseEntity<Object> exportExcelData(IPageData pd) throws Exception { ComponentValidateResult result = this.validateStoreStaffCommunityRelationship(pd, restTemplate); Assert.hasKeyAndValue(JSONObject.parseObject(pd.getReqData()), "communityId", "请求中未包含小区"); Workbook workbook = null; //工作簿 //工作表 workbook = new HSSFWorkbook(); //获取楼信息 getRooms(pd, result, workbook); ByteArrayOutputStream os = new ByteArrayOutputStream(); MultiValueMap headers = new HttpHeaders(); headers.add("content-type", "application/octet-stream;charset=UTF-8"); headers.add("Content-Disposition", "attachment;filename=" + DateUtil.getyyyyMMddhhmmssDateString() + ".xls"); headers.add("Pargam", "no-cache"); headers.add("Cache-Control", "no-cache"); //headers.add("Content-Disposition", "attachment; filename=" + outParam.getString("fileName")); headers.add("Accept-Ranges", "bytes"); byte[] context = null; try { workbook.write(os); context = os.toByteArray(); os.close(); workbook.close(); } catch (IOException e) { e.printStackTrace(); // 保存数据 return new ResponseEntity<Object>("导出失败", HttpStatus.INTERNAL_SERVER_ERROR); } // 保存数据 return new ResponseEntity<Object>(context, headers, HttpStatus.OK); } /** * 查询存在的房屋信息 * room.queryRooms * * @param pd * @param result * @return */ private JSONArray getExistsRoom(IPageData pd, ComponentValidateResult result) { String apiUrl = ""; ResponseEntity<String> responseEntity = null; apiUrl = ServiceConstant.SERVICE_API_URL + "/api/room.queryRooms?page=1&row=10000&communityId=" + result.getCommunityId(); responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET); if (responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 return null; } JSONObject savedRoomInfoResults = JSONObject.parseObject(responseEntity.getBody()); if (!savedRoomInfoResults.containsKey("rooms")) { return null; } return savedRoomInfoResults.getJSONArray("rooms"); } private JSONArray getExistsUnit(IPageData pd, ComponentValidateResult result, String floorId) { String apiUrl = ""; ResponseEntity<String> responseEntity = null; apiUrl = ServiceConstant.SERVICE_API_URL + "/api/unit.queryUnits?communityId=" + result.getCommunityId() + "&floorId=" + floorId; responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET); if (responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 return null; } JSONArray savedFloorInfoResults = JSONArray.parseArray(responseEntity.getBody()); return savedFloorInfoResults; } private JSONArray getExistsFloor(IPageData pd, ComponentValidateResult result) { String apiUrl = ""; ResponseEntity<String> responseEntity = null; apiUrl = ServiceConstant.SERVICE_API_URL + "/api/floor.queryFloors?page=1&row=100&communityId=" + result.getCommunityId(); responseEntity = this.callCenterService(restTemplate, pd, "", apiUrl, HttpMethod.GET); if (responseEntity.getStatusCode() != HttpStatus.OK) { //跳过 保存单元信息 return null; } JSONObject savedFloorInfoResult = JSONObject.parseObject(responseEntity.getBody()); if (!savedFloorInfoResult.containsKey("apiFloorDataVoList")) { return null; } return savedFloorInfoResult.getJSONArray("apiFloorDataVoList"); } /** * 获取 房屋信息 * * @param componentValidateResult * @param workbook */ private void getRooms(IPageData pd, ComponentValidateResult componentValidateResult, Workbook workbook) { Sheet sheet = workbook.createSheet("房屋信息"); Row row = sheet.createRow(0); row.createCell(0).setCellValue("楼栋编号"); row.createCell(1).setCellValue("单元编号"); row.createCell(2).setCellValue("房屋编码"); row.createCell(3).setCellValue("费用名称"); row.createCell(4).setCellValue("开始时间"); row.createCell(5).setCellValue("结束时间"); row.createCell(6).setCellValue("收费金额"); //查询楼栋信息 JSONArray rooms = this.getExistsRoom(pd, componentValidateResult); if (rooms == null) { return; } for (int roomIndex = 0; roomIndex < rooms.size(); roomIndex++) { row = sheet.createRow(roomIndex + 1); row.createCell(0).setCellValue(rooms.getJSONObject(roomIndex).getString("roomNum")); row.createCell(1).setCellValue(rooms.getJSONObject(roomIndex).getString("floorNum")); row.createCell(2).setCellValue(rooms.getJSONObject(roomIndex).getString("unitNum")); row.createCell(3).setCellValue(""); row.createCell(4).setCellValue(""); row.createCell(5).setCellValue(""); row.createCell(6).setCellValue(""); } } /** * 获取小区 * * @param workbook */ private void getFloors(IPageData pd, ComponentValidateResult componentValidateResult, Workbook workbook) { Sheet sheet = workbook.createSheet("楼栋单元"); Row row = sheet.createRow(0); row.createCell(0).setCellValue("楼栋号"); row.createCell(1).setCellValue("单元编号"); row.createCell(2).setCellValue("总层数"); row.createCell(3).setCellValue("是否有电梯"); //查询楼栋信息 JSONArray floors = this.getExistsFloor(pd, componentValidateResult); if (floors == null) { return; } for (int floorIndex = 0; floorIndex < floors.size(); floorIndex++) { JSONArray units = this.getExistsUnit(pd, componentValidateResult, floors.getJSONObject(floorIndex).getString("floorId")); for (int unitIndex = 0; unitIndex < units.size(); unitIndex++) { row = sheet.createRow(floorIndex + 1); row.createCell(0).setCellValue(floors.getJSONObject(floorIndex).getString("floorNum")); row.createCell(1).setCellValue(units.getJSONObject(unitIndex).getString("unitNum")); row.createCell(2).setCellValue(units.getJSONObject(unitIndex).getString("layerCount")); row.createCell(3).setCellValue("1010".equals(units.getJSONObject(unitIndex).getString("lift")) ? "有" : "无"); } } } public RestTemplate getRestTemplate() { return restTemplate; } public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } }
优化费用导入模板下载功能
service-front/src/main/java/com/java110/front/smo/assetExport/impl/ExportRoomSMOImpl.java
优化费用导入模板下载功能
<ide><path>ervice-front/src/main/java/com/java110/front/smo/assetExport/impl/ExportRoomSMOImpl.java <ide> } <ide> for (int roomIndex = 0; roomIndex < rooms.size(); roomIndex++) { <ide> row = sheet.createRow(roomIndex + 1); <del> row.createCell(0).setCellValue(rooms.getJSONObject(roomIndex).getString("roomNum")); <del> row.createCell(1).setCellValue(rooms.getJSONObject(roomIndex).getString("floorNum")); <del> row.createCell(2).setCellValue(rooms.getJSONObject(roomIndex).getString("unitNum")); <add> row.createCell(0).setCellValue(rooms.getJSONObject(roomIndex).getString("floorNum")); <add> row.createCell(1).setCellValue(rooms.getJSONObject(roomIndex).getString("unitNum")); <add> row.createCell(2).setCellValue(rooms.getJSONObject(roomIndex).getString("roomNum")); <ide> row.createCell(3).setCellValue(""); <ide> row.createCell(4).setCellValue(""); <ide> row.createCell(5).setCellValue("");
JavaScript
mit
30f41ce720829df426e784bffac21d4363b324b5
0
Tvolex/FA_Tvolex,Tvolex/FA_Tvolex
const config = {}; config.port = process.env.PORT || 3000; config.dbName = "firstappusers"; config.dbHost = "Tvolex:[email protected]"; config.dbPort = "31895"; config.DBurl = `mongodb://${config.dbHost}:${config.dbPort}/${config.dbName}`; module.exports = config;
src/config.js
const config = {}; config.port = process.env.PORT || 3000; config.dbName = "firstappusers"; config.dbHost = "Tvolex:[email protected]"; config.dbPort = "31895"; //config.DBurl= 'mongodb://Tvolex:[email protected]:31895/${config.DBname}'; config.DBurl = `mongodb://${config.dbHost}:${config.dbPort}/${config.dbName}`; module.exports = config;
master
src/config.js
master
<ide><path>rc/config.js <ide> config.dbName = "firstappusers"; <ide> config.dbHost = "Tvolex:[email protected]"; <ide> config.dbPort = "31895"; <del>//config.DBurl= 'mongodb://Tvolex:[email protected]:31895/${config.DBname}'; <ide> config.DBurl = `mongodb://${config.dbHost}:${config.dbPort}/${config.dbName}`; <ide> <ide> module.exports = config;
Java
agpl-3.0
a065cae3b032ab2ef4fa7725bccabc3089e6e8ec
0
Tanaguru/Tanaguru,medsob/Tanaguru,dzc34/Asqatasun,Asqatasun/Asqatasun,Tanaguru/Tanaguru,dzc34/Asqatasun,Asqatasun/Asqatasun,dzc34/Asqatasun,Asqatasun/Asqatasun,medsob/Tanaguru,Asqatasun/Asqatasun,medsob/Tanaguru,medsob/Tanaguru,Tanaguru/Tanaguru,dzc34/Asqatasun,Asqatasun/Asqatasun,Tanaguru/Tanaguru,dzc34/Asqatasun
package org.opens.tanaguru.contentloader; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.UnknownHostException; import javax.net.ssl.SSLPeerUnverifiedException; import org.apache.http.client.HttpClient; import org.apache.http.client.HttpResponseException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpParams; import org.apache.log4j.Logger; public class DownloaderImpl implements Downloader { protected String result; protected String url; private final String HTTP_PROTOCOL_PREFIX = "http://"; private final String HTTPS_PROTOCOL_PREFIX = "https://"; private final String FILE_PROTOCOL_PREFIX = "file:/"; // private final String unreachableUrl = "Unreachable Url : "; public DownloaderImpl() { super(); } private String load(String url) { BufferedReader in = null; try { StringBuffer urlContent = new StringBuffer(); String thisLine; URL u = new URL(url); in = new BufferedReader(new InputStreamReader(u.openStream())); while ((thisLine = in.readLine()) != null) { //Correction of #34 bug urlContent.append(thisLine + "\r"); } return urlContent.toString(); } catch (IOException ex) { Logger.getLogger(DownloaderImpl.class.getName()).warn(ex); return ""; } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { Logger.getLogger(DownloaderImpl.class.getName()).warn(ex); throw new RuntimeException(ex); } } } private String download(String url) { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); httpclient.getParams().setParameter( "http.socket.timeout", new Integer(10000)); httpclient.getParams().setParameter( "http.connection.timeout", new Integer(10000)); // Create a response handler ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = null; try { responseBody = httpclient.execute(httpget, responseHandler); } catch (HttpResponseException ex) { Logger.getLogger(DownloaderImpl.class.getName()). warn(ex.getMessage() + " " +url); return ""; } catch (UnknownHostException ex ) { Logger.getLogger(DownloaderImpl.class.getName()). warn(ex.getMessage() + " " +url); return ""; } catch (SSLPeerUnverifiedException ex) { Logger.getLogger(DownloaderImpl.class.getName()). warn(ex.getMessage() + " " +url); return ""; } catch (IOException ex) { Logger.getLogger(DownloaderImpl.class.getName()). warn(ex.getMessage() + " " +url); return ""; } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); return responseBody; } @Override public String getResult() { return result; } @Override public String getURL() { return url; } @Override public void run() { if (url.startsWith(HTTP_PROTOCOL_PREFIX) || url.startsWith(HTTPS_PROTOCOL_PREFIX)) { Logger.getLogger(DownloaderImpl.class.getName()). info("Download resource " + url); result = download(url); } else if (url.startsWith(FILE_PROTOCOL_PREFIX)) { Logger.getLogger(DownloaderImpl.class.getName()). info("Load resource " + url); result = load(url); } } @Override public void setURL(String url) { this.url = url; } }
contentloader/src/main/java/org/opens/tanaguru/contentloader/DownloaderImpl.java
package org.opens.tanaguru.contentloader; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.net.UnknownHostException; import javax.net.ssl.SSLPeerUnverifiedException; import org.apache.http.client.HttpClient; import org.apache.http.client.HttpResponseException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.log4j.Logger; public class DownloaderImpl implements Downloader { protected String result; protected String url; private final String HTTP_PROTOCOL_PREFIX = "http://"; private final String HTTPS_PROTOCOL_PREFIX = "https://"; private final String FILE_PROTOCOL_PREFIX = "file:/"; private final String unreachableUrl = "Unreachable Url : "; public DownloaderImpl() { super(); } private String load(String url) { BufferedReader in = null; try { StringBuffer urlContent = new StringBuffer(); String thisLine; URL u = new URL(url); in = new BufferedReader(new InputStreamReader(u.openStream())); while ((thisLine = in.readLine()) != null) { //Correction of #34 bug urlContent.append(thisLine + "\r"); } return urlContent.toString(); } catch (IOException ex) { Logger.getLogger(DownloaderImpl.class.getName()).warn(ex); return ""; } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { Logger.getLogger(DownloaderImpl.class.getName()).warn(ex); throw new RuntimeException(ex); } } } private String download(String url) { HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); // Create a response handler ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = null; try { responseBody = httpclient.execute(httpget, responseHandler); } catch (HttpResponseException ex) { Logger.getLogger(DownloaderImpl.class.getName()). warn(ex.getMessage() + " " +url); return ""; } catch (UnknownHostException ex ) { Logger.getLogger(DownloaderImpl.class.getName()). warn(ex.getMessage() + " " +url); return ""; } catch (SSLPeerUnverifiedException ex) { Logger.getLogger(DownloaderImpl.class.getName()). warn(ex.getMessage() + " " +url); return ""; } catch (IOException ex) { Logger.getLogger(DownloaderImpl.class.getName()). warn(ex.getMessage() + " " +url); return ""; } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); return responseBody; } @Override public String getResult() { return result; } @Override public String getURL() { return url; } @Override public void run() { if (url.startsWith(HTTP_PROTOCOL_PREFIX) || url.startsWith(HTTPS_PROTOCOL_PREFIX)) { Logger.getLogger(DownloaderImpl.class.getName()). info("Download resource " + url); result = download(url); } else if (url.startsWith(FILE_PROTOCOL_PREFIX)) { Logger.getLogger(DownloaderImpl.class.getName()). info("Load resource " + url); result = load(url); } } @Override public void setURL(String url) { this.url = url; } }
Adding a timeout for the downloader
contentloader/src/main/java/org/opens/tanaguru/contentloader/DownloaderImpl.java
Adding a timeout for the downloader
<ide><path>ontentloader/src/main/java/org/opens/tanaguru/contentloader/DownloaderImpl.java <ide> import org.apache.http.client.methods.HttpGet; <ide> import org.apache.http.impl.client.BasicResponseHandler; <ide> import org.apache.http.impl.client.DefaultHttpClient; <add>import org.apache.http.params.HttpParams; <ide> import org.apache.log4j.Logger; <ide> <ide> public class DownloaderImpl implements Downloader { <ide> private final String HTTP_PROTOCOL_PREFIX = "http://"; <ide> private final String HTTPS_PROTOCOL_PREFIX = "https://"; <ide> private final String FILE_PROTOCOL_PREFIX = "file:/"; <del> private final String unreachableUrl = "Unreachable Url : "; <add>// private final String unreachableUrl = "Unreachable Url : "; <ide> <ide> public DownloaderImpl() { <ide> super(); <ide> <ide> HttpGet httpget = new HttpGet(url); <ide> <add> httpclient.getParams().setParameter( <add> "http.socket.timeout", new Integer(10000)); <add> httpclient.getParams().setParameter( <add> "http.connection.timeout", new Integer(10000)); <add> <ide> // Create a response handler <ide> ResponseHandler<String> responseHandler = new BasicResponseHandler(); <ide> String responseBody = null; <ide> Logger.getLogger(DownloaderImpl.class.getName()). <ide> warn(ex.getMessage() + " " +url); <ide> return ""; <del> } <add> } <ide> // When HttpClient instance is no longer needed, <ide> // shut down the connection manager to ensure <ide> // immediate deallocation of all system resources <ide> @Override <ide> public void setURL(String url) { <ide> this.url = url; <del> } <add> } <ide> <ide> }
JavaScript
mit
7a1151c579063c90a4c2c785176290279810be01
0
JamesMGreene/qunit-assert-html,qunitjs/qunit,danielgindi/qunit,qunitjs/qunit,JamesMGreene/qunit-assert-html
/* * QUnit - A JavaScript Unit Testing Framework * * http://docs.jquery.com/QUnit * * Copyright (c) 2009 John Resig, Jörn Zaefferer * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * $Id$ */ (function(window) { var QUnit = { // call on start of module test to prepend name to all tests module: function module(name, lifecycle) { config.currentModule = name; config.moduleLifecycle = lifecycle; synchronize(function() { QUnit.moduleLog( name ); }); }, test: function test(testName, callback) { var name = testName; if ( config.currentModule ) { name = config.currentModule + " module: " + name; } var lifecycle = extend({ setup: function() {}, teardown: function() {} }, config.moduleLifecycle); if ( !validTest(name) ) { return; } var testEnvironment = {}; synchronize(function() { QUnit.testLog( testName ); config.assertions = []; config.expected = null; try { if ( !config.pollution ) { saveGlobal(); } lifecycle.setup.call(testEnvironment); } catch(e) { QUnit.ok( false, "Setup failed on " + name + ": " + e.message ); } }); synchronize(function() { try { callback.call(testEnvironment); } catch(e) { fail("Test " + name + " died, exception and test follows", e, callback); QUnit.ok( false, "Died on test #" + (config.assertions.length + 1) + ": " + e.message ); // else next test will carry the responsibility saveGlobal(); } }); synchronize(function() { try { checkPollution(); lifecycle.teardown.call(testEnvironment); } catch(e) { QUnit.ok( false, "Teardown failed on " + name + ": " + e.message ); } }); synchronize(function() { try { reset(); } catch(e) { fail("reset() failed, following Test " + name + ", exception and reset fn follows", e, reset); } if ( config.expected && config.expected != config.assertions.length ) { QUnit.ok( false, "Expected " + config.expected + " assertions, but " + config.assertions.length + " were run" ); } var good = 0, bad = 0, tests = id("qunit-tests"); config.stats.all += config.assertions.length; if ( tests ) { var ol = document.createElement("ol"); ol.style.display = "none"; for ( var i = 0; i < config.assertions.length; i++ ) { var assertion = config.assertions[i]; var li = document.createElement("li"); li.className = assertion.result ? "pass" : "fail"; li.innerHTML = assertion.message || "(no message)"; ol.appendChild( li ); if ( assertion.result ) { good++; } else { bad++; config.stats.bad++; } } var b = document.createElement("strong"); b.innerHTML = name + " <b style='color:black;'>(<b class='fail'>" + bad + "</b>, <b class='pass'>" + good + "</b>, " + config.assertions.length + ")</b>"; addEvent(b, "click", function() { var next = b.nextSibling, display = next.style.display; next.style.display = display === "none" ? "block" : "none"; }); addEvent(b, "dblclick", function(e) { var target = (e || window.event).target; if ( target.nodeName.toLowerCase() === "strong" ) { var text = "", node = target.firstChild; while ( node.nodeType === 3 ) { text += node.nodeValue; node = node.nextSibling; } text = text.replace(/(^\s*|\s*$)/g, ""); if ( window.location ) { window.location.href = window.location.href.match(/^(.+?)(\?.*)?$/)[1] + "?" + encodeURIComponent(text); } } }); var li = document.createElement("li"); li.className = bad ? "fail" : "pass"; li.appendChild( b ); li.appendChild( ol ); tests.appendChild( li ); if ( bad ) { var pass = id("qunit-filter-pass"), missing = id("qunit-filter-missing"); if ( pass && missing ) { pass.disabled = null; missing.disabled = null; } } } else { for ( var i = 0; i < config.assertions.length; i++ ) { if ( !config.assertions[i].result ) { config.stats.bad++; } } } }); }, /** * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. */ expect: function expect(asserts) { config.expected = asserts; }, /** * Asserts true. * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); */ ok: function ok(a, msg) { QUnit.log(a, msg); config.assertions.push({ result: !!a, message: msg }); }, /** * Checks that the first two arguments are equal, with an optional message. * Prints out both actual and expected values. * * Prefered to ok( actual == expected, message ) * * @example equals( format("Received {0} bytes.", 2), "Received 2 bytes." ); * * @param Object actual * @param Object expected * @param String message (optional) */ equals: function equals(actual, expected, message) { push(expected == actual, actual, expected, message); }, same: function(a, b, message) { push(QUnit.equiv(a, b), a, b, message); }, start: function start() { // A slight delay, to avoid any current callbacks if ( window.setTimeout ) { window.setTimeout(function() { if ( config.timeout ) { clearTimeout(config.timeout); } config.blocking = false; process(); }, 13); } else { config.blocking = false; process(); } }, stop: function stop(timeout) { config.blocking = true; if ( timeout && window.setTimeout ) { config.timeout = window.setTimeout(function() { QUnit.ok( false, "Test timed out" ); start(); }, timeout); } }, /** * Resets the test setup. Useful for tests that modify the DOM. */ reset: function reset() { if ( window.jQuery ) { jQuery("#main").html( config.fixture ); jQuery.event.global = {}; jQuery.ajaxSettings = extend({}, config.ajaxSettings); } }, /** * Trigger an event on an element. * * @example triggerEvent( document.body, "click" ); * * @param DOMElement elem * @param String type */ triggerEvent: function triggerEvent( elem, type, event ) { if ( document.createEvent ) { event = document.createEvent("MouseEvents"); event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null); elem.dispatchEvent( event ); } else if ( elem.fireEvent ) { elem.fireEvent("on"+type); } }, // Logging callbacks done: function done(failures, total) {}, log: function log(result, message) {}, testLog: function testLog(name) {}, moduleLog: function moduleLog(name) {} }; // Maintain internal state var config = { // Logging the passes and failures stats: { all: 0, bad: 0 }, // The queue of tests to run queue: [], // The log of global variables to check against pollution: [], // queue of test assertions assertions: [], // block until document ready blocking: true }; // Load paramaters (function() { var location = window.location || { search: "", protocol: "file:" }, GETParams = location.search.slice(1).split('&'); for ( var i = 0; i < GETParams.length; i++ ) { GETParams[i] = decodeURIComponent( GETParams[i] ); if ( GETParams[i] === "noglobals" ) { GETParams.splice( i, 1 ); i--; config.noglobals = true; } } // restrict modules/tests by get parameters config.filters = GETParams; // Figure out if we're running the tests from a server or not QUnit.isLocal = !!(location.protocol === 'file:'); })(); // public API as global methods extend(window, QUnit); window.QUnit = QUnit; addEvent(window, "load", function() { var userAgent = id("qunit-userAgent"); if ( userAgent ) { userAgent.innerHTML = navigator.userAgent; } var toolbar = id("qunit-testrunner-toolbar"); if ( toolbar ) { var filter = document.createElement("input"); filter.type = "checkbox"; filter.id = "qunit-filter-pass"; filter.disabled = true; addEvent( filter, "click", function() { var li = document.getElementsByTagName("li"); for ( var i = 0; i < li.length; i++ ) { if ( li[i].className.indexOf("pass") > -1 ) { li[i].style.display = filter.checked ? "none" : "block"; } } }); toolbar.appendChild( filter ); var label = document.createElement("label"); label.setAttribute("for", "filter-pass"); label.innerHTML = "Hide passed tests"; toolbar.appendChild( label ); var missing = document.createElement("input"); missing.type = "checkbox"; missing.id = "qunit-filter-missing"; missing.disabled = true; addEvent( missing, "click", function() { var li = document.getElementsByTagName("li"); for ( var i = 0; i < li.length; i++ ) { if ( li[i].className.indexOf("fail") > -1 && li[i].innerHTML.indexOf('missing test - untested code is broken code') > - 1 ) { li[i].parentNode.parentNode.style.display = missing.checked ? "none" : "block"; } } }); toolbar.appendChild( missing ); label = document.createElement("label"); label.setAttribute("for", "filter-missing"); label.innerHTML = "Hide missing tests (untested code is broken code)"; toolbar.appendChild( label ); } var started = +new Date, main = id('main'); config.blocking = false; if ( main ) { config.fixture = main.innerHTML; } if ( window.jQuery ) { config.ajaxSettings = window.jQuery.ajaxSettings; } synchronize(function() { var banner = id("qunit-banner"), html = ['Tests completed in ', +new Date - started, ' milliseconds.<br/>', '<span class="bad">', config.stats.all - config.stats.bad, '</span> tests of <span class="all">', config.stats.all, '</span> passed, ', config.stats.bad,' failed.'].join(''); if ( banner ) { var result = document.createElement("p"); result.id = "qunit-testresult"; result.className = "result"; result.innerHTML = html; document.body.appendChild( result ); banner.className += " " + (config.stats.bad ? "fail" : "pass"); } QUnit.done( config.stats.bad, config.stats.all ); }); }); function validTest( name ) { var i = config.filters.length, run = false; if ( !i ) { return true; } while ( i-- ) { var filter = config.filters[i], not = filter.charAt(0) == '!'; if ( not ) { filter = filter.slice(1); } if ( name.indexOf(filter) !== -1 ) { return !not; } if ( not ) { run = true; } } return run; } function push(result, actual, expected, message) { message = message || (result ? "okay" : "failed"); QUnit.ok( result, result ? message + ": " + expected : message + ", expected: " + QUnit.jsDump.parse(expected) + " result: " + QUnit.jsDump.parse(actual) ); } function synchronize( callback ) { config.queue.push( callback ); if ( !config.blocking ) { process(); } } function process() { while ( config.queue.length && !config.blocking ) { config.queue.shift()(); } } function saveGlobal() { config.pollution = []; if ( config.noglobals ) { for ( var key in window ) { config.pollution.push(key); } } } function checkPollution( name ) { var old = config.pollution; saveGlobal(); if ( config.pollution.length > old.length ) { ok( false, "Introduced global variable(s): " + diff(old, config.pollution).join(", ") ); config.expected++; } } function diff( clean, dirty ) { var results = []; for ( var i = 0; i < dirty.length; i++ ) { for ( var c = 0; c < clean.length; c++ ) { if ( clean[c] === dirty[i] ) { results.push( clean[c] ); } } } return results; } function fail(message, exception, callback) { if ( typeof console !== "undefined" && console.error && console.warn ) { console.error(message); console.error(exception); console.warn(callback.toString()); } else if ( window.opera && opera.postError ) { opera.postError(message, exception, callback.toString); } } function extend(a, b) { for ( var prop in b ) { a[prop] = b[prop]; } return a; } function addEvent(elem, type, fn) { if ( elem.addEventListener ) { elem.addEventListener( type, fn, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, fn ); } else { fn(); } } function id(name) { return !!(typeof document !== "undefined" && document && document.getElementById) && document.getElementById( name ); } // Test for equality any JavaScript type. // Discussions and reference: http://philrathe.com/articles/equiv // Test suites: http://philrathe.com/tests/equiv // Author: Philippe Rathé <[email protected]> QUnit.equiv = function () { var innerEquiv; // the real equiv function var callers = []; // stack to decide between skip/abort functions // Determine what is o. function hoozit(o) { if (o.constructor === String) { return "string"; } else if (o.constructor === Boolean) { return "boolean"; } else if (o.constructor === Number) { if (isNaN(o)) { return "nan"; } else { return "number"; } } else if (typeof o === "undefined") { return "undefined"; // consider: typeof null === object } else if (o === null) { return "null"; // consider: typeof [] === object } else if (o instanceof Array) { return "array"; // consider: typeof new Date() === object } else if (o instanceof Date) { return "date"; // consider: /./ instanceof Object; // /./ instanceof RegExp; // typeof /./ === "function"; // => false in IE and Opera, // true in FF and Safari } else if (o instanceof RegExp) { return "regexp"; } else if (typeof o === "object") { return "object"; } else if (o instanceof Function) { return "function"; } else { return undefined; } } // Call the o related callback with the given arguments. function bindCallbacks(o, callbacks, args) { var prop = hoozit(o); if (prop) { if (hoozit(callbacks[prop]) === "function") { return callbacks[prop].apply(callbacks, args); } else { return callbacks[prop]; // or undefined } } } var callbacks = function () { // for string, boolean, number and null function useStrictEquality(b, a) { if (b instanceof a.constructor || a instanceof b.constructor) { // to catch short annotaion VS 'new' annotation of a declaration // e.g. var i = 1; // var j = new Number(1); return a == b; } else { return a === b; } } return { "string": useStrictEquality, "boolean": useStrictEquality, "number": useStrictEquality, "null": useStrictEquality, "undefined": useStrictEquality, "nan": function (b) { return isNaN(b); }, "date": function (b, a) { return hoozit(b) === "date" && a.valueOf() === b.valueOf(); }, "regexp": function (b, a) { return hoozit(b) === "regexp" && a.source === b.source && // the regex itself a.global === b.global && // and its modifers (gmi) ... a.ignoreCase === b.ignoreCase && a.multiline === b.multiline; }, // - skip when the property is a method of an instance (OOP) // - abort otherwise, // initial === would have catch identical references anyway "function": function () { var caller = callers[callers.length - 1]; return caller !== Object && typeof caller !== "undefined"; }, "array": function (b, a) { var i; var len; // b could be an object literal here if ( ! (hoozit(b) === "array")) { return false; } len = a.length; if (len !== b.length) { // safe and faster return false; } for (i = 0; i < len; i++) { if ( ! innerEquiv(a[i], b[i])) { return false; } } return true; }, "object": function (b, a) { var i; var eq = true; // unless we can proove it var aProperties = [], bProperties = []; // collection of strings // comparing constructors is more strict than using instanceof if ( a.constructor !== b.constructor) { return false; } // stack constructor before traversing properties callers.push(a.constructor); for (i in a) { // be strict: don't ensures hasOwnProperty and go deep aProperties.push(i); // collect a's properties if ( ! innerEquiv(a[i], b[i])) { eq = false; } } callers.pop(); // unstack, we are done for (i in b) { bProperties.push(i); // collect b's properties } // Ensures identical properties name return eq && innerEquiv(aProperties.sort(), bProperties.sort()); } }; }(); innerEquiv = function () { // can take multiple arguments var args = Array.prototype.slice.apply(arguments); if (args.length < 2) { return true; // end transition } return (function (a, b) { if (a === b) { return true; // catch the most you can } else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || hoozit(a) !== hoozit(b)) { return false; // don't lose time with error prone cases } else { return bindCallbacks(a, callbacks, [b, a]); } // apply transition with (1..n) arguments })(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length -1)); }; return innerEquiv; }(); /** * jsDump * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com * Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php) * Date: 5/15/2008 * @projectDescription Advanced and extensible data dumping for Javascript. * @version 1.0.0 * @author Ariel Flesler * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} */ QUnit.jsDump = (function() { function quote( str ) { return '"' + str.toString().replace(/"/g, '\\"') + '"'; }; function literal( o ) { return o + ''; }; function join( pre, arr, post ) { var s = jsDump.separator(), base = jsDump.indent(), inner = jsDump.indent(1); if ( arr.join ) arr = arr.join( ',' + s + inner ); if ( !arr ) return pre + post; return [ pre, inner + arr, base + post ].join(s); }; function array( arr ) { var i = arr.length, ret = Array(i); this.up(); while ( i-- ) ret[i] = this.parse( arr[i] ); this.down(); return join( '[', ret, ']' ); }; var reName = /^function (\w+)/; var jsDump = { parse:function( obj, type ) { //type is used mostly internally, you can fix a (custom)type in advance var parser = this.parsers[ type || this.typeOf(obj) ]; type = typeof parser; return type == 'function' ? parser.call( this, obj ) : type == 'string' ? parser : this.parsers.error; }, typeOf:function( obj ) { var type = typeof obj, f = 'function';//we'll use it 3 times, save it return type != 'object' && type != f ? type : !obj ? 'null' : obj.exec ? 'regexp' :// some browsers (FF) consider regexps functions obj.getHours ? 'date' : obj.scrollBy ? 'window' : obj.nodeName == '#document' ? 'document' : obj.nodeName ? 'node' : obj.item ? 'nodelist' : // Safari reports nodelists as functions obj.callee ? 'arguments' : obj.call || obj.constructor != Array && //an array would also fall on this hack (obj+'').indexOf(f) != -1 ? f : //IE reports functions like alert, as objects 'length' in obj ? 'array' : type; }, separator:function() { return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? '&nbsp;' : ' '; }, indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing if ( !this.multiline ) return ''; var chr = this.indentChar; if ( this.HTML ) chr = chr.replace(/\t/g,' ').replace(/ /g,'&nbsp;'); return Array( this._depth_ + (extra||0) ).join(chr); }, up:function( a ) { this._depth_ += a || 1; }, down:function( a ) { this._depth_ -= a || 1; }, setParser:function( name, parser ) { this.parsers[name] = parser; }, // The next 3 are exposed so you can use them quote:quote, literal:literal, join:join, // _depth_: 1, // This is the list of parsers, to modify them, use jsDump.setParser parsers:{ window: '[Window]', document: '[Document]', error:'[ERROR]', //when no parser is found, shouldn't happen unknown: '[Unknown]', 'null':'null', undefined:'undefined', 'function':function( fn ) { var ret = 'function', name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE if ( name ) ret += ' ' + name; ret += '('; ret = [ ret, this.parse( fn, 'functionArgs' ), '){'].join(''); return join( ret, this.parse(fn,'functionCode'), '}' ); }, array: array, nodelist: array, arguments: array, object:function( map ) { var ret = [ ]; this.up(); for ( var key in map ) ret.push( this.parse(key,'key') + ': ' + this.parse(map[key]) ); this.down(); return join( '{', ret, '}' ); }, node:function( node ) { var open = this.HTML ? '&lt;' : '<', close = this.HTML ? '&gt;' : '>'; var tag = node.nodeName.toLowerCase(), ret = open + tag; for ( var a in this.DOMAttrs ) { var val = node[this.DOMAttrs[a]]; if ( val ) ret += ' ' + a + '=' + this.parse( val, 'attribute' ); } return ret + close + open + '/' + tag + close; }, functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function var l = fn.length; if ( !l ) return ''; var args = Array(l); while ( l-- ) args[l] = String.fromCharCode(97+l);//97 is 'a' return ' ' + args.join(', ') + ' '; }, key:quote, //object calls it internally, the key part of an item in a map functionCode:'[code]', //function calls it internally, it's the content of the function attribute:quote, //node calls it internally, it's an html attribute value string:quote, date:quote, regexp:literal, //regex number:literal, 'boolean':literal }, DOMAttrs:{//attributes to dump from nodes, name=>realName id:'id', name:'name', 'class':'className' }, HTML:true,//if true, entities are escaped ( <, >, \t, space and \n ) indentChar:' ',//indentation unit multiline:true //if true, items in a collection, are separated by a \n, else just a space. }; return jsDump; })(); })(this);
testrunner.js
/* * QUnit - A JavaScript Unit Testing Framework * * http://docs.jquery.com/QUnit * * Copyright (c) 2009 John Resig, Jörn Zaefferer * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * $Id$ */ (function(window) { var QUnit = { // call on start of module test to prepend name to all tests module: function module(name, lifecycle) { config.currentModule = name; config.moduleLifecycle = lifecycle; synchronize(function() { QUnit.moduleLog( name ); }); }, test: function test(testName, callback) { var name = testName; if ( config.currentModule ) { name = config.currentModule + " module: " + name; } var lifecycle = extend({ setup: function() {}, teardown: function() {} }, config.moduleLifecycle); if ( !validTest(name) ) { return; } var testEnvironment = {}; synchronize(function() { QUnit.testLog( testName ); config.assertions = []; config.expected = null; try { if ( !config.pollution ) { saveGlobal(); } lifecycle.setup.call(testEnvironment); } catch(e) { QUnit.ok( false, "Setup failed on " + name + ": " + e.message ); } }); synchronize(function() { try { callback.call(testEnvironment); } catch(e) { fail("Test " + name + " died, exception and test follows", e, callback); QUnit.ok( false, "Died on test #" + (config.assertions.length + 1) + ": " + e.message ); // else next test will carry the responsibility saveGlobal(); } }); synchronize(function() { try { checkPollution(); lifecycle.teardown.call(testEnvironment); } catch(e) { QUnit.ok( false, "Teardown failed on " + name + ": " + e.message ); } }); synchronize(function() { try { reset(); } catch(e) { fail("reset() failed, following Test " + name + ", exception and reset fn follows", e, reset); } if ( config.expected && config.expected != config.assertions.length ) { QUnit.ok( false, "Expected " + config.expected + " assertions, but " + config.assertions.length + " were run" ); } var good = 0, bad = 0, tests = id("qunit-tests"); config.stats.all += config.assertions.length; if ( tests ) { var ol = document.createElement("ol"); ol.style.display = "none"; for ( var i = 0; i < config.assertions.length; i++ ) { var assertion = config.assertions[i]; var li = document.createElement("li"); li.className = assertion.result ? "pass" : "fail"; li.innerHTML = assertion.message || "(no message)"; ol.appendChild( li ); if ( assertion.result ) { good++; } else { bad++; config.stats.bad++; } } var b = document.createElement("strong"); b.innerHTML = name + " <b style='color:black;'>(<b class='fail'>" + bad + "</b>, <b class='pass'>" + good + "</b>, " + config.assertions.length + ")</b>"; addEvent(b, "click", function() { var next = b.nextSibling, display = next.style.display; next.style.display = display === "none" ? "block" : "none"; }); addEvent(b, "dblclick", function(e) { var target = (e || window.event).target; if ( target.nodeName.toLowerCase() === "strong" ) { var text = "", node = target.firstChild; while ( node.nodeType === 3 ) { text += node.nodeValue; node = node.nextSibling; } text = text.replace(/(^\s*|\s*$)/g, ""); if ( window.location ) { window.location.href = window.location.href.match(/^(.+?)(\?.*)?$/)[1] + "?" + encodeURIComponent(text); } } }); var li = document.createElement("li"); li.className = bad ? "fail" : "pass"; li.appendChild( b ); li.appendChild( ol ); tests.appendChild( li ); if ( bad ) { var pass = id("qunit-filter-pass"), missing = id("qunit-filter-missing"); if ( pass && missing ) { pass.disabled = null; missing.disabled = null; } } } else { for ( var i = 0; i < config.assertions.length; i++ ) { if ( !config.assertions[i].result ) { config.stats.bad++; } } } }); }, /** * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. */ expect: function expect(asserts) { config.expected = asserts; }, /** * Asserts true. * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); */ ok: function ok(a, msg) { QUnit.log(a, msg); config.assertions.push({ result: !!a, message: msg }); }, /** * Checks that the first two arguments are equal, with an optional message. * Prints out both actual and expected values. * * Prefered to ok( actual == expected, message ) * * @example equals( format("Received {0} bytes.", 2), "Received 2 bytes." ); * * @param Object actual * @param Object expected * @param String message (optional) */ equals: function equals(actual, expected, message) { push(expected == actual, actual, expected, message); }, same: function(a, b, message) { push(equiv(a, b), a, b, message); }, start: function start() { // A slight delay, to avoid any current callbacks if ( window.setTimeout ) { window.setTimeout(function() { if ( config.timeout ) { clearTimeout(config.timeout); } config.blocking = false; process(); }, 13); } else { config.blocking = false; process(); } }, stop: function stop(timeout) { config.blocking = true; if ( timeout && window.setTimeout ) { config.timeout = window.setTimeout(function() { QUnit.ok( false, "Test timed out" ); start(); }, timeout); } }, /** * Resets the test setup. Useful for tests that modify the DOM. */ reset: function reset() { if ( window.jQuery ) { jQuery("#main").html( config.fixture ); jQuery.event.global = {}; jQuery.ajaxSettings = extend({}, config.ajaxSettings); } }, /** * Trigger an event on an element. * * @example triggerEvent( document.body, "click" ); * * @param DOMElement elem * @param String type */ triggerEvent: function triggerEvent( elem, type, event ) { if ( document.createEvent ) { event = document.createEvent("MouseEvents"); event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null); elem.dispatchEvent( event ); } else if ( elem.fireEvent ) { elem.fireEvent("on"+type); } }, // Expose the equiv method equiv: equiv, // Logging callbacks done: function done(failures, total) {}, log: function log(result, message) {}, testLog: function testLog(name) {}, moduleLog: function moduleLog(name) {} }; // Maintain internal state var config = { // Logging the passes and failures stats: { all: 0, bad: 0 }, // The queue of tests to run queue: [], // The log of global variables to check against pollution: [], // queue of test assertions assertions: [], // block until document ready blocking: true }; // Load paramaters (function() { var location = window.location || { search: "", protocol: "file:" }, GETParams = location.search.slice(1).split('&'); for ( var i = 0; i < GETParams.length; i++ ) { GETParams[i] = decodeURIComponent( GETParams[i] ); if ( GETParams[i] === "noglobals" ) { GETParams.splice( i, 1 ); i--; config.noglobals = true; } } // restrict modules/tests by get parameters config.filters = GETParams; // Figure out if we're running the tests from a server or not QUnit.isLocal = !!(location.protocol === 'file:'); })(); // public API as global methods extend(window, QUnit); window.QUnit = QUnit; addEvent(window, "load", function() { var userAgent = id("qunit-userAgent"); if ( userAgent ) { userAgent.innerHTML = navigator.userAgent; } var toolbar = id("qunit-testrunner-toolbar"); if ( toolbar ) { var filter = document.createElement("input"); filter.type = "checkbox"; filter.id = "qunit-filter-pass"; filter.disabled = true; addEvent( filter, "click", function() { var li = document.getElementsByTagName("li"); for ( var i = 0; i < li.length; i++ ) { if ( li[i].className.indexOf("pass") > -1 ) { li[i].style.display = filter.checked ? "none" : "block"; } } }); toolbar.appendChild( filter ); var label = document.createElement("label"); label.setAttribute("for", "filter-pass"); label.innerHTML = "Hide passed tests"; toolbar.appendChild( label ); var missing = document.createElement("input"); missing.type = "checkbox"; missing.id = "qunit-filter-missing"; missing.disabled = true; addEvent( missing, "click", function() { var li = document.getElementsByTagName("li"); for ( var i = 0; i < li.length; i++ ) { if ( li[i].className.indexOf("fail") > -1 && li[i].innerHTML.indexOf('missing test - untested code is broken code') > - 1 ) { li[i].parentNode.parentNode.style.display = missing.checked ? "none" : "block"; } } }); toolbar.appendChild( missing ); label = document.createElement("label"); label.setAttribute("for", "filter-missing"); label.innerHTML = "Hide missing tests (untested code is broken code)"; toolbar.appendChild( label ); } var started = +new Date, main = id('main'); config.blocking = false; if ( main ) { config.fixture = main.innerHTML; } if ( window.jQuery ) { config.ajaxSettings = window.jQuery.ajaxSettings; } synchronize(function() { var banner = id("qunit-banner"), html = ['Tests completed in ', +new Date - started, ' milliseconds.<br/>', '<span class="bad">', config.stats.all - config.stats.bad, '</span> tests of <span class="all">', config.stats.all, '</span> passed, ', config.stats.bad,' failed.'].join(''); if ( banner ) { var result = document.createElement("p"); result.id = "qunit-testresult"; result.className = "result"; result.innerHTML = html; document.body.appendChild( result ); banner.className += " " + (config.stats.bad ? "fail" : "pass"); } QUnit.done( config.stats.bad, config.stats.all ); }); }); function validTest( name ) { var i = config.filters.length, run = false; if ( !i ) { return true; } while ( i-- ) { var filter = config.filters[i], not = filter.charAt(0) == '!'; if ( not ) { filter = filter.slice(1); } if ( name.indexOf(filter) !== -1 ) { return !not; } if ( not ) { run = true; } } return run; } function push(result, actual, expected, message) { message = message || (result ? "okay" : "failed"); QUnit.ok( result, result ? message + ": " + expected : message + ", expected: " + jsDump.parse(expected) + " result: " + jsDump.parse(actual) ); } function synchronize( callback ) { config.queue.push( callback ); if ( !config.blocking ) { process(); } } function process() { while ( config.queue.length && !config.blocking ) { config.queue.shift()(); } } function saveGlobal() { config.pollution = []; if ( config.noglobals ) { for ( var key in window ) { config.pollution.push(key); } } } function checkPollution( name ) { var old = config.pollution; saveGlobal(); if ( config.pollution.length > old.length ) { ok( false, "Introduced global variable(s): " + diff(old, config.pollution).join(", ") ); config.expected++; } } function diff( clean, dirty ) { var results = []; for ( var i = 0; i < dirty.length; i++ ) { for ( var c = 0; c < clean.length; c++ ) { if ( clean[c] === dirty[i] ) { results.push( clean[c] ); } } } return results; } function fail(message, exception, callback) { if ( typeof console !== "undefined" && console.error && console.warn ) { console.error(message); console.error(exception); console.warn(callback.toString()); } else if ( window.opera && opera.postError ) { opera.postError(message, exception, callback.toString); } } function extend(a, b) { for ( var prop in b ) { a[prop] = b[prop]; } return a; } function addEvent(elem, type, fn) { if ( elem.addEventListener ) { elem.addEventListener( type, fn, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, fn ); } else { fn(); } } function id(name) { return !!(typeof document !== "undefined" && document && document.getElementById) && document.getElementById( name ); } // Test for equality any JavaScript type. // Discussions and reference: http://philrathe.com/articles/equiv // Test suites: http://philrathe.com/tests/equiv // Author: Philippe Rathé <[email protected]> var equiv = function () { var innerEquiv; // the real equiv function var callers = []; // stack to decide between skip/abort functions // Determine what is o. function hoozit(o) { if (o.constructor === String) { return "string"; } else if (o.constructor === Boolean) { return "boolean"; } else if (o.constructor === Number) { if (isNaN(o)) { return "nan"; } else { return "number"; } } else if (typeof o === "undefined") { return "undefined"; // consider: typeof null === object } else if (o === null) { return "null"; // consider: typeof [] === object } else if (o instanceof Array) { return "array"; // consider: typeof new Date() === object } else if (o instanceof Date) { return "date"; // consider: /./ instanceof Object; // /./ instanceof RegExp; // typeof /./ === "function"; // => false in IE and Opera, // true in FF and Safari } else if (o instanceof RegExp) { return "regexp"; } else if (typeof o === "object") { return "object"; } else if (o instanceof Function) { return "function"; } else { return undefined; } } // Call the o related callback with the given arguments. function bindCallbacks(o, callbacks, args) { var prop = hoozit(o); if (prop) { if (hoozit(callbacks[prop]) === "function") { return callbacks[prop].apply(callbacks, args); } else { return callbacks[prop]; // or undefined } } } var callbacks = function () { // for string, boolean, number and null function useStrictEquality(b, a) { if (b instanceof a.constructor || a instanceof b.constructor) { // to catch short annotaion VS 'new' annotation of a declaration // e.g. var i = 1; // var j = new Number(1); return a == b; } else { return a === b; } } return { "string": useStrictEquality, "boolean": useStrictEquality, "number": useStrictEquality, "null": useStrictEquality, "undefined": useStrictEquality, "nan": function (b) { return isNaN(b); }, "date": function (b, a) { return hoozit(b) === "date" && a.valueOf() === b.valueOf(); }, "regexp": function (b, a) { return hoozit(b) === "regexp" && a.source === b.source && // the regex itself a.global === b.global && // and its modifers (gmi) ... a.ignoreCase === b.ignoreCase && a.multiline === b.multiline; }, // - skip when the property is a method of an instance (OOP) // - abort otherwise, // initial === would have catch identical references anyway "function": function () { var caller = callers[callers.length - 1]; return caller !== Object && typeof caller !== "undefined"; }, "array": function (b, a) { var i; var len; // b could be an object literal here if ( ! (hoozit(b) === "array")) { return false; } len = a.length; if (len !== b.length) { // safe and faster return false; } for (i = 0; i < len; i++) { if ( ! innerEquiv(a[i], b[i])) { return false; } } return true; }, "object": function (b, a) { var i; var eq = true; // unless we can proove it var aProperties = [], bProperties = []; // collection of strings // comparing constructors is more strict than using instanceof if ( a.constructor !== b.constructor) { return false; } // stack constructor before traversing properties callers.push(a.constructor); for (i in a) { // be strict: don't ensures hasOwnProperty and go deep aProperties.push(i); // collect a's properties if ( ! innerEquiv(a[i], b[i])) { eq = false; } } callers.pop(); // unstack, we are done for (i in b) { bProperties.push(i); // collect b's properties } // Ensures identical properties name return eq && innerEquiv(aProperties.sort(), bProperties.sort()); } }; }(); innerEquiv = function () { // can take multiple arguments var args = Array.prototype.slice.apply(arguments); if (args.length < 2) { return true; // end transition } return (function (a, b) { if (a === b) { return true; // catch the most you can } else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || hoozit(a) !== hoozit(b)) { return false; // don't lose time with error prone cases } else { return bindCallbacks(a, callbacks, [b, a]); } // apply transition with (1..n) arguments })(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length -1)); }; return innerEquiv; }(); /** * jsDump * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com * Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php) * Date: 5/15/2008 * @projectDescription Advanced and extensible data dumping for Javascript. * @version 1.0.0 * @author Ariel Flesler * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} */ var jsDump = (function() { function quote( str ) { return '"' + str.toString().replace(/"/g, '\\"') + '"'; }; function literal( o ) { return o + ''; }; function join( pre, arr, post ) { var s = jsDump.separator(), base = jsDump.indent(), inner = jsDump.indent(1); if ( arr.join ) arr = arr.join( ',' + s + inner ); if ( !arr ) return pre + post; return [ pre, inner + arr, base + post ].join(s); }; function array( arr ) { var i = arr.length, ret = Array(i); this.up(); while ( i-- ) ret[i] = this.parse( arr[i] ); this.down(); return join( '[', ret, ']' ); }; var reName = /^function (\w+)/; var jsDump = { parse:function( obj, type ) { //type is used mostly internally, you can fix a (custom)type in advance var parser = this.parsers[ type || this.typeOf(obj) ]; type = typeof parser; return type == 'function' ? parser.call( this, obj ) : type == 'string' ? parser : this.parsers.error; }, typeOf:function( obj ) { var type = typeof obj, f = 'function';//we'll use it 3 times, save it return type != 'object' && type != f ? type : !obj ? 'null' : obj.exec ? 'regexp' :// some browsers (FF) consider regexps functions obj.getHours ? 'date' : obj.scrollBy ? 'window' : obj.nodeName == '#document' ? 'document' : obj.nodeName ? 'node' : obj.item ? 'nodelist' : // Safari reports nodelists as functions obj.callee ? 'arguments' : obj.call || obj.constructor != Array && //an array would also fall on this hack (obj+'').indexOf(f) != -1 ? f : //IE reports functions like alert, as objects 'length' in obj ? 'array' : type; }, separator:function() { return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? '&nbsp;' : ' '; }, indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing if ( !this.multiline ) return ''; var chr = this.indentChar; if ( this.HTML ) chr = chr.replace(/\t/g,' ').replace(/ /g,'&nbsp;'); return Array( this._depth_ + (extra||0) ).join(chr); }, up:function( a ) { this._depth_ += a || 1; }, down:function( a ) { this._depth_ -= a || 1; }, setParser:function( name, parser ) { this.parsers[name] = parser; }, // The next 3 are exposed so you can use them quote:quote, literal:literal, join:join, // _depth_: 1, // This is the list of parsers, to modify them, use jsDump.setParser parsers:{ window: '[Window]', document: '[Document]', error:'[ERROR]', //when no parser is found, shouldn't happen unknown: '[Unknown]', 'null':'null', undefined:'undefined', 'function':function( fn ) { var ret = 'function', name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE if ( name ) ret += ' ' + name; ret += '('; ret = [ ret, this.parse( fn, 'functionArgs' ), '){'].join(''); return join( ret, this.parse(fn,'functionCode'), '}' ); }, array: array, nodelist: array, arguments: array, object:function( map ) { var ret = [ ]; this.up(); for ( var key in map ) ret.push( this.parse(key,'key') + ': ' + this.parse(map[key]) ); this.down(); return join( '{', ret, '}' ); }, node:function( node ) { var open = this.HTML ? '&lt;' : '<', close = this.HTML ? '&gt;' : '>'; var tag = node.nodeName.toLowerCase(), ret = open + tag; for ( var a in this.DOMAttrs ) { var val = node[this.DOMAttrs[a]]; if ( val ) ret += ' ' + a + '=' + this.parse( val, 'attribute' ); } return ret + close + open + '/' + tag + close; }, functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function var l = fn.length; if ( !l ) return ''; var args = Array(l); while ( l-- ) args[l] = String.fromCharCode(97+l);//97 is 'a' return ' ' + args.join(', ') + ' '; }, key:quote, //object calls it internally, the key part of an item in a map functionCode:'[code]', //function calls it internally, it's the content of the function attribute:quote, //node calls it internally, it's an html attribute value string:quote, date:quote, regexp:literal, //regex number:literal, 'boolean':literal }, DOMAttrs:{//attributes to dump from nodes, name=>realName id:'id', name:'name', 'class':'className' }, HTML:true,//if true, entities are escaped ( <, >, \t, space and \n ) indentChar:' ',//indentation unit multiline:true //if true, items in a collection, are separated by a \n, else just a space. }; return jsDump; })(); })(this);
Expose QUnit.equiv and QUnit.jsDump in QUnit.
testrunner.js
Expose QUnit.equiv and QUnit.jsDump in QUnit.
<ide><path>estrunner.js <ide> }, <ide> <ide> same: function(a, b, message) { <del> push(equiv(a, b), a, b, message); <add> push(QUnit.equiv(a, b), a, b, message); <ide> }, <ide> <ide> start: function start() { <ide> elem.fireEvent("on"+type); <ide> } <ide> }, <del> <del> // Expose the equiv method <del> equiv: equiv, <ide> <ide> // Logging callbacks <ide> done: function done(failures, total) {}, <ide> <ide> function push(result, actual, expected, message) { <ide> message = message || (result ? "okay" : "failed"); <del> QUnit.ok( result, result ? message + ": " + expected : message + ", expected: " + jsDump.parse(expected) + " result: " + jsDump.parse(actual) ); <add> QUnit.ok( result, result ? message + ": " + expected : message + ", expected: " + QUnit.jsDump.parse(expected) + " result: " + QUnit.jsDump.parse(actual) ); <ide> } <ide> <ide> function synchronize( callback ) { <ide> // Discussions and reference: http://philrathe.com/articles/equiv <ide> // Test suites: http://philrathe.com/tests/equiv <ide> // Author: Philippe Rathé <[email protected]> <del>var equiv = function () { <add>QUnit.equiv = function () { <ide> <ide> var innerEquiv; // the real equiv function <ide> var callers = []; // stack to decide between skip/abort functions <ide> * @author Ariel Flesler <ide> * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} <ide> */ <del>var jsDump = (function() { <add>QUnit.jsDump = (function() { <ide> function quote( str ) { <ide> return '"' + str.toString().replace(/"/g, '\\"') + '"'; <ide> };
JavaScript
bsd-3-clause
adfebf4de90fb9a4c7a7eaad6bcbc86988475954
0
GoogleChromeLabs/confluence,GoogleChromeLabs/confluence,GoogleChromeLabs/confluence
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. 'use strict'; require('./api_velocity_data.es6'); foam.CLASS({ name: 'ApiVelocity', package: 'org.chromium.apis.web', documentation: `ApiVelocity is a class that computes the API Velocity metrics from browserApiDAO. It shows the total number of APIs, new APIs and remvoed APIs for each version of browser.`, requires: [ 'org.chromium.apis.web.Browser', 'org.chromium.apis.web.WebInterface', 'org.chromium.apis.web.BrowserWebInterfaceJunction', 'org.chromium.apis.web.ApiVelocityData', 'foam.mlang.ExpressionsSingleton', 'foam.dao.ArraySink', 'foam.dao.EasyDAO', ], properties: [ { class: 'FObjectProperty', of: 'foam.dao.DAO', name: 'browserApiDAO', documentation: `A DAO containing junction objects of Browser and WebInterface.`, required: true, final: true, }, { class: 'FObjectProperty', of: 'foam.dao.DAO', name: 'browserDAO', documentation: `A DAO containing each browsers' version and environment metadata.`, required: true, final: true, }, { class: 'FObjectProperty', of: 'foam.dao.DAO', name: 'interfaceDAO', documentation: `A DAO containing all interface and API pairs.`, required: true, final: true, }, { class: 'FObjectProperty', of: 'foam.dao.DAO', name: 'apiVelocityDAO', documentation: `This is a DAO that contains ApiVelocityData.`, final: true, factory: function() { return this.EasyDAO.create({ name: 'apiVelocityDAO', of: this.ApiVelocityData, daoType: 'MDAO', }); }, }, { name: 'mlang', documentation: 'The mlang expressions singleton.', factory: function() { return this.ExpressionsSingleton.create(); }, }, ], methods: [ { name: 'init', documentation: `The init function computes the API Velocity for each major browsers contained in the given browserApiDAO and store them in apiVelocityDAO.`, code: function() { this.browserDAO.orderBy(this.Browser.RELEASE_DATE) .select(this.mlang.GROUP_BY( this.Browser.BROWSER_NAME, this.mlang.GROUP_BY( this.Browser.OS_NAME, this.ArraySink.create()))) .then((groups) => { for (let i = 0; i < groups.groupKeys.length; i++) { let browserName = groups.groupKeys[i]; // Use Windows platform if this browser is available in Windows. // Use whatever available if Windows is not supported. let browserOS = 'Windows'; if (!groups.groups[browserName].groups.hasOwnProperty( browserOS)) { browserOS = groups.groups[browserName].groupKeys[0]; } let browsers = groups.groups[browserName].groups[browserOS].a; let prevIfaceSelect = null; for (let i = 0; i < browsers.length; i++) { let browser = browsers[i]; // Continue when no previous release is found. if (i === 0) { prevIfaceSelect = browser.interfaces.select(); prevIfaceSelect.then((arraySink) => { this.apiVelocityDAO.put(this.ApiVelocityData.create({ releaseDate: browser.releaseDate, browserName: browser.browserName, prevBrowser: null, currBrowser: browser, totalApis: arraySink.a.length, newApis: 0, removedApis: 0, })); }); continue; } // Reuse selected data by passing promise to next iteration. let tempPromise = prevIfaceSelect; prevIfaceSelect = browser.interfaces.select(); Promise.all([tempPromise, prevIfaceSelect]).then((result) => { // prevIfaceDict initialized as all previous, but pared // down when found in curIfaces, yielding only removed // interfaces. let prevIfaces = result[0].a; let currIfaces = result[1].a; let prevIfaceDict = {}; let newApis = 0; let removedApis = 0; for (let j = 0; j < prevIfaces.length; j++) { prevIfaceDict[prevIfaces[j].interfaceKey] = true; } for (let j = 0; j < currIfaces.length; j++) { let ifaceKey = currIfaces[j].interfaceKey; if (prevIfaceDict[ifaceKey]) { delete prevIfaceDict[ifaceKey]; } else { // This interface exists in current version // not in previous version. newApis++; } } removedApis = Object.keys(prevIfaceDict).length; this.apiVelocityDAO.put(this.ApiVelocityData.create({ releaseDate: browser.releaseDate, browserName: browser.browserName, prevBrowser: browsers[i - 1], currBrowser: browser, totalApis: currIfaces.length, newApis, removedApis, })); }); } } }); }, }, ], });
lib/confluence/api_velocity.es6.js
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. 'use strict'; require('./api_velocity_data.es6'); foam.CLASS({ name: 'ApiVelocity', package: 'org.chromium.apis.web', documentation: `ApiVelocity is a class that computes the API Velocity metrics from browserApiDAO. It shows the total number of APIs, new APIs and remvoed APIs for each version of browser.`, requires: [ 'org.chromium.apis.web.Browser', 'org.chromium.apis.web.WebInterface', 'org.chromium.apis.web.BrowserWebInterfaceJunction', 'org.chromium.apis.web.ApiVelocityData', 'foam.mlang.ExpressionsSingleton', 'foam.dao.ArraySink', 'foam.dao.EasyDAO', ], properties: [ { class: 'FObjectProperty', of: 'foam.dao.DAO', name: 'browserApiDAO', documentation: `A DAO containing junction objects of Browser and WebInterface.`, required: true, final: true, }, { class: 'FObjectProperty', of: 'foam.dao.DAO', name: 'browserDAO', documentation: `A DAO containing each browsers' version and environment metadata.`, required: true, final: true, }, { class: 'FObjectProperty', of: 'foam.dao.DAO', name: 'interfaceDAO', documentation: `A DAO containing all interface and API pairs.`, required: true, final: true, }, { class: 'FObjectProperty', of: 'foam.dao.DAO', name: 'apiVelocityDAO', documentation: `This is a DAO that contains ApiVelocityData.`, final: true, factory: function() { return this.EasyDAO.create({ name: 'apiVelocityDAO', of: this.ApiVelocityData, daoType: 'MDAO', }); }, }, { name: 'mlang', documentation: 'The mlang expressions singleton.', factory: function() { return this.ExpressionsSingleton.create(); }, }, ], methods: [ { name: 'init', documentation: `The init function computes the API Velocity for each major browsers contained in the given browserApiDAO and store them in apiVelocityDAO.`, code: function() { this.browserDAO.orderBy(this.Browser.RELEASE_DATE) .select(this.mlang.GROUP_BY( this.Browser.BROWSER_NAME, this.mlang.GROUP_BY( this.Browser.OS_NAME, this.ArraySink.create()))) .then((groups) => { for (let i = 0; i < groups.groupKeys.length; i++) { let browserName = groups.groupKeys[i]; // Use Windows platform if this browser is available in Windows. // Use whatever available if Windows is not supported. let browserOS = 'Windows'; if (!groups.groups[browserName].groups.hasOwnProperty( browserOS)) { browserOS = groups.groups[browserName].groupKeys[0]; } let browsers = groups.groups[browserName].groups[browserOS].a; let prevIfaceSelect = null; for (let i = 0; i < browsers.length; i++) { let browser = browsers[i]; // Continue when no previous release is found. if (i === 0) { prevIfaceSelect = browser.interfaces.select(); prevIfaceSelect.then((arraySink) => { this.apiVelocityDAO.put(this.ApiVelocityData.create({ releaseDate: browser.releaseDate, browserName: browser.browserName, prevBrowser: null, currBrowser: browser, totalApis: arraySink.a.length, newApis: 0, removedApis: 0, })); }); continue; } let tempPromise = prevIfaceSelect; prevIfaceSelect = browser.interfaces.select() Promise.all(tempPromise, prevIfaceSelect.then((result) => { // prevIfaceDict initialized as all previous, but pared // down when found in curIfaces, yielding only removed // interfaces. let prevIfaces = result[0].a; let currIfaces = result[1].a; let prevIfaceDict = {}; let newApis = 0; let removedApis = 0; for (let j = 0; j < prevIfaces.length; j++) { prevIfaceDict[prevIfaces[j].interfaceKey] = true; } for (let j = 0; j < currIfaces.length; j++) { let ifaceKey = currIfaces[j].interfaceKey; if (prevIfaceDict[ifaceKey]) { delete prevIfaceDict[ifaceKey]; } else { // This interface exists in current version // not in previous version. newApis++; } } removedApis = Object.keys(prevIfaceDict).length; this.apiVelocityDAO.put(this.ApiVelocityData.create({ releaseDate: browser.releaseDate, browserName: browser.browserName, prevBrowser: browsers[i - 1], currBrowser: browser, totalApis: currIfaces.length, newApis, removedApis, })); }); } } }); }, }, ], });
Nit: documentation.
lib/confluence/api_velocity.es6.js
Nit: documentation.
<ide><path>ib/confluence/api_velocity.es6.js <ide> }); <ide> continue; <ide> } <add> // Reuse selected data by passing promise to next iteration. <ide> let tempPromise = prevIfaceSelect; <del> prevIfaceSelect = browser.interfaces.select() <del> Promise.all(tempPromise, prevIfaceSelect.then((result) => { <add> prevIfaceSelect = browser.interfaces.select(); <add> Promise.all([tempPromise, prevIfaceSelect]).then((result) => { <ide> // prevIfaceDict initialized as all previous, but pared <ide> // down when found in curIfaces, yielding only removed <ide> // interfaces.
Java
apache-2.0
d93153190053faa0b50a15cc788458a77659a65d
0
sreedishps/pintail,InMobi/pintail,sreedishps/pintail,InMobi/pintail,rajubairishetti/pintail,rajubairishetti/pintail
package com.inmobi.messaging.util; import com.inmobi.messaging.ClientConfig; @SuppressWarnings("rawtypes") public abstract class TopicSelector<T> { private static final String CLASS_SUFFIX = ".selector.class"; /* * Selects the topic to publish for a given message. */ public abstract String selectTopic(T message); /* * Creates the TopicSelector for a given logical topic. If no topic selector * set for the class then return the default selector which selects same * topic as the logical topic. */ public static TopicSelector create(String logicalTopic) { return create(logicalTopic, new ClientConfig()); } @SuppressWarnings("unchecked") public static TopicSelector create(String logicalTopic, ClientConfig conf) { String name = conf.getString(logicalTopic + CLASS_SUFFIX); TopicSelector selector; if (name != null) { Class<TopicSelector> claz; try { claz = (Class<TopicSelector>) Class.forName(name); selector = claz.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } else { selector = new DefaultTopicSelector(); } selector.init(logicalTopic, conf); return selector; } protected void init(String logicalTopic, ClientConfig conf) { } public void close() { } public static void setSelectorClass(ClientConfig conf, String logicalTopic, String classname) { conf.set(logicalTopic + CLASS_SUFFIX, classname); } /* * */ public static class DefaultTopicSelector extends TopicSelector { private String topic; protected ClientConfig conf; public DefaultTopicSelector() { } @Override protected void init(String logicalTopic, ClientConfig conf) { this.topic = logicalTopic; this.conf = conf; } @Override public String selectTopic(Object object) { return topic; } } }
messaging-client-core/src/main/java/com/inmobi/messaging/util/TopicSelector.java
package com.inmobi.messaging.util; import com.inmobi.messaging.ClientConfig; public abstract class TopicSelector<T> { private static final String CLASS_SUFFIX = ".selector.class"; /* * Selects the topic to publish for a given message. */ public abstract String selectTopic(T message); /* * Creates the TopicSelector for a given logical topic. If no topic selector * set for the class then return the default selector which selects same * topic as the logical topic. */ public static TopicSelector create(String logicalTopic) { return create(logicalTopic, new ClientConfig()); } public static TopicSelector create(String logicalTopic, ClientConfig conf) { String name = conf.getString(logicalTopic + CLASS_SUFFIX); TopicSelector selector; if (name != null) { Class<TopicSelector> claz; try { claz = (Class<TopicSelector>) Class.forName(name); selector = claz.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } else { selector = new DefaultTopicSelector(); } selector.init(logicalTopic, conf); return selector; } protected void init(String logicalTopic, ClientConfig conf) { } public void close() { } public static void setSelectorClass(ClientConfig conf, String logicalTopic, String classname) { conf.set(logicalTopic + CLASS_SUFFIX, classname); } /* * */ public static class DefaultTopicSelector extends TopicSelector { private String topic; private ClientConfig conf; public DefaultTopicSelector() { } @Override protected void init(String logicalTopic, ClientConfig conf) { this.topic = logicalTopic; this.conf = conf; } @Override public String selectTopic(Object object) { return topic; } } }
Suppress warnings in TopicSelector
messaging-client-core/src/main/java/com/inmobi/messaging/util/TopicSelector.java
Suppress warnings in TopicSelector
<ide><path>essaging-client-core/src/main/java/com/inmobi/messaging/util/TopicSelector.java <ide> <ide> import com.inmobi.messaging.ClientConfig; <ide> <add>@SuppressWarnings("rawtypes") <ide> public abstract class TopicSelector<T> { <ide> <ide> private static final String CLASS_SUFFIX = ".selector.class"; <ide> return create(logicalTopic, new ClientConfig()); <ide> } <ide> <add> @SuppressWarnings("unchecked") <ide> public static TopicSelector create(String logicalTopic, ClientConfig conf) { <ide> String name = conf.getString(logicalTopic + CLASS_SUFFIX); <ide> TopicSelector selector; <ide> */ <ide> public static class DefaultTopicSelector extends TopicSelector { <ide> private String topic; <del> private ClientConfig conf; <add> protected ClientConfig conf; <ide> <ide> public DefaultTopicSelector() { <ide> }
JavaScript
mit
cf760a1a2d8d1fef7b1ab7107c433d16e916567f
0
ilios/common,ilios/common
import RSVP from 'rsvp'; import EmberObject from '@ember/object'; import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render, settled, click, find, findAll, fillIn, } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; import { padStart } from 'ember-pad/utils/pad'; import moment from 'moment'; import { openDatepicker } from 'ember-pikaday/helpers/pikaday'; const { resolve } = RSVP; module('Integration | Component | offering form', function(hooks) { setupRenderingTest(hooks); test('room input does not show by default', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} />`); assert.dom('.room').doesNotExist(); }); test('room input shows up when requested', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} @showRoom={{true}} />`); assert.dom('.room').exists({ count: 1 }); }); test('room validation errors do not show up initially', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} @showRoom={{true}} />`); const item = '.room'; const error = `${item} .validation-error-message`; assert.dom(error).doesNotExist(); }); test('room validation errors show up when typing', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} @showRoom={{true}} />`); const item = '.room'; const input = `${item} input`; const error = `${item} .validation-error-message`; const save = '.buttons .done'; await fillIn(input, padStart('a', 300, 'a')); await click(save); assert.dom(error).exists({ count: 1 }); }); test('recurring options does not show by default', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} />`); assert.dom('.make-recurring').doesNotExist(); }); test('recurring options shows up when requested', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} @showMakeRecurring={{true}} />`); assert.dom('.make-recurring').exists({ count: 1 }); }); test('recurring options has all the days of the week', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} @showMakeRecurring={{true}} />`); const sunday = '[data-test-recurring-day-label="0"]'; const monday = '[data-test-recurring-day-label="1"]'; const tuesday = '[data-test-recurring-day-label="2"]'; const wednesday = '[data-test-recurring-day-label="3"]'; const thursday = '[data-test-recurring-day-label="4"]'; const friday = '[data-test-recurring-day-label="5"]'; const saturday = '[data-test-recurring-day-label="6"]'; const toggle = '.make-recurring [data-test-toggle-yesno] [data-test-handle]'; await click(toggle); assert.dom(sunday).hasText('Sunday'); assert.dom(monday).hasText('Monday'); assert.dom(tuesday).hasText('Tuesday'); assert.dom(wednesday).hasText('Wednesday'); assert.dom(thursday).hasText('Thursday'); assert.dom(friday).hasText('Friday'); assert.dom(saturday).hasText('Saturday'); }); test('recurring numberOfWeeks validation errors do not show up initially', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} @showMakeRecurring={{true}} />`); const item = '.make-recurring-input-container'; const error = `${item} .validation-error-message`; const toggle = '.make-recurring [data-test-toggle-yesno] [data-test-handle]'; await click(toggle); assert.dom(error).doesNotExist(); }); test('recurring numberOfWeeks validation errors show up when saving', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} @showMakeRecurring={{true}} />`); const item = '.make-recurring-input-container'; const error = `${item} .validation-error-message`; const input = `${item} input`; const toggle = '.make-recurring [data-test-toggle-yesno] [data-test-handle]'; await click(toggle); const save = '.buttons .done'; await fillIn(input, 0); await click(save); assert.dom(error).exists({ count: 1 }); }); test('recurring default day is disabled and checked', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} @showMakeRecurring={{true}} />`); const inputs = '.make-recurring-days input'; const dayToday = moment().day(); const toggle = '.make-recurring [data-test-toggle-yesno] [data-test-handle]'; await click(toggle); const checkbox = findAll(inputs)[dayToday]; assert.ok(checkbox.checked); assert.ok(checkbox.disabled); }); test('instructor manager does not show by default', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} />`); assert.dom('.instructors').doesNotExist(); }); test('instructor manager shows up when requested', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} @showInstructors={{true}} />`); assert.dom('.instructors').exists({ count: 1 }); }); test('before course startDate default initial startDate falls on course start date', async function(assert) { const courseStartDate = moment().add(2, 'days'); const courseEndDate = moment().add(4, 'days'); this.set('courseStartDate', courseStartDate); this.set('courseEndDate', courseEndDate); await render(hbs`<OfferingForm @close={{noop}} @courseStartDate={{this.courseStartDate}} @courseEndDate={{this.courseEndDate}} />`); const startDate = '.start-date input'; const interactor = openDatepicker(find(startDate)); assert.equal( interactor.selectedYear(), courseStartDate.year(), 'Selected year initialized to course start date year.' ); assert.equal( interactor.selectedMonth(), courseStartDate.month(), 'Selected month initialized to course start date month.' ); assert.equal( interactor.selectedDay(), courseStartDate.date(), 'Selected day initialized to course start date day.' ); }); test('after course endDate default initial startDate falls on course end date', async function(assert) { const courseStartDate = moment().subtract(4, 'days'); const courseEndDate = moment().subtract(2, 'days'); this.set('courseStartDate', courseStartDate); this.set('courseEndDate', courseEndDate); await render(hbs`<OfferingForm @close={{noop}} @courseStartDate={{this.courseStartDate}} @courseEndDate={{this.courseEndDate}} />`); const startDate = '.start-date input'; const interactor = openDatepicker(find(startDate)); assert.equal( interactor.selectedYear(), courseEndDate.year(), 'Selected year initialized to course start date year.' ); assert.equal( interactor.selectedMonth(), courseEndDate.month(), 'Selected month initialized to course start date month.' ); assert.equal( interactor.selectedDay(), courseEndDate.date(), 'Selected day initialized to course start date day.' ); }); test('between course startDate and endDate default initial startDate falls on today', async function(assert) { const courseStartDate = moment().subtract(4, 'days'); const courseEndDate = moment().add(4, 'days'); const today = moment(); this.set('courseStartDate', courseStartDate); this.set('courseEndDate', courseEndDate); await render(hbs`<OfferingForm @close={{noop}} @courseStartDate={{this.courseStartDate}} @courseEndDate={{this.courseEndDate}} />`); const startDate = '.start-date input'; const interactor = openDatepicker(find(startDate)); assert.equal( interactor.selectedYear(), today.year(), 'Selected year initialized to course start date year.' ); assert.equal( interactor.selectedMonth(), today.month(), 'Selected month initialized to course start date month.' ); assert.equal( interactor.selectedDay(), today.date(), 'Selected day initialized to course start date day.' ); }); test('close sends close', async function(assert) { assert.expect(1); this.set('close', ()=>{ assert.ok(true); }); const closeButton = '.buttons .cancel'; await render(hbs`<OfferingForm @close={{this.close}} />`); await click(closeButton); }); test('save not recurring', async function(assert) { assert.expect(7); this.set('save', (startDate, endDate, room, learners, learnerGroups, instructorGroups, instructors)=>{ assert.equal(moment(startDate).format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')); assert.equal(moment(endDate).format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')); assert.equal(room, 'TBD'); assert.equal(learnerGroups.length, 0); assert.equal(learners.length, 0); assert.equal(instructorGroups.length, 0); assert.equal(instructors.length, 0); }); const save = '.buttons .done'; await render(hbs`<OfferingForm @close={{noop}} @save={{this.save}} />`); await click(save); return settled(); }); test('save recurring one week with days selected before initial date', async function(assert) { assert.expect(2); const wednesday = moment().add(1, 'week').day(3); const thursday = wednesday.clone().add(1, 'day').day(); const tuesday = wednesday.clone().subtract(1, 'day').day(); const toggle = '.make-recurring [data-test-toggle-yesno] [data-test-handle]'; const startDateInput = '.start-date input'; const newStartDate = wednesday.toDate(); let savedCount = 0; this.set('save', (startDate)=>{ let expectedStartDate; if (savedCount === 0) { expectedStartDate = wednesday.clone(); } else if (savedCount === 1) { expectedStartDate = wednesday.clone().day(thursday); } else { assert.ok(false, 'should only get two saved offerings, we got ' + (savedCount + 1)); } if (expectedStartDate) { assert.equal(moment(startDate).format('YYYY-MM-DD'), expectedStartDate.format('YYYY-MM-DD')); } savedCount++; return resolve(); }); const save = '.buttons .done'; await render(hbs`<OfferingForm @close={{noop}} @showMakeRecurring={{true}} @save={{this.save}} />`); await click(toggle); const interactor = openDatepicker(find(startDateInput)); interactor.selectDate(newStartDate); await click(`[data-test-recurring-day-input="${thursday}"]`); await click(`[data-test-recurring-day-input="${tuesday}"]`); await click(save); }); test('save recurring 3 weeks should get lots of days', async function(assert) { assert.expect(8); const wednesday = moment().add(1, 'week').day(3); const thursday = wednesday.clone().add(1, 'day').day(); const tuesday = wednesday.clone().subtract(1, 'day').day(); const weeks = '.make-recurring-input-container input'; const toggle = '.make-recurring [data-test-toggle-yesno] [data-test-handle]'; const startDateInput = '.start-date input'; const newStartDate = wednesday.toDate(); let savedCount = 0; this.set('save', (startDate)=>{ let expectedStartDate; if (savedCount === 0) { expectedStartDate = wednesday.clone(); } else if (savedCount === 1) { expectedStartDate = wednesday.clone().add(1, 'day'); } else if (savedCount === 2) { expectedStartDate = wednesday.clone().subtract(1, 'day').add(1, 'weeks'); } else if (savedCount === 3) { expectedStartDate = wednesday.clone().add(1, 'weeks'); } else if (savedCount === 4) { expectedStartDate = wednesday.clone().add(1, 'day').add(1, 'weeks'); } else if (savedCount === 5) { expectedStartDate = wednesday.clone().subtract(1, 'day').add(2, 'weeks'); } else if (savedCount === 6) { expectedStartDate = wednesday.clone().add(2, 'weeks'); } else if (savedCount === 7) { expectedStartDate = wednesday.clone().add(1, 'day').add(2, 'weeks'); } else { assert.ok(false, 'should only get eight saved offerings, we got ' + (savedCount + 1) + ' with startDate ' + moment(startDate).format('YYYY-MM-DD')); } if (expectedStartDate) { assert.equal(expectedStartDate.format('YYYY-MM-DD'), moment(startDate).format('YYYY-MM-DD')); } savedCount++; return resolve(); }); const save = '.buttons .done'; await render(hbs`<OfferingForm @close={{noop}} @showMakeRecurring={{true}} @save={{this.save}} />`); await click(toggle); await fillIn(weeks, 3); const interactor = openDatepicker(find(startDateInput)); interactor.selectDate(newStartDate); await click(`[data-test-recurring-day-input="${thursday}"]`); await click(`[data-test-recurring-day-input="${tuesday}"]`); await click(save); }); test('changing start date changes end date', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} />`); const startDate = '.start-date input'; const endDate = '.end-date-time .text'; const format = 'M/D/YYYY h:mm a'; const newStartDate = moment().add(1, 'day').toDate(); const interactor = openDatepicker(find(startDate)); assert.equal(moment().hour(9).minute(0).format(format), find(endDate).textContent.trim()); interactor.selectDate(newStartDate); await settled(); assert.equal(moment(newStartDate).hour(9).minute(0).format(format), find(endDate).textContent.trim()); }); test('changing start time changes end date', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} />`); const startHour = '.start-time select:nth-of-type(1)'; const startMinute = '.start-time select:nth-of-type(2)'; const startAmPm = '.start-time select:nth-of-type(3)'; const endDate = '.end-date-time .text'; const format = 'M/D/YYYY h:mm a'; assert.equal(moment().hour(9).minute(0).format(format), find(endDate).textContent.trim()); await fillIn(startHour, '2'); await fillIn(startMinute, '15'); await fillIn(startAmPm, 'pm'); assert.equal(moment().hour(15).minute(15).format(format), find(endDate).textContent.trim()); }); test('changing duration changes end date', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} />`); const durationHour = '.offering-duration .hours input'; const durationMinute = '.offering-duration .minutes input'; const endDate = '.end-date-time .text'; const format = 'M/D/YYYY h:mm a'; assert.equal(moment().hour(9).minute(0).format(format), find(endDate).textContent.trim()); await fillIn(durationHour, '2'); await fillIn(durationMinute, '15'); assert.equal(moment().hour(10).minute(15).format(format), find(endDate).textContent.trim()); }); // @see https://github.com/ilios/frontend/issues/1903 test('changing duration and start time changes end date', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} />`); const startHour = '.start-time select:nth-of-type(1)'; const startMinute = '.start-time select:nth-of-type(2)'; const startAmPm = '.start-time select:nth-of-type(3)'; const durationHour = '.offering-duration .hours input'; const durationMinute = '.offering-duration .minutes input'; const endDate = '.end-date-time .text'; const format = 'M/D/YYYY h:mm a'; assert.equal(moment().hour(9).minute(0).format(format), find(endDate).textContent.trim()); await fillIn(startHour, '2'); await fillIn(startMinute, '10'); await fillIn(startAmPm, 'pm'); await fillIn(durationHour, '2'); await fillIn(durationMinute, '50'); assert.equal(moment().hour(17).minute(0).format(format), find(endDate).textContent.trim()); }); test('learner manager is not present in small-group mode', async function(assert) { assert.expect(1); await render(hbs`<OfferingForm @close={{noop}} @smallGroupMode={{true}} />`); assert.dom('[data-test-learner-selection-manager').doesNotExist(); }); test('learner manager is present in single-offering mode', async function(assert) { assert.expect(1); await render(hbs`<OfferingForm @close={{noop}} @smallGroupMode={{false}} />`); assert.dom('[data-test-learner-selection-manager').exists(); }); test('learnerGroup validation errors do not show up initially', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} @smallGroupMode={{true}} />`); const item = '.learner-groups'; const error = `${item} .validation-error-message`; return settled().then(()=>{ assert.dom(error).doesNotExist(); }); }); test('learnerGroup validation errors show up when saving', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} @smallGroupMode={{true}} />`); const item = '.learner-groups'; const error = `${item} .validation-error-message`; const save = '.buttons .done'; await click(save); return settled().then(()=>{ assert.dom(error).exists({ count: 1 }); }); }); test('renders when an offering is provided', async function(assert) { const offering = EmberObject.create({ room: 'emerald bay', startDate: moment('2005-06-24').hour(18).minute(24).toDate(), endDate: moment('2005-06-24').hour(19).minute(24).toDate(), learnerGroups: resolve([]), learners: resolve([]), instructors: resolve([]), instructorGroups: resolve([]), }); this.set('offering', offering); await render(hbs`<OfferingForm @offering={{this.offering}} @close={{noop}} @showRoom={{true}} @showMakeRecurring={{true}} @showInstructors={{true}} />`); const startDate = '.start-date input'; const room = '.room input'; const durationHours = '.offering-duration .hours input'; const durationMinutes = '.offering-duration .minutes input'; assert.dom(room).hasValue('emerald bay'); assert.dom(durationHours).hasValue('1'); assert.dom(durationMinutes).hasValue('0'); const interactor = openDatepicker(find(startDate)); return settled().then(()=> { assert.equal( interactor.selectedYear(), 2005, 'Selected year initialized to offering start date year.' ); assert.equal( interactor.selectedMonth(), '5', 'Selected month initialized to offering start date month.' ); assert.equal( interactor.selectedDay(), '24', 'Selected day initialized to offering start date day.' ); }); }); test('shows current timezone', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} />`); const timezoneService = this.owner.lookup('service:timezone'); const timezoneValue = '[data-test-current-timezone]'; const currentTimezone = moment.tz.guess(); assert.dom(timezoneValue).containsText(timezoneService.formatTimezone(currentTimezone)); }); test('save date with new timezone', async function(assert) { assert.expect(11); const newTimezone = 'Pacific/Midway'; const utc = 'Etc/UTC'; const currentTimezone = moment.tz.guess(); const offering = EmberObject.create({ room: 'emerald bay', startDate: moment('2005-06-24').hour(18).minute(24).toDate(), endDate: moment('2005-06-24').hour(19).minute(24).toDate(), learnerGroups: resolve([]), learners: resolve([]), instructors: resolve([]), instructorGroups: resolve([]), }); this.set('offering', offering); this.set('save', (startDate, endDate)=>{ assert.equal('2005-06-25 05:24', moment(startDate).tz(utc).format('Y-MM-DD HH:mm')); assert.equal('2005-06-25 06:24', moment(endDate).tz(utc).format('Y-MM-DD HH:mm')); }); const save = '.buttons .done'; await render(hbs`<OfferingForm @offering={{this.offering}} @close={{noop}} @save={{this.save}} />`); const timezoneService = this.owner.lookup('service:timezone'); const currentTimezoneDisplay = '[data-test-current-timezone]'; const timezonePicker = '[data-test-timezone-picker] select'; const timezonePickerLabel = '[data-test-timezone-picker] label'; assert.notEqual(newTimezone, currentTimezone); assert.dom(timezonePicker).isNotVisible(); assert.dom(timezonePickerLabel).isNotVisible(); await click(currentTimezoneDisplay); assert.dom(timezonePicker).isVisible(); assert.dom(timezonePickerLabel).isVisible(); assert.dom(timezonePicker).hasValue(currentTimezone); await fillIn(timezonePicker, newTimezone); assert.dom(timezonePicker).isNotVisible(); assert.dom(timezonePickerLabel).isNotVisible(); assert.dom(currentTimezoneDisplay).containsText(timezoneService.formatTimezone(newTimezone)); await click(save); }); });
tests/integration/components/offering-form-test.js
import RSVP from 'rsvp'; import EmberObject from '@ember/object'; import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render, settled, click, find, findAll, fillIn, } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; import { padStart } from 'ember-pad/utils/pad'; import moment from 'moment'; import { openDatepicker } from 'ember-pikaday/helpers/pikaday'; const { resolve } = RSVP; module('Integration | Component | offering form', function(hooks) { setupRenderingTest(hooks); test('room input does not show by default', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} />`); assert.dom('.room').doesNotExist(); }); test('room input shows up when requested', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} @showRoom={{true}} />`); assert.dom('.room').exists({ count: 1 }); }); test('room validation errors do not show up initially', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} @showRoom={{true}} />`); const item = '.room'; const error = `${item} .validation-error-message`; assert.dom(error).doesNotExist(); }); test('room validation errors show up when typing', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} @showRoom={{true}} />`); const item = '.room'; const input = `${item} input`; const error = `${item} .validation-error-message`; const save = '.buttons .done'; await fillIn(input, padStart('a', 300, 'a')); await click(save); assert.dom(error).exists({ count: 1 }); }); test('recurring options does not show by default', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} />`); assert.dom('.make-recurring').doesNotExist(); }); test('recurring options shows up when requested', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} @showMakeRecurring={{true}} />`); assert.dom('.make-recurring').exists({ count: 1 }); }); test('recurring options has all the days of the week', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} @showMakeRecurring={{true}} />`); const sunday = '[data-test-recurring-day-label="0"]'; const monday = '[data-test-recurring-day-label="1"]'; const tuesday = '[data-test-recurring-day-label="2"]'; const wednesday = '[data-test-recurring-day-label="3"]'; const thursday = '[data-test-recurring-day-label="4"]'; const friday = '[data-test-recurring-day-label="5"]'; const saturday = '[data-test-recurring-day-label="6"]'; const toggle = '.make-recurring [data-test-toggle-yesno] [data-test-handle]'; await click(toggle); assert.dom(sunday).hasText('Sunday'); assert.dom(monday).hasText('Monday'); assert.dom(tuesday).hasText('Tuesday'); assert.dom(wednesday).hasText('Wednesday'); assert.dom(thursday).hasText('Thursday'); assert.dom(friday).hasText('Friday'); assert.dom(saturday).hasText('Saturday'); }); test('recurring numberOfWeeks validation errors do not show up initially', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} @showMakeRecurring={{true}} />`); const item = '.make-recurring-input-container'; const error = `${item} .validation-error-message`; const toggle = '.make-recurring [data-test-toggle-yesno] [data-test-handle]'; await click(toggle); assert.dom(error).doesNotExist(); }); test('recurring numberOfWeeks validation errors show up when saving', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} @showMakeRecurring={{true}} />`); const item = '.make-recurring-input-container'; const error = `${item} .validation-error-message`; const input = `${item} input`; const toggle = '.make-recurring [data-test-toggle-yesno] [data-test-handle]'; await click(toggle); const save = '.buttons .done'; await fillIn(input, 0); await click(save); assert.dom(error).exists({ count: 1 }); }); test('recurring default day is disabled and checked', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} @showMakeRecurring={{true}} />`); const inputs = '.make-recurring-days input'; const dayToday = moment().day(); const toggle = '.make-recurring [data-test-toggle-yesno] [data-test-handle]'; await click(toggle); const checkbox = findAll(inputs)[dayToday]; assert.ok(checkbox.checked); assert.ok(checkbox.disabled); }); test('instructor manager does not show by default', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} />`); assert.dom('.instructors').doesNotExist(); }); test('instructor manager shows up when requested', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} @showInstructors={{true}} />`); assert.dom('.instructors').exists({ count: 1 }); }); test('before course startDate default initial startDate falls on course start date', async function(assert) { const courseStartDate = moment().add(2, 'days'); const courseEndDate = moment().add(4, 'days'); this.set('courseStartDate', courseStartDate); this.set('courseEndDate', courseEndDate); await render(hbs`<OfferingForm @close={{noop}} @courseStartDate={{courseStartDate}} @courseEndDate={{courseEndDate}} />`); const startDate = '.start-date input'; const interactor = openDatepicker(find(startDate)); assert.equal( interactor.selectedYear(), courseStartDate.year(), 'Selected year initialized to course start date year.' ); assert.equal( interactor.selectedMonth(), courseStartDate.month(), 'Selected month initialized to course start date month.' ); assert.equal( interactor.selectedDay(), courseStartDate.date(), 'Selected day initialized to course start date day.' ); }); test('after course endDate default initial startDate falls on course end date', async function(assert) { const courseStartDate = moment().subtract(4, 'days'); const courseEndDate = moment().subtract(2, 'days'); this.set('courseStartDate', courseStartDate); this.set('courseEndDate', courseEndDate); await render(hbs`<OfferingForm @close={{noop}} @courseStartDate={{courseStartDate}} @courseEndDate={{courseEndDate}} />`); const startDate = '.start-date input'; const interactor = openDatepicker(find(startDate)); assert.equal( interactor.selectedYear(), courseEndDate.year(), 'Selected year initialized to course start date year.' ); assert.equal( interactor.selectedMonth(), courseEndDate.month(), 'Selected month initialized to course start date month.' ); assert.equal( interactor.selectedDay(), courseEndDate.date(), 'Selected day initialized to course start date day.' ); }); test('between course startDate and endDate default initial startDate falls on today', async function(assert) { const courseStartDate = moment().subtract(4, 'days'); const courseEndDate = moment().add(4, 'days'); const today = moment(); this.set('courseStartDate', courseStartDate); this.set('courseEndDate', courseEndDate); await render(hbs`<OfferingForm @close={{noop}} @courseStartDate={{courseStartDate}} @courseEndDate={{courseEndDate}} />`); const startDate = '.start-date input'; const interactor = openDatepicker(find(startDate)); assert.equal( interactor.selectedYear(), today.year(), 'Selected year initialized to course start date year.' ); assert.equal( interactor.selectedMonth(), today.month(), 'Selected month initialized to course start date month.' ); assert.equal( interactor.selectedDay(), today.date(), 'Selected day initialized to course start date day.' ); }); test('close sends close', async function(assert) { assert.expect(1); this.set('close', ()=>{ assert.ok(true); }); const closeButton = '.buttons .cancel'; await render(hbs`<OfferingForm @close={{action close}} />`); await click(closeButton); }); test('save not recurring', async function(assert) { assert.expect(7); this.set('save', (startDate, endDate, room, learners, learnerGroups, instructorGroups, instructors)=>{ assert.equal(moment(startDate).format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')); assert.equal(moment(endDate).format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')); assert.equal(room, 'TBD'); assert.equal(learnerGroups.length, 0); assert.equal(learners.length, 0); assert.equal(instructorGroups.length, 0); assert.equal(instructors.length, 0); }); const save = '.buttons .done'; await render(hbs`<OfferingForm @close={{noop}} @save={{action save}} />`); await click(save); return settled(); }); test('save recurring one week with days selected before initial date', async function(assert) { assert.expect(2); const wednesday = moment().add(1, 'week').day(3); const thursday = wednesday.clone().add(1, 'day').day(); const tuesday = wednesday.clone().subtract(1, 'day').day(); const toggle = '.make-recurring [data-test-toggle-yesno] [data-test-handle]'; const startDateInput = '.start-date input'; const newStartDate = wednesday.toDate(); let savedCount = 0; this.set('save', (startDate)=>{ let expectedStartDate; if (savedCount === 0) { expectedStartDate = wednesday.clone(); } else if (savedCount === 1) { expectedStartDate = wednesday.clone().day(thursday); } else { assert.ok(false, 'should only get two saved offerings, we got ' + (savedCount + 1)); } if (expectedStartDate) { assert.equal(moment(startDate).format('YYYY-MM-DD'), expectedStartDate.format('YYYY-MM-DD')); } savedCount++; return resolve(); }); const save = '.buttons .done'; await render(hbs`<OfferingForm @close={{noop}} @showMakeRecurring={{true}} @save={{action save}} />`); await click(toggle); const interactor = openDatepicker(find(startDateInput)); interactor.selectDate(newStartDate); await click(`[data-test-recurring-day-input="${thursday}"]`); await click(`[data-test-recurring-day-input="${tuesday}"]`); await click(save); }); test('save recurring 3 weeks should get lots of days', async function(assert) { assert.expect(8); const wednesday = moment().add(1, 'week').day(3); const thursday = wednesday.clone().add(1, 'day').day(); const tuesday = wednesday.clone().subtract(1, 'day').day(); const weeks = '.make-recurring-input-container input'; const toggle = '.make-recurring [data-test-toggle-yesno] [data-test-handle]'; const startDateInput = '.start-date input'; const newStartDate = wednesday.toDate(); let savedCount = 0; this.set('save', (startDate)=>{ let expectedStartDate; if (savedCount === 0) { expectedStartDate = wednesday.clone(); } else if (savedCount === 1) { expectedStartDate = wednesday.clone().add(1, 'day'); } else if (savedCount === 2) { expectedStartDate = wednesday.clone().subtract(1, 'day').add(1, 'weeks'); } else if (savedCount === 3) { expectedStartDate = wednesday.clone().add(1, 'weeks'); } else if (savedCount === 4) { expectedStartDate = wednesday.clone().add(1, 'day').add(1, 'weeks'); } else if (savedCount === 5) { expectedStartDate = wednesday.clone().subtract(1, 'day').add(2, 'weeks'); } else if (savedCount === 6) { expectedStartDate = wednesday.clone().add(2, 'weeks'); } else if (savedCount === 7) { expectedStartDate = wednesday.clone().add(1, 'day').add(2, 'weeks'); } else { assert.ok(false, 'should only get eight saved offerings, we got ' + (savedCount + 1) + ' with startDate ' + moment(startDate).format('YYYY-MM-DD')); } if (expectedStartDate) { assert.equal(expectedStartDate.format('YYYY-MM-DD'), moment(startDate).format('YYYY-MM-DD')); } savedCount++; return resolve(); }); const save = '.buttons .done'; await render(hbs`<OfferingForm @close={{noop}} @showMakeRecurring={{true}} @save={{action save}} />`); await click(toggle); await fillIn(weeks, 3); const interactor = openDatepicker(find(startDateInput)); interactor.selectDate(newStartDate); await click(`[data-test-recurring-day-input="${thursday}"]`); await click(`[data-test-recurring-day-input="${tuesday}"]`); await click(save); }); test('changing start date changes end date', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} />`); const startDate = '.start-date input'; const endDate = '.end-date-time .text'; const format = 'M/D/YYYY h:mm a'; const newStartDate = moment().add(1, 'day').toDate(); const interactor = openDatepicker(find(startDate)); assert.equal(moment().hour(9).minute(0).format(format), find(endDate).textContent.trim()); interactor.selectDate(newStartDate); await settled(); assert.equal(moment(newStartDate).hour(9).minute(0).format(format), find(endDate).textContent.trim()); }); test('changing start time changes end date', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} />`); const startHour = '.start-time select:nth-of-type(1)'; const startMinute = '.start-time select:nth-of-type(2)'; const startAmPm = '.start-time select:nth-of-type(3)'; const endDate = '.end-date-time .text'; const format = 'M/D/YYYY h:mm a'; assert.equal(moment().hour(9).minute(0).format(format), find(endDate).textContent.trim()); await fillIn(startHour, '2'); await fillIn(startMinute, '15'); await fillIn(startAmPm, 'pm'); assert.equal(moment().hour(15).minute(15).format(format), find(endDate).textContent.trim()); }); test('changing duration changes end date', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} />`); const durationHour = '.offering-duration .hours input'; const durationMinute = '.offering-duration .minutes input'; const endDate = '.end-date-time .text'; const format = 'M/D/YYYY h:mm a'; assert.equal(moment().hour(9).minute(0).format(format), find(endDate).textContent.trim()); await fillIn(durationHour, '2'); await fillIn(durationMinute, '15'); assert.equal(moment().hour(10).minute(15).format(format), find(endDate).textContent.trim()); }); // @see https://github.com/ilios/frontend/issues/1903 test('changing duration and start time changes end date', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} />`); const startHour = '.start-time select:nth-of-type(1)'; const startMinute = '.start-time select:nth-of-type(2)'; const startAmPm = '.start-time select:nth-of-type(3)'; const durationHour = '.offering-duration .hours input'; const durationMinute = '.offering-duration .minutes input'; const endDate = '.end-date-time .text'; const format = 'M/D/YYYY h:mm a'; assert.equal(moment().hour(9).minute(0).format(format), find(endDate).textContent.trim()); await fillIn(startHour, '2'); await fillIn(startMinute, '10'); await fillIn(startAmPm, 'pm'); await fillIn(durationHour, '2'); await fillIn(durationMinute, '50'); assert.equal(moment().hour(17).minute(0).format(format), find(endDate).textContent.trim()); }); test('learner manager is not present in small-group mode', async function(assert) { assert.expect(1); await render(hbs`<OfferingForm @close={{noop}} @smallGroupMode={{true}} />`); assert.dom('[data-test-learner-selection-manager').doesNotExist(); }); test('learner manager is present in single-offering mode', async function(assert) { assert.expect(1); await render(hbs`<OfferingForm @close={{noop}} @smallGroupMode={{false}} />`); assert.dom('[data-test-learner-selection-manager').exists(); }); test('learnerGroup validation errors do not show up initially', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} @smallGroupMode={{true}} />`); const item = '.learner-groups'; const error = `${item} .validation-error-message`; return settled().then(()=>{ assert.dom(error).doesNotExist(); }); }); test('learnerGroup validation errors show up when saving', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} @smallGroupMode={{true}} />`); const item = '.learner-groups'; const error = `${item} .validation-error-message`; const save = '.buttons .done'; await click(save); return settled().then(()=>{ assert.dom(error).exists({ count: 1 }); }); }); test('renders when an offering is provided', async function(assert) { const offering = EmberObject.create({ room: 'emerald bay', startDate: moment('2005-06-24').hour(18).minute(24).toDate(), endDate: moment('2005-06-24').hour(19).minute(24).toDate(), learnerGroups: resolve([]), learners: resolve([]), instructors: resolve([]), instructorGroups: resolve([]), }); this.set('offering', offering); await render(hbs`<OfferingForm @offering={{offering}} @close={{noop}} @showRoom={{true}} @showMakeRecurring={{true}} @showInstructors={{true}} />`); const startDate = '.start-date input'; const room = '.room input'; const durationHours = '.offering-duration .hours input'; const durationMinutes = '.offering-duration .minutes input'; assert.dom(room).hasValue('emerald bay'); assert.dom(durationHours).hasValue('1'); assert.dom(durationMinutes).hasValue('0'); const interactor = openDatepicker(find(startDate)); return settled().then(()=> { assert.equal( interactor.selectedYear(), 2005, 'Selected year initialized to offering start date year.' ); assert.equal( interactor.selectedMonth(), '5', 'Selected month initialized to offering start date month.' ); assert.equal( interactor.selectedDay(), '24', 'Selected day initialized to offering start date day.' ); }); }); test('shows current timezone', async function(assert) { await render(hbs`<OfferingForm @close={{noop}} />`); const timezoneService = this.owner.lookup('service:timezone'); const timezoneValue = '[data-test-current-timezone]'; const currentTimezone = moment.tz.guess(); assert.dom(timezoneValue).containsText(timezoneService.formatTimezone(currentTimezone)); }); test('save date with new timezone', async function(assert) { assert.expect(11); const newTimezone = 'Pacific/Midway'; const utc = 'Etc/UTC'; const currentTimezone = moment.tz.guess(); const offering = EmberObject.create({ room: 'emerald bay', startDate: moment('2005-06-24').hour(18).minute(24).toDate(), endDate: moment('2005-06-24').hour(19).minute(24).toDate(), learnerGroups: resolve([]), learners: resolve([]), instructors: resolve([]), instructorGroups: resolve([]), }); this.set('offering', offering); this.set('save', (startDate, endDate)=>{ assert.equal('2005-06-25 05:24', moment(startDate).tz(utc).format('Y-MM-DD HH:mm')); assert.equal('2005-06-25 06:24', moment(endDate).tz(utc).format('Y-MM-DD HH:mm')); }); const save = '.buttons .done'; await render(hbs`<OfferingForm @offering={{offering}} @close={{noop}} @save={{action save}} />`); const timezoneService = this.owner.lookup('service:timezone'); const currentTimezoneDisplay = '[data-test-current-timezone]'; const timezonePicker = '[data-test-timezone-picker] select'; const timezonePickerLabel = '[data-test-timezone-picker] label'; assert.notEqual(newTimezone, currentTimezone); assert.dom(timezonePicker).isNotVisible(); assert.dom(timezonePickerLabel).isNotVisible(); await click(currentTimezoneDisplay); assert.dom(timezonePicker).isVisible(); assert.dom(timezonePickerLabel).isVisible(); assert.dom(timezonePicker).hasValue(currentTimezone); await fillIn(timezonePicker, newTimezone); assert.dom(timezonePicker).isNotVisible(); assert.dom(timezonePickerLabel).isNotVisible(); assert.dom(currentTimezoneDisplay).containsText(timezoneService.formatTimezone(newTimezone)); await click(save); }); });
rm action helper, prefix passed args with this.
tests/integration/components/offering-form-test.js
rm action helper, prefix passed args with this.
<ide><path>ests/integration/components/offering-form-test.js <ide> <ide> await render(hbs`<OfferingForm <ide> @close={{noop}} <del> @courseStartDate={{courseStartDate}} <del> @courseEndDate={{courseEndDate}} <add> @courseStartDate={{this.courseStartDate}} <add> @courseEndDate={{this.courseEndDate}} <ide> />`); <ide> <ide> const startDate = '.start-date input'; <ide> <ide> await render(hbs`<OfferingForm <ide> @close={{noop}} <del> @courseStartDate={{courseStartDate}} <del> @courseEndDate={{courseEndDate}} <add> @courseStartDate={{this.courseStartDate}} <add> @courseEndDate={{this.courseEndDate}} <ide> />`); <ide> <ide> const startDate = '.start-date input'; <ide> <ide> await render(hbs`<OfferingForm <ide> @close={{noop}} <del> @courseStartDate={{courseStartDate}} <del> @courseEndDate={{courseEndDate}} <add> @courseStartDate={{this.courseStartDate}} <add> @courseEndDate={{this.courseEndDate}} <ide> />`); <ide> <ide> const startDate = '.start-date input'; <ide> assert.ok(true); <ide> }); <ide> const closeButton = '.buttons .cancel'; <del> await render(hbs`<OfferingForm @close={{action close}} />`); <add> await render(hbs`<OfferingForm @close={{this.close}} />`); <ide> await click(closeButton); <ide> }); <ide> <ide> assert.equal(instructors.length, 0); <ide> }); <ide> const save = '.buttons .done'; <del> await render(hbs`<OfferingForm @close={{noop}} @save={{action save}} />`); <add> await render(hbs`<OfferingForm @close={{noop}} @save={{this.save}} />`); <ide> <ide> await click(save); <ide> <ide> await render(hbs`<OfferingForm <ide> @close={{noop}} <ide> @showMakeRecurring={{true}} <del> @save={{action save}} <add> @save={{this.save}} <ide> />`); <ide> <ide> await click(toggle); <ide> await render(hbs`<OfferingForm <ide> @close={{noop}} <ide> @showMakeRecurring={{true}} <del> @save={{action save}} <add> @save={{this.save}} <ide> />`); <ide> <ide> await click(toggle); <ide> <ide> this.set('offering', offering); <ide> await render(hbs`<OfferingForm <del> @offering={{offering}} <add> @offering={{this.offering}} <ide> @close={{noop}} <ide> @showRoom={{true}} <ide> @showMakeRecurring={{true}} <ide> assert.equal('2005-06-25 06:24', moment(endDate).tz(utc).format('Y-MM-DD HH:mm')); <ide> }); <ide> const save = '.buttons .done'; <del> await render(hbs`<OfferingForm @offering={{offering}} @close={{noop}} @save={{action save}} />`); <add> await render(hbs`<OfferingForm @offering={{this.offering}} @close={{noop}} @save={{this.save}} />`); <ide> <ide> const timezoneService = this.owner.lookup('service:timezone'); <ide>
Java
apache-2.0
cb12480fa3d6ad4e8be1a07c2c3b205cc974867b
0
abohomol/kaa,vtkhir/kaa,liuhu/Kaa,liuhu/Kaa,rasendubi/kaa,sashadidukh/kaa,kallelzied/kaa,sashadidukh/kaa,Dubland/kaa,aglne/kaa,Deepnekroz/kaa,Oleh-Kravchenko/kaa,liuhu/Kaa,sashadidukh/kaa,sashadidukh/kaa,aglne/kaa,Deepnekroz/kaa,rasendubi/kaa,liuhu/Kaa,vtkhir/kaa,vtkhir/kaa,sashadidukh/kaa,forGGe/kaa,abohomol/kaa,Deepnekroz/kaa,Dubland/kaa,kallelzied/kaa,vtkhir/kaa,abohomol/kaa,zofuthan/kaa,liuhu/Kaa,sashadidukh/kaa,Oleh-Kravchenko/kaa,Deepnekroz/kaa,liuhu/Kaa,rasendubi/kaa,forGGe/kaa,rasendubi/kaa,Oleh-Kravchenko/kaa,Dubland/kaa,Deepnekroz/kaa,forGGe/kaa,vtkhir/kaa,kallelzied/kaa,aglne/kaa,Oleh-Kravchenko/kaa,forGGe/kaa,liuhu/Kaa,zofuthan/kaa,rasendubi/kaa,vtkhir/kaa,zofuthan/kaa,kallelzied/kaa,aglne/kaa,rasendubi/kaa,kallelzied/kaa,aglne/kaa,zofuthan/kaa,abohomol/kaa,kallelzied/kaa,Deepnekroz/kaa,zofuthan/kaa,zofuthan/kaa,Dubland/kaa,sashadidukh/kaa,vtkhir/kaa,Deepnekroz/kaa,Oleh-Kravchenko/kaa,rasendubi/kaa,aglne/kaa,Oleh-Kravchenko/kaa,forGGe/kaa,Dubland/kaa,forGGe/kaa,abohomol/kaa,Oleh-Kravchenko/kaa,forGGe/kaa,sashadidukh/kaa,vtkhir/kaa,Dubland/kaa,aglne/kaa,abohomol/kaa,abohomol/kaa,Dubland/kaa
/* * Copyright 2014-2015 CyberVision, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaaproject.kaa.sandbox.demo; import java.util.ArrayList; import java.util.List; public class DemoBuildersRegistry { private static final List<DemoBuilder> demoBuilders = new ArrayList<>(); static { // Iot World demo /* demoBuilders.add(new IotWorldDemoBuilder()); demoBuilders.add(new ConnectedCarDemo()); demoBuilders.add(new PowerPlantDemoBuilder()); demoBuilders.add(new TrafficLightsDriverDemoBuilder()); demoBuilders.add(new StreetLightDriverDemoBuilder()); demoBuilders.add(new CityLightsControllerDemoBuilder()); demoBuilders.add(new TwitterBoardDemoBuilder()); demoBuilders.add(new TwitterMonitorDemoBuilder()); demoBuilders.add(new VehicleTelemetryDemoBuider()); demoBuilders.add(new PowerPlantAndroidDemoBuilder()); */ //ANDROID DEMOS demoBuilders.add(new AndroidNotificationDemoBuilder()); demoBuilders.add(new CellMonitorDemoBuilder()); demoBuilders.add(new CityGuideDemoBuilder()); demoBuilders.add(new PhotoFrameDemoBuilder()); demoBuilders.add(new SmartHouseDemoBuilder()); demoBuilders.add(new VerifiersDemoBuilder()); // demoBuilders.add(new RobotRunDemoBuilder()); demoBuilders.add(new EventDemoBuilder()); demoBuilders.add(new DataCollectionDemoBuider()); demoBuilders.add(new ConfigurationDemoBuilder()); demoBuilders.add(new NotificationDemoBuilder()); } public static List<DemoBuilder> getRegisteredDemoBuilders() { return demoBuilders; } }
sandbox/demo/src/main/java/org/kaaproject/kaa/sandbox/demo/DemoBuildersRegistry.java
/* * Copyright 2014-2015 CyberVision, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kaaproject.kaa.sandbox.demo; import java.util.ArrayList; import java.util.List; public class DemoBuildersRegistry { private static final List<DemoBuilder> demoBuilders = new ArrayList<>(); static { // Iot World demo demoBuilders.add(new IotWorldDemoBuilder()); demoBuilders.add(new ConnectedCarDemo()); demoBuilders.add(new PowerPlantDemoBuilder()); demoBuilders.add(new TrafficLightsDriverDemoBuilder()); demoBuilders.add(new StreetLightDriverDemoBuilder()); demoBuilders.add(new CityLightsControllerDemoBuilder()); demoBuilders.add(new TwitterBoardDemoBuilder()); demoBuilders.add(new TwitterMonitorDemoBuilder()); demoBuilders.add(new VehicleTelemetryDemoBuider()); //ANDROID DEMOS demoBuilders.add(new AndroidNotificationDemoBuilder()); demoBuilders.add(new CellMonitorDemoBuilder()); demoBuilders.add(new CityGuideDemoBuilder()); demoBuilders.add(new PhotoFrameDemoBuilder()); // demoBuilders.add(new SmartHouseDemoBuilder()); demoBuilders.add(new VerifiersDemoBuilder()); // demoBuilders.add(new RobotRunDemoBuilder()); demoBuilders.add(new EventDemoBuilder()); demoBuilders.add(new DataCollectionDemoBuider()); demoBuilders.add(new ConfigurationDemoBuilder()); demoBuilders.add(new NotificationDemoBuilder()); demoBuilders.add(new PowerPlantAndroidDemoBuilder()); } public static List<DemoBuilder> getRegisteredDemoBuilders() { return demoBuilders; } }
eliminate IoT World demos from build
sandbox/demo/src/main/java/org/kaaproject/kaa/sandbox/demo/DemoBuildersRegistry.java
eliminate IoT World demos from build
<ide><path>andbox/demo/src/main/java/org/kaaproject/kaa/sandbox/demo/DemoBuildersRegistry.java <ide> <ide> static { <ide> // Iot World demo <add>/* <ide> demoBuilders.add(new IotWorldDemoBuilder()); <ide> <ide> demoBuilders.add(new ConnectedCarDemo()); <ide> demoBuilders.add(new TwitterMonitorDemoBuilder()); <ide> <ide> demoBuilders.add(new VehicleTelemetryDemoBuider()); <add> demoBuilders.add(new PowerPlantAndroidDemoBuilder()); <ide> <add>*/ <ide> //ANDROID DEMOS <ide> demoBuilders.add(new AndroidNotificationDemoBuilder()); <ide> demoBuilders.add(new CellMonitorDemoBuilder()); <ide> demoBuilders.add(new CityGuideDemoBuilder()); <ide> demoBuilders.add(new PhotoFrameDemoBuilder()); <del>// demoBuilders.add(new SmartHouseDemoBuilder()); <del> demoBuilders.add(new VerifiersDemoBuilder()); <add> demoBuilders.add(new SmartHouseDemoBuilder()); <add> demoBuilders.add(new VerifiersDemoBuilder()); <ide> // demoBuilders.add(new RobotRunDemoBuilder()); <ide> <ide> demoBuilders.add(new EventDemoBuilder()); <ide> demoBuilders.add(new DataCollectionDemoBuider()); <ide> demoBuilders.add(new ConfigurationDemoBuilder()); <ide> demoBuilders.add(new NotificationDemoBuilder()); <del> demoBuilders.add(new PowerPlantAndroidDemoBuilder()); <ide> } <ide> <ide> public static List<DemoBuilder> getRegisteredDemoBuilders() {
Java
mit
error: pathspec 'src/main/java/org/ccci/gto/android/common/content/ForwardingBroadcastReceiver.java' did not match any file(s) known to git
c42cfd21c97dfadb44202a5264c49143dcd3efd6
1
CruGlobal/android-gto-support,GlobalTechnology/android-gto-support,CruGlobal/android-gto-support
package org.ccci.gto.android.common.content; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.support.annotation.Nullable; public abstract class ForwardingBroadcastReceiver extends BroadcastReceiver { private BroadcastReceiver mDelegate; protected ForwardingBroadcastReceiver() { } @Override public void onReceive(final Context context, final Intent intent) { if (mDelegate != null) { mDelegate.onReceive(context, intent); } } public final void setDelegate(@Nullable final BroadcastReceiver receiver) { mDelegate = receiver; } }
src/main/java/org/ccci/gto/android/common/content/ForwardingBroadcastReceiver.java
create a ForwardingBroadcastReceiver this object will allow any BroadcastReceiver to be wrapped with additional functionality
src/main/java/org/ccci/gto/android/common/content/ForwardingBroadcastReceiver.java
create a ForwardingBroadcastReceiver
<ide><path>rc/main/java/org/ccci/gto/android/common/content/ForwardingBroadcastReceiver.java <add>package org.ccci.gto.android.common.content; <add> <add>import android.content.BroadcastReceiver; <add>import android.content.Context; <add>import android.content.Intent; <add>import android.support.annotation.Nullable; <add> <add>public abstract class ForwardingBroadcastReceiver extends BroadcastReceiver { <add> private BroadcastReceiver mDelegate; <add> <add> protected ForwardingBroadcastReceiver() { <add> } <add> <add> @Override <add> public void onReceive(final Context context, final Intent intent) { <add> if (mDelegate != null) { <add> mDelegate.onReceive(context, intent); <add> } <add> } <add> <add> public final void setDelegate(@Nullable final BroadcastReceiver receiver) { <add> mDelegate = receiver; <add> } <add>}
Java
apache-2.0
028669bbf9f9c57b96ec3da72970ae7f91a1e11e
0
skoulouzis/vlet,skoulouzis/vlet,skoulouzis/vlet,skoulouzis/vlet,skoulouzis/vlet,skoulouzis/vlet
/* * Copyright 2006-2011 The Virtual Laboratory for e-Science (VL-e) * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * For details, see the LICENCE.txt file location in the root directory of this * distribution or obtain the Apache Licence at the following location: * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * See: http://www.vl-e.nl/ * See: LICENCE.txt (located in the root folder of this distribution). * --- * $Id: SftpFileSystem.java,v 1.2 2011-12-07 10:19:58 ptdeboer Exp $ * $Date: 2011-12-07 10:19:58 $ */ // source: package nl.uva.vlet.vfs.jcraft.ssh; import static nl.uva.vlet.data.VAttributeConstants.ATTR_ACCESS_TIME; import static nl.uva.vlet.data.VAttributeConstants.ATTR_GID; import static nl.uva.vlet.data.VAttributeConstants.ATTR_LENGTH; import static nl.uva.vlet.data.VAttributeConstants.ATTR_MODIFICATION_TIME; import static nl.uva.vlet.data.VAttributeConstants.ATTR_UID; import static nl.uva.vlet.data.VAttributeConstants.ATTR_UNIX_FILE_MODE; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.Hashtable; import java.util.Random; import java.util.Vector; import nl.uva.vlet.Global; import nl.uva.vlet.data.StringHolder; import nl.uva.vlet.data.StringUtil; import nl.uva.vlet.data.VAttribute; import nl.uva.vlet.data.VAttributeType; import nl.uva.vlet.exception.ResourceAlreadyExistsException; import nl.uva.vlet.exception.ResourceCreationFailedException; import nl.uva.vlet.exception.ResourceNotFoundException; import nl.uva.vlet.exception.VlAuthenticationException; import nl.uva.vlet.exception.VlException; import nl.uva.vlet.io.StreamUtil; import nl.uva.vlet.vfs.FileSystemNode; import nl.uva.vlet.vfs.VDir; import nl.uva.vlet.vfs.VFS; import nl.uva.vlet.vfs.VFSNode; import nl.uva.vlet.vfs.VFSTransfer; import nl.uva.vlet.vfs.VFile; import nl.uva.vlet.vfs.jcraft.ssh.SSHChannel.SSHChannelOptions; import nl.uva.vlet.vrl.VRL; import nl.uva.vlet.vrs.ServerInfo; import nl.uva.vlet.vrs.VRS; import nl.uva.vlet.vrs.VRSContext; import nl.uva.vlet.vrs.io.VShellChannelCreator; import nl.uva.vlet.vrs.net.VOutgoingTunnelCreator; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.HostKey; import com.jcraft.jsch.HostKeyRepository; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpATTRS; import com.jcraft.jsch.SftpException; import com.jcraft.jsch.SftpProgressMonitor; import com.jcraft.jsch.UserInfo; /** * SFTP FileSystem implementation. * The jsch session can provide a FTP channel and a command line channel. * Also tunneling is supported by the API. */ public class SftpFileSystem extends FileSystemNode implements VOutgoingTunnelCreator, VShellChannelCreator { // === class stuff private static Hashtable<String, SftpFileSystem> servers = new Hashtable<String, SftpFileSystem>(); private static String createServerID(String host, int port, String user) { // must use default port in ServerID ! if (port <= 0) port = VRS.DEFAULT_SSH_PORT; return user + "@" + host + ":" + port; } public class VLUserInfo implements UserInfo { public VLUserInfo() { super(); } public String getUsername() { return getServerInfo().getUsername(); } public String getPassphrase() { return getServerInfo().getPassphrase(); } public String getPassword() { return getServerInfo().getPassword(); } // this object has no acces to the gui... public boolean promptPassword(String message) { if (getAllowUserInterAction()==false) { // use store password: if (StringUtil.isEmpty(getPassword())==false) return true; return false; } // getVRSContext().getConfigManager().getHasUI(); String field=uiPromptPassfield(message); if (field!=null) { getServerInfo().setPassword(field); field=null; return true; } return false; } public boolean promptPassphrase(String message) { if (getAllowUserInterAction()==false) { // use store password: if (StringUtil.isEmpty(getPassphrase())==false) return true; return false; } // jSch doesn't provide username in message ! message="Authentication needed for: "+getUsername()+"@"+getHostname()+"\n" +message; // getVRSContext().getConfigManager().getHasUI(); String field=uiPromptPassfield(message); if (field!=null) { getServerInfo().setPassphrase(field); field=null; return true; } return false; } public String uiPromptPassfield(String message) { StringHolder secretHolder=new StringHolder(null); boolean result=getVRSContext().getUI().askAuthentication(message, secretHolder); if (result == true) return secretHolder.value; else return null; } public void showMessage(String message) { if (getAllowUserInterAction()==false) { return; } else { getVRSContext().getUI().showMessage(message); } } public boolean promptYesNo(String message) { if (getAllowUserInterAction()==false) { return getDefaultYesNoAnswer(message); } else { return getVRSContext().getUI().askYesNo("Yes or No?",message, false); } } } // ============================================================================= // ============================================================================= private static Random portRandomizer=new Random(); private static Vector<Integer> usedLocalPorts=new Vector<Integer>(); public VRL getServerVRL() { return new VRL(VRS.SFTP_SCHEME,null,this.getHostname(),getPort(),null); } /* public static final int SSH_FX_OK = 0; public static final int SSH_FX_EOF = 1; public static final int SSH_FX_NO_SUCH_FILE = 2; public static final int SSH_FX_PERMISSION_DENIED = 3; public static final int SSH_FX_FAILURE = 4; public static final int SSH_FX_BAD_MESSAGE = 5; public static final int SSH_FX_NO_CONNECTION = 6; public static final int SSH_FX_CONNECTION_LOST = 7; public static final int SSH_FX_OP_UNSUPPORTED = 8; */ public static String[] errorStringsList = { "SSH:OK", // 0=No error SSH_FX_OK "SSH:End of file reached", // 1=SSH_FX_EOF "SSH:No such file", // 2=SSH_FX_NO_SUCH_FILE "SSH:Permission denied", // 3=... "SSH:General failure", // 4 "SSH:Bad message", // 5 "SSH:No connection", // 6 "SSH:Connection lost", // 7 "SSH:Unsupported operation" // 8 }; // ======================================================================= // Instance // ======================================================================= // === instanceSSH_FX_OK //private String hostname = null; //private int port = DEFAULT_SSH_PORT; private ChannelSftp sftpChannel; private nl.uva.vlet.vfs.jcraft.ssh.SftpFileSystem.VLUserInfo userInfo; private JSch jschInstance; private Session session; final Boolean serverMutex=new Boolean(true); private String defaultHome="/"; private String userSubject; // ======================================================================= // Server Critical // ======================================================================= private void init(ServerInfo info) throws VlException { Debug("init for:" + info.getUsername() + "@" + getHostname() + ":" + getPort()); this.userInfo = new VLUserInfo(); this.serverID = createServerID(getHostname(), getPort(), info.getUsername()); this.connect(); } /** * */ public SftpFileSystem(VRSContext context,ServerInfo info, VRL location) throws VlException { super(context,info); init(info); Debug("New:" + this); } public String getUsername() { return this.userInfo.getUsername(); } // ======================================================================= // Authentication // ======================================================================= public boolean getDefaultYesNoAnswer(String optMessage) { return this.getServerInfo().getBoolProperty(ServerInfo.ATTR_DEFAULT_YES_NO_ANSWER, false); } public void setDefaultYesNoAnswer(boolean value) { ServerInfo info=getServerInfo(); info.setAttribute(ServerInfo.ATTR_DEFAULT_YES_NO_ANSWER, value); info.store(); } // ======================================================================= // === synchronized methods === // ======================================================================= public VFSNode openLocation(VRL vrl) throws VlException { // No Exceptions: store ServerInfo ! String path=vrl.getPath(); if ((path==null) || (path.compareTo("")==0)) path=getHomeDir(); // ~/ home expansion if (path.startsWith("~")) path=getHomeDir()+path.substring(1); if (path.startsWith("/~")) path=getHomeDir()+path.substring(2); return getPath(path); } public VFSNode getPath(String path) throws VlException { String user = getUsername(); int port = getPort(); String host = getHostname(); // '~' expansion -> default home if (path.startsWith("~")) path=defaultHome+"/"+path.substring(1,path.length()); else if (path.startsWith("/~")) path=defaultHome+"/"+path.substring(2,path.length()); // // hide default port from location // IMPORTANT: must match accountID in ServerInfo ! // if (port == VRS.DEFAULT_SSH_PORT) port = 0; VRL vrl = new VRL(VRS.SFTP_SCHEME, user, host, port, path); Debug("getPath:" + path); SftpATTRS attrs = null; try { synchronized(serverMutex) { checkState(); // Must throw the right Exception: /*// cd to dirname to speed up stat String pwd=sftpChannel.pwd(); String dirname=VRL.dirname(path); if (pwd.compareTo(dirname)!=0) { Debug("cd to:"+dirname); sftpChannel.cd(dirname); } attrs = sftpChannel.lstat(VRL.basename(path)); //attrs = sftpChannel.stat(VRL.basename(path)); */ // do not resolve (possivle errornous) link: attrs=this.getSftpAttrs(path,false); } } catch (Exception e) { throw convertException(e); } if (attrs == null) { throw new ResourceNotFoundException("Couldn't stat:" + path); } else if (attrs.isDir()) { return new SftpDir(this, vrl); } else if (attrs.isLink()) { // resolve link: check attributes SftpATTRS targetAttrs=null; try { targetAttrs=getSftpAttrs(path,true); // Link Target Error: return as file if (targetAttrs!=null) { // return linked directory as VDir ! (not file) if (targetAttrs.isDir()) { return new SftpDir(this, vrl); } } } catch (Exception e) { Debug("??? Exception when resolving link:"+vrl+" Exception="+e); } } // default: return as file return new SftpFile(this, vrl); } public void myDispose() { synchronized(serverMutex) { try { disconnect(); } catch (VlException e) { // TODO Auto-generated catch block e.printStackTrace(); } servers.remove(this); } } public String[] list(String path) throws VlException { Debug("listing:" + path); try { java.util.Vector<?> dirList; synchronized(serverMutex) { try { checkState(); dirList = sftpChannel.ls(path); } catch (Exception e) { checkState(); dirList = sftpChannel.ls(path); } } int index = 0; String childs[] = new String[dirList.size()]; for (int i = 0; i < dirList.size(); i++) { Object entry = dirList.elementAt(i); if (entry instanceof com.jcraft.jsch.ChannelSftp.LsEntry) { ChannelSftp.LsEntry lsEntry = (ChannelSftp.LsEntry) entry; childs[index] = lsEntry.getFilename(); } else { Global.errorPrintln(this,"ls() returned unknown entry[" + index + "]=" + entry.getClass().getCanonicalName()); childs[index] = null; } index++; } return childs; } catch (SftpException e) { throw convertException(e,"Could not list contents of remote path:"+path); } } private void checkState() throws VlException { try { synchronized(serverMutex) { if (this.session.isConnected() == false) { Global.errorPrintln(this, "Session disconnected: reconnecting:" + this); session = jschInstance.getSession(userInfo.getUsername(), getHostname(), getPort()); session.setUserInfo(userInfo); session.connect(); if (sftpChannel.isConnected()==true) sftpChannel.disconnect(); sftpChannel=null; } if ((this.sftpChannel==null) || this.sftpChannel.isConnected()==false) { Global.errorPrintln(this, "Channel closed: reconnecting:" + this); this.sftpChannel = (ChannelSftp) session.openChannel("sftp"); sftpChannel.connect(); } } } /*catch (SftpException e1) { throw convertException(e1); }*/ catch (JSchException e) { throw convertException(e); } } public boolean existsPath(String path, boolean checkDir) throws VlException { Debug("existsPath:"+path); try { synchronized(serverMutex) { SftpATTRS attrs; try { checkState(); attrs = sftpChannel.lstat(path); } catch (Exception e) { checkState(); attrs = sftpChannel.lstat(path); } // sadly stat generates an exception when the path doesn't exists, // so the following code will not be executed. if (attrs == null) { return false; } else { if (checkDir==true) { if (attrs.isDir()==true) { return true; } else { // exists but is NOT a directory ! return false; } } else { if (attrs.isDir()==false) { return true; } else { // exists but is NOT a file ! return false; } } } } } catch (Exception e) { if (e instanceof SftpException) { SftpException ex=(SftpException)e; //Global.messagePrintln(this,"after existsPath, session="+this.session.isConnected()); //Global.messagePrintln(this,"after existsPath, channel="+this.sftpChannel.isConnected()); // SftpException reason 2=no such file ! if (ex.id==2) return false; } // other reason: throw convertException(e,"Could not stat remote path:"+path); } } public void uploadFile(VFSTransfer transfer,String localfilepath, String remotefilepath) throws VlException { try { synchronized(serverMutex) { checkState(); // jCraft has a tranfer interface ! SftpTransferMonitor monitor=new SftpTransferMonitor(transfer); this.sftpChannel.put(localfilepath,remotefilepath,monitor); } } catch(Exception e) { throw convertException(e,"Error when uploading file to remote paths:"+remotefilepath); } } public void downloadFile(VFSTransfer transfer, String remotefilepath, String localfilepath) throws VlException { try { synchronized(serverMutex) { checkState(); // jCraft has a tranfer interface ! SftpTransferMonitor monitor=new SftpTransferMonitor(transfer); this.sftpChannel.get(remotefilepath,localfilepath,monitor); } } catch(Exception e) { throw convertException(e,"Error when downloading file to local path:"+localfilepath); } } public VDir createDir(String dirpath, boolean ignoreExisting) throws VlException { // check existing! SftpATTRS attrs=null; //checkAndCreateParentDir(VRL.dirname(dirpath),force); try { // check existing! attrs = this.getSftpAttrs(dirpath,ignoreExisting); } catch (Exception e) { ; // ignore } // exists: if (attrs!=null) { if (attrs.isDir()==false) throw new ResourceCreationFailedException("path already exists but is not a directory:"+this); if (ignoreExisting == false) throw new ResourceAlreadyExistsException("path already exists (use ignoreExisting==true to overwrite) :"+this); else return (VDir) getPath(dirpath); } try { synchronized(serverMutex) { checkState(); sftpChannel.mkdir(dirpath); } return (VDir) getPath(dirpath); } catch (SftpException e) { throw convertException(e,"Error when creating remote directory:"+dirpath); } } private void checkAndCreateParentDir(String dirname, boolean force) throws VlException { SftpATTRS parentAttrs=null; try { // check existing parent: parentAttrs = this.getSftpAttrs(dirname,force); } catch (Exception e) { ; // ignore } // create parent first if (parentAttrs==null) createDir(dirname,force); } public VFile createFile(String filepath, boolean force) throws VlException { SftpATTRS attrs=null; // checkAndCreateParentDir(VRL.dirname(filepath),force); try { // stat: attrs= this.getSftpAttrs(filepath); } catch (Exception e) { ; // ignore; } if (attrs!=null) { // exists: if (force == false) throw new ResourceAlreadyExistsException("path already exists:"+this); if (attrs.isDir()==true) throw new ResourceAlreadyExistsException("path already exists but is a directory:"+this); if (attrs.isLink()==true) throw new ResourceAlreadyExistsException("path already exists but is a symbolic link:"+this); // delete existing: delete(filepath, false); } // create new: // write null bytes byte nulbuf[] = new byte[0]; OutputStream out; try { synchronized(this.serverMutex) { checkState(); OutputStream output= this.sftpChannel.put(filepath,ChannelSftp.OVERWRITE); output.write(nulbuf); output.flush(); output.close(); } VFSNode node = getPath(filepath); if (node instanceof VFile) { return (VFile) node; } else { throw new ResourceCreationFailedException( "path exists, but is not a file:" + filepath); } } catch (Exception e) { throw this.convertException(e,"Could not create file:"+filepath); } } public SftpATTRS getSftpAttrs(String filepath) throws VlException { return getSftpAttrs(filepath,false); } public boolean delete(String path, boolean isDir) throws VlException { try { synchronized(serverMutex) { checkState(); if (isDir == false) { sftpChannel.rm(path); } else { sftpChannel.rmdir(path); } } return (existsPath(path,isDir) == false); } catch (Exception e) { throw convertException(e); } } /*public int isOwner() { SftpATTRS attrs=getSftpAttrs(path); attrs.getPermissions(); attrs.getUId(); }*/ public SftpATTRS getSftpAttrs(String path,boolean resolveLink) throws VlException { Debug("getSftpAttrs:"+path); try { synchronized(serverMutex) { try { checkState(); if (resolveLink==false) return sftpChannel.lstat(path); else return sftpChannel.stat(path); } catch (Exception e) { checkState(); if (resolveLink==false) return sftpChannel.lstat(path); else return sftpChannel.stat(path); } } } catch (Exception e) { //System.err.println("Exception when statting:"+path); throw convertException(e,"Could not stat remote path:"+path); } } private ChannelSftp createNewFTPChannel() throws VlException { Debug("createNewChannel:"+this); try { ChannelSftp channel; channel = (ChannelSftp)session.openChannel("sftp"); channel.connect(); return channel; } catch (JSchException e) { throw convertException(e,"Couldn't create new channel to:"+this); } } public void setSftpAttrs(String path,boolean isDir, SftpATTRS attrs) throws VlException { try { synchronized(serverMutex) { checkState(); sftpChannel.setStat(path, attrs); } } catch (SftpException e) { // find out what is wrong: if (this.existsPath(path,isDir) == false) { // Error Handling: return better Exception throw new ResourceNotFoundException("Path doesn't exists:" + path); } else { throw convertException(e); } } } public InputStream createInputStream(String path) throws VlException { try { ChannelSftp newChannel=null; synchronized(serverMutex) { checkState(); // old: // return this.sftpChannel.get(path); // open up a new channel for multithreaded viewing ! newChannel =(ChannelSftp) this.session.openChannel("sftp"); } newChannel.connect(); InputStream inps=newChannel.get(path); return new InputStreamWatcher(newChannel,inps); } catch (Exception e) { throw convertException(e); } //return null; } public int readBytes(String path, long fileOffset, byte[] buffer, int bufferOffset, int nrBytes) throws VlException { try { /*if (true) { ByteArrayOutputStream outpBuffer=new ByteArrayOutputStream(nrBytes); synchronized(serverMutex) { sftpChannel.get(path, outpBuffer, null,nrBytes,fileOffset); byte[] sourcebuf = outpBuffer.toByteArray(); System.arraycopy(sourcebuf,0,buffer,bufferOffset,nrBytes); int numread=nrBytes; return numread; } } else */ { // // Emulate Random Read by using StreamRead: // This method is also used in VFile.read(...) // InputStream inps; synchronized(serverMutex) { checkState(); inps = sftpChannel.get(path); } //DONE BY SYNC READ: inps.skip(fileOffset); int numread = StreamUtil.syncReadBytes(inps, fileOffset, buffer, bufferOffset,nrBytes); inps.close(); return numread; } } catch (Exception e) { throw convertException(e); } } /** * TODO: Still buggy */ public void writeBytes(String path, long fileOffset, byte[] buffer, int bufferOffset, int nrBytes) throws VlException { OutputStream outps; //int mode=ChannelSftp.RESUME; int mode=ChannelSftp.OVERWRITE; // must currently write in 32000 byte sized chunks int chunksize=32000; // skip existing bytes: if (fileOffset>0) mode=ChannelSftp.RESUME; try { synchronized(serverMutex) { checkState(); // TODO: MODE !!! outps = sftpChannel.put(path, (SftpProgressMonitor)null,mode, fileOffset); // chunk write: { // write in chunks: for (int i=0;i<nrBytes;i+=chunksize) { if (i+chunksize>nrBytes) chunksize=nrBytes-i; outps.write(buffer,bufferOffset+i,chunksize); } } /** { // write all at once: BUGGY ! // outps.write(buffer,bufferOffset,nrBytes); }*/ outps.flush(); outps.close(); } } catch (Exception e) { throw convertException(e); } } public OutputStream createOutputStream(String path, boolean append) throws VlException { try { synchronized(serverMutex) { checkState(); // create private channel: ChannelSftp outputChannel = (ChannelSftp)session.openChannel("sftp"); outputChannel.connect(); int mode = ChannelSftp.APPEND; if (append==false) mode=ChannelSftp.OVERWRITE; OutputStream outps = outputChannel.put(path,mode); return new OutputStreamWatcher(outps,outputChannel); // return this.sftpChannel.put(path,ChannelSftp.OVERWRITE); } } catch (Exception e) { throw convertException(e); } } public String rename(String path, String newName, boolean nameIsPath) throws VlException { String newPath = null; if (nameIsPath == false) newPath = VRL.dirname(path) + VRL.SEP_CHAR + newName; else newPath = newName; Global.infoPrintln(this,"rename:" + path + "->" + newPath); Debug("rename:" + path + "->" + newPath); try { synchronized(serverMutex) { checkState(); sftpChannel.rename(path, newPath); } } catch (SftpException e) { boolean destExists=false; try { if (sftpChannel.stat(newPath)!=null) destExists=true; } catch (Exception e2) { destExists=false ; //ignore } if (destExists==true) throw new nl.uva.vlet.exception.ResourceAlreadyExistsException("Couldn't rename: destination already exists:"+newPath); throw convertException(e); } return newPath; } // ======================================================================= // Misc. // ======================================================================= private static void Debug(String msg) { //Global.errorPrintln(SFTPServer.class,msg); Global.debugPrintln(SftpFileSystem.class,msg); } private static String getJschErrorString(int id) { // nr matches index in error list if ((id >= 0) && (id < errorStringsList.length)) return errorStringsList[id]; return "Unknown Error"; } /** Convert Exceptions to something more human readable */ private VlException convertException(Exception e) { return convertException(e,null); } private VlException convertException(Exception e, String optMessage) { if (e instanceof VlException) return (VlException)e; // keep my own; // extra message: String message=""; if (optMessage!=null) message=optMessage+"\n"; String emsg=e.getMessage(); // Translate japanese enklish to Dutch Enklish if (emsg.startsWith("Auth fail")) { message+="Authentication failure\n" + "---\n--- sftp message --- \n"+emsg; return new nl.uva.vlet.exception.VlAuthenticationException(message,e); } else if (e instanceof SftpException) { SftpException ex=(SftpException)e; String reason = "Error =" + ex.id + ":" + getJschErrorString(ex.id) + "\n" + "message =" + ex.getMessage() + "\n" + "Channel connected=" + sftpChannel.isConnected() + "\n" + "Session connected=" + session.isConnected() + "\n"; //Global.messagePrintln(this,"sftp error="+getJschErrorString(ex.id)); if (ex.id==1) return new VlException(message+"End of file error",reason,e); if (ex.id==2) // SftpException reason 2=no such file ! return new ResourceNotFoundException(message+"StfpException:"+reason,e); if (ex.id==3) // don't know whether it is read or write return new VlException("AccessDenied",message+reason,e); return new VlException("SFTP Exception",message+reason,e); } else { return new VlException("Exception",message+e.getMessage(),e); } } // === // Factory methods // === public static SftpFileSystem createFor(VRSContext context,ServerInfo info) throws VlException { SftpFileSystem server = null; int port = info.getPort(); // update port if (info.getPort() <= 0) port = VRS.DEFAULT_SSH_PORT; String serverID = createServerID(info.getHostname(), port, info .getUsername()); synchronized (servers) { if ((server = servers.get(serverID)) == null) { Debug("Adding new SFTP Server:" + info.getID()); //Global.messagePrint("SFTPServer", ">>> Adding new SFTP Server:" // + info); server = new SftpFileSystem(context,info,info.getServerVRL()); servers.put(server.getServerID(), server); } server.setFinalUserSubject(context); } return server; } public static boolean existsServerFor(ServerInfo info) { if (info == null) return false; return existsServerFor(info.getHostname(), info.getPort(), info .getUsername()); } public static boolean existsServerFor(String host, int port2, String user) { String serverID = createServerID(host, port2, user); return (servers.get(serverID) != null); } public String toString() { return getServerID(); } public String getServerID() { return this.serverID; } public boolean isWritable(String path) throws VlException { // check user writable: SftpATTRS attrs=getSftpAttrs(path); int mod=attrs.getPermissions(); return ((mod & 0200)>0); } public boolean isReadable(String path) throws VlException { // check user readable: SftpATTRS attrs=getSftpAttrs(path); int mod=attrs.getPermissions(); return ((mod & 0400)>0); } public boolean isLink(String path) throws VlException { SftpATTRS attrs=getSftpAttrs(path); boolean val = attrs.isLink(); if (val) { String strs[]=attrs.getExtended(); if (strs!=null) { int i=0; for (String str:strs) { System.err.println(""+(i++)+":"+str); } } } return val; } /** Returns/home/<username> */ public String getHomeDir() { return defaultHome; } public VAttribute[][] getACL(String path, boolean isDir) throws VlException { SftpATTRS attrs = getSftpAttrs(path); // sftp support unix styl file permissions int mode = attrs.getPermissions(); return VFS.convertFileMode2ACL(mode, isDir); } public void setACL(String path, VAttribute[][] acl, boolean isDir) throws VlException { int mode = VFS.convertACL2FileMode(acl, isDir); if (mode < 0) throw new VlException("Error converting ACL list"); setPermissions(path, isDir,mode); } private void setPermissions(String path,boolean isDir,int mode) throws VlException { //SftpATTRS attrs=new SftpATTRS(); SftpATTRS attrs = getSftpAttrs(path); attrs.setPERMISSIONS(mode); setSftpAttrs(path, isDir,attrs); } public int getOwnerID(String path) throws VlException { //SftpATTRS attrs=new SftpATTRS(); SftpATTRS attrs = getSftpAttrs(path); return attrs.getUId(); } public int getGroupID(String path) throws VlException { //SftpATTRS attrs=new SftpATTRS(); SftpATTRS attrs = getSftpAttrs(path); return attrs.getGId(); } SftpATTRS attrs=null; public VAttribute getAttribute(VFSNode node,SftpATTRS attrs, String name, boolean isDir, boolean update) throws VlException { Debug("getAttribute for:"+node.getPath()+":"+name); //Optimization: only update if a SftpAttribute AND an update is requested: if (name==null) return null; // initialize attributes if not yet fetched! if (attrs==null) { attrs=this.getSftpAttrs(node.getPath()); } // get attributes from same holder: if (name.compareTo(ATTR_MODIFICATION_TIME)==0) { return VAttribute.createDateSinceEpoch(name,getModificationTime(attrs)); } else if (name.compareTo(ATTR_ACCESS_TIME)==0) { return new VAttribute(VAttributeType.TIME,name,getAccessTime(attrs)); } else if (name.compareTo(ATTR_LENGTH)==0) { return new VAttribute(name,attrs.getSize()); } else if (name.compareTo(ATTR_UID)==0) { return new VAttribute(name,attrs.getUId()); } else if (name.compareTo(ATTR_GID)==0) { return new VAttribute(name,attrs.getGId()); } else if (name.compareTo(ATTR_UNIX_FILE_MODE)==0) { // note sftp attributes return higher value the (8)07777 (isdir and islink) return new VAttribute(name,"0"+Integer.toOctalString(attrs.getPermissions()%07777)); } return null; } public VAttribute[] getAttributes(VFSNode node,SftpATTRS holder,String[] names, boolean isDir) throws VlException { if (names==null) return null; VAttribute attrs[]=new VAttribute[names.length]; for (int i=0;i<names.length;i++) { attrs[i]=getAttribute(node,holder,names[i],isDir,(i==0)); } return attrs; } public String getPermissionsString(SftpATTRS attrs, boolean isDir) throws VlException { return attrs.getPermissionsString(); } public int getUnixMode(SftpATTRS attrs, boolean isDir) throws VlException { return attrs.getPermissions(); } public int getPermissions(SftpATTRS attrs) throws VlException { return attrs.getPermissions(); } public long getModificationTime(SftpATTRS attrs) { return attrs.getMTime()*1000L; } public long getAccessTime(SftpATTRS attrs) { return attrs.getATime()*1000L; } public long getLength(SftpATTRS attrs) { return attrs.getSize(); } //For the new clear() method: public static void clearServers() { for (Enumeration<String> keys = servers.keys();keys.hasMoreElements();) { String key=(String)keys.nextElement(); SftpFileSystem server = servers.get(key); try { server.disconnect(); } catch (VlException e) { // TODO Auto-generated catch block e.printStackTrace(); } } servers.clear(); } // ======================================================================= // VServer interface // ======================================================================= public void connect() throws VlException { this.jschInstance = new JSch(); ServerInfo info=this.getServerInfo(); String sshdir=Global.getUserHome()+"/.ssh"; String idFile=sshdir+"/"+getSSHIndentity();// check multiple files ? try { if (new java.io.File(idFile).exists()==false) idFile=null; jschInstance.setKnownHosts(sshdir+"/known_hosts"); if (idFile!=null) jschInstance.addIdentity(idFile); jschInstance.setKnownHosts(getKnowHostsFile()); } catch (Exception e) { Global.errorPrintln(this,"Error initializing jCraft SSH:"+e); Global.errorPrintStacktrace(e); } // System.out.println("s:" + server + " p:" + port + " u:" + user); try { int port=getPort(); if (port<=0) port=VRS.DEFAULT_SSH_PORT; this.session = jschInstance.getSession(userInfo.getUsername(), getHostname(),port); // ssh.setSocketTimeout(timeout); session.setUserInfo(userInfo); session.connect(); //channel.setExtOutputStream(new OutputLog()); //channel.setOutputStream(new OutputLog()); this.sftpChannel = createNewFTPChannel(); Debug("Connected to:" + getHostname() + ":" + getPort()); // valid authentication info.setHasValidAuthentication(true); info.store(); // update in registry ! try { defaultHome=this.sftpChannel.pwd(); } catch (SftpException e) { // can not get pwd() ? throw convertException(e); } Debug("defaultHome="+defaultHome); } catch (JSchException e) { info.setHasValidAuthentication(false); // invalidize authentication info ! info.store(); // Update in registry ! throw convertException(e); } try { HostKeyRepository hkr=jschInstance.getHostKeyRepository(); HostKey hk=session.getHostKey(); } catch (Exception e) { Global.errorPrintln(this,"Error initializing jCraft SSH:"+e); Global.errorPrintStacktrace(e); } } private String getSSHIndentity() { String idStr=getServerInfo().getStringProperty(ServerInfo.ATTR_SSH_IDENTITY); if (idStr!=null) return idStr; return "id_rsa"; } public void disconnect() throws VlException { synchronized(serverMutex) { this.sftpChannel.disconnect(); this.session.disconnect(); this.jschInstance=null; this.session=null; this.sftpChannel=null; } } public String getID() { return this.serverID; } public String getScheme() { return VFS.SFTP_SCHEME; } public boolean isConnected() { if (this.sftpChannel!=null) return this.sftpChannel.isConnected(); return false; } private String getKnowHostsFile() { ServerInfo info=this.getServerInfo(); VAttribute attr=info.getAttribute(SftpFSFactory.ATTR_KNOWN_HOSTS_FILE); if (attr==null) return getDefaultKnownHostsFile(); else return attr.getStringValue(); } public String getSSHConfigDir() { ServerInfo info=this.getServerInfo(); VAttribute attr=info.getAttribute(SftpFSFactory.ATTR_SSH_CONFIG_DIR); if (attr==null) return getDefaultSSHDir(); else return attr.getStringValue(); } public boolean getAllowUserInterAction() { return this.vrsContext.getConfigManager().getAllowUserInteraction(); } public String getDefaultKnownHostsFile() { return getDefaultSSHDir()+"/known_hosts"; } public String getDefaultSSHDir() { return vrsContext.getLocalUserHome()+VRL.SEP_CHAR_STR+".ssh"; } private void setFinalUserSubject(VRSContext newContext) throws VlAuthenticationException { String newSubject=newContext.getGridProxy().getSubject(); if (this.userSubject!=null) { if (this.userSubject.compareTo(newSubject)!=0) { // OOPSY!! throw new nl.uva.vlet.exception.VlAuthenticationException("Illegal User. Current server is not authenticated for new user:"+newSubject); } } else // May Be Set Only Once !!! this.userSubject=newSubject; } public String getUserSubject() { return this.userSubject; } public String getLinkTarget(String path) { return null; } @Override public VDir newDir(VRL path) throws VlException { return new SftpDir(this,path); } @Override public VFile newFile(VRL path) throws VlException { return new SftpFile(this,path); } /** * Create localPort which connected to remoteHost:remotePort * @throws VlException */ public void createOutgoingTunnel(int localPort,String remoteHost,int remotePort) throws VlException { try { String[] list = this.session.getPortForwardingL(); String optStr=""+localPort+":"+remoteHost.toLowerCase()+":"+remotePort; for (String s:list) { if (StringUtil.equalsIgnoreCase(optStr,s)) { Global.warnPrintln(this,"Outgoing port forwarding already exists:"+s); return; } } //jsch doesn it all: this.session.setPortForwardingL(localPort,remoteHost,remotePort); Global.errorPrintln(this,"New SSH tunnel="+optStr); } catch (JSchException e) { throw this.convertException(e,"Couldn't create remote port forwarding:"+localPort+":"+remoteHost+":"+remotePort); } } /** Create localPort which connected to remoteHost:remotePort * @throws VlException */ public void createIncomingTunnel(int remotePort,String localHost,int localPort) throws VlException { try { //jsch doesn it all: this.session.setPortForwardingR(remotePort,localHost,localPort); } catch (JSchException e) { throw this.convertException(e,"Couldn't create incoming port forwarding:"+remotePort+":"+localHost+":"+localPort); } } /** Creates a new outgoing SSH tunnel and return the local tunnel port * @throws VlException */ public int createOutgoingTunnel(String bdiiHost, int bdiiPort) throws VlException { VlException lastEx=null; for (int i=0;i<32;i++) { int lport=getFreeLocalPort(); try { this.createOutgoingTunnel(lport,bdiiHost, bdiiPort); usedLocalPorts.add(new Integer(lport)); return lport; } catch (VlException e) { lastEx=e; Global.errorPrintln(this,"Failed to create new local tunnel port:"+lport+"\n"+e); } } if (lastEx!=null) throw lastEx; throw new VlException("Failed to create new local tunnel port"); } public static int getFreeLocalPort() { // use randomizer for now: (is much faster!) int offset=10000; int max=65535; int port=0; for (int i=0;i<100;i++) { port=offset+portRandomizer.nextInt(max-offset); // Integer(A) equals Integer(B) when (int)A==(int)B. if (usedLocalPorts.contains(new Integer(port))==false) return port; } return -1; } public SSHChannel createShellChannel(VRL optLocation) throws VlException { SSHChannelOptions options = new SSHChannelOptions(); SSHChannel sshChannel = new SSHChannel(vrsContext, getUsername(), getHostname(), getPort(), options); String path=optLocation.getPath(); try { // connect but re-use current session and options; sshChannel.connectTo(session); sshChannel.setCWD(path); return sshChannel; } catch (IOException e) { throw new VlException(e); } } }
source/core/nl.uva.vlet.vfs.jcraft.ssh/src/nl/uva/vlet/vfs/jcraft/ssh/SftpFileSystem.java
/* * Copyright 2006-2011 The Virtual Laboratory for e-Science (VL-e) * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * For details, see the LICENCE.txt file location in the root directory of this * distribution or obtain the Apache Licence at the following location: * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * See: http://www.vl-e.nl/ * See: LICENCE.txt (located in the root folder of this distribution). * --- * $Id: SftpFileSystem.java,v 1.2 2011-12-07 10:19:58 ptdeboer Exp $ * $Date: 2011-12-07 10:19:58 $ */ // source: package nl.uva.vlet.vfs.jcraft.ssh; import static nl.uva.vlet.data.VAttributeConstants.ATTR_ACCESS_TIME; import static nl.uva.vlet.data.VAttributeConstants.ATTR_GID; import static nl.uva.vlet.data.VAttributeConstants.ATTR_LENGTH; import static nl.uva.vlet.data.VAttributeConstants.ATTR_MODIFICATION_TIME; import static nl.uva.vlet.data.VAttributeConstants.ATTR_UID; import static nl.uva.vlet.data.VAttributeConstants.ATTR_UNIX_FILE_MODE; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.Hashtable; import java.util.Random; import java.util.Vector; import nl.uva.vlet.Global; import nl.uva.vlet.data.StringHolder; import nl.uva.vlet.data.StringUtil; import nl.uva.vlet.data.VAttribute; import nl.uva.vlet.data.VAttributeType; import nl.uva.vlet.exception.ResourceAlreadyExistsException; import nl.uva.vlet.exception.ResourceCreationFailedException; import nl.uva.vlet.exception.ResourceNotFoundException; import nl.uva.vlet.exception.VlAuthenticationException; import nl.uva.vlet.exception.VlException; import nl.uva.vlet.io.StreamUtil; import nl.uva.vlet.vfs.FileSystemNode; import nl.uva.vlet.vfs.VDir; import nl.uva.vlet.vfs.VFS; import nl.uva.vlet.vfs.VFSNode; import nl.uva.vlet.vfs.VFSTransfer; import nl.uva.vlet.vfs.VFile; import nl.uva.vlet.vfs.jcraft.ssh.SSHChannel.SSHChannelOptions; import nl.uva.vlet.vrl.VRL; import nl.uva.vlet.vrs.ServerInfo; import nl.uva.vlet.vrs.VRS; import nl.uva.vlet.vrs.VRSContext; import nl.uva.vlet.vrs.io.VShellChannelCreator; import nl.uva.vlet.vrs.net.VOutgoingTunnelCreator; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.HostKey; import com.jcraft.jsch.HostKeyRepository; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpATTRS; import com.jcraft.jsch.SftpException; import com.jcraft.jsch.SftpProgressMonitor; import com.jcraft.jsch.UserInfo; /** * SFTP FileSystem implementation. * The jsch session can provide a FTP channel and a command line channel. * Also tunneling is supported by the API. */ public class SftpFileSystem extends FileSystemNode implements VOutgoingTunnelCreator, VShellChannelCreator { // === class stuff private static Hashtable<String, SftpFileSystem> servers = new Hashtable<String, SftpFileSystem>(); private static String createServerID(String host, int port, String user) { // must use default port in ServerID ! if (port <= 0) port = VRS.DEFAULT_SSH_PORT; return user + "@" + host + ":" + port; } public class VLUserInfo implements UserInfo { public VLUserInfo() { super(); } public String getUsername() { return getServerInfo().getUsername(); } public String getPassphrase() { return getServerInfo().getPassphrase(); } public String getPassword() { return getServerInfo().getPassword(); } // this object has no acces to the gui... public boolean promptPassword(String message) { if (getAllowUserInterAction()==false) { // use store password: if (StringUtil.isEmpty(getPassword())==false) return true; return false; } // getVRSContext().getConfigManager().getHasUI(); String field=uiPromptPassfield(message); if (field!=null) { getServerInfo().setPassword(field); field=null; return true; } return false; } public boolean promptPassphrase(String message) { if (getAllowUserInterAction()==false) { // use store password: if (StringUtil.isEmpty(getPassphrase())==false) return true; return false; } // jSch doesn't provide username in message ! message="Authentication needed for: "+getUsername()+"@"+getHostname()+"\n" +message; // getVRSContext().getConfigManager().getHasUI(); String field=uiPromptPassfield(message); if (field!=null) { getServerInfo().setPassphrase(field); field=null; return true; } return false; } public String uiPromptPassfield(String message) { StringHolder secretHolder=new StringHolder(null); boolean result=getVRSContext().getUI().askAuthentication(message, secretHolder); if (result == true) return secretHolder.value; else return null; } public void showMessage(String message) { if (getAllowUserInterAction()==false) { return; } else { getVRSContext().getUI().showMessage(message); } } public boolean promptYesNo(String message) { if (getAllowUserInterAction()==false) { return getDefaultYesNoAnswer(message); } else { return getVRSContext().getUI().askYesNo("Yes or No?",message, false); } } } // ============================================================================= // ============================================================================= private static Random portRandomizer=new Random(); private static Vector<Integer> usedLocalPorts=new Vector<Integer>(); public VRL getServerVRL() { return new VRL(VRS.SFTP_SCHEME,null,this.getHostname(),getPort(),null); } /* public static final int SSH_FX_OK = 0; public static final int SSH_FX_EOF = 1; public static final int SSH_FX_NO_SUCH_FILE = 2; public static final int SSH_FX_PERMISSION_DENIED = 3; public static final int SSH_FX_FAILURE = 4; public static final int SSH_FX_BAD_MESSAGE = 5; public static final int SSH_FX_NO_CONNECTION = 6; public static final int SSH_FX_CONNECTION_LOST = 7; public static final int SSH_FX_OP_UNSUPPORTED = 8; */ public static String[] errorStringsList = { "SSH:OK", // 0=No error SSH_FX_OK "SSH:End of file reached", // 1=SSH_FX_EOF "SSH:No such file", // 2=SSH_FX_NO_SUCH_FILE "SSH:Permission denied", // 3=... "SSH:General failure", // 4 "SSH:Bad message", // 5 "SSH:No connection", // 6 "SSH:Connection lost", // 7 "SSH:Unsupported operation" // 8 }; // ======================================================================= // Instance // ======================================================================= // === instanceSSH_FX_OK //private String hostname = null; //private int port = DEFAULT_SSH_PORT; private ChannelSftp sftpChannel; private nl.uva.vlet.vfs.jcraft.ssh.SftpFileSystem.VLUserInfo userInfo; private JSch jschInstance; private Session session; final Boolean serverMutex=new Boolean(true); private String defaultHome="/"; private String userSubject; // ======================================================================= // Server Critical // ======================================================================= private void init(ServerInfo info) throws VlException { Debug("init for:" + info.getUsername() + "@" + getHostname() + ":" + getPort()); this.userInfo = new VLUserInfo(); this.serverID = createServerID(getHostname(), getPort(), info.getUsername()); this.connect(); } /** * */ public SftpFileSystem(VRSContext context,ServerInfo info, VRL location) throws VlException { super(context,info); init(info); Debug("New:" + this); } public String getUsername() { return this.userInfo.getUsername(); } // ======================================================================= // Authentication // ======================================================================= public boolean getDefaultYesNoAnswer(String optMessage) { return this.getServerInfo().getBoolProperty(ServerInfo.ATTR_DEFAULT_YES_NO_ANSWER, false); } public void setDefaultYesNoAnswer(boolean value) { ServerInfo info=getServerInfo(); info.setAttribute(ServerInfo.ATTR_DEFAULT_YES_NO_ANSWER, value); info.store(); } // ======================================================================= // === synchronized methods === // ======================================================================= public VFSNode openLocation(VRL vrl) throws VlException { // No Exceptions: store ServerInfo ! String path=vrl.getPath(); if ((path==null) || (path.compareTo("")==0)) path=getHomeDir(); // ~/ home expansion if (path.startsWith("~")) path=getHomeDir()+path.substring(1); if (path.startsWith("/~")) path=getHomeDir()+path.substring(2); return getPath(path); } public VFSNode getPath(String path) throws VlException { String user = getUsername(); int port = getPort(); String host = getHostname(); // '~' expansion -> default home if (path.startsWith("~")) path=defaultHome+"/"+path.substring(1,path.length()); else if (path.startsWith("/~")) path=defaultHome+"/"+path.substring(2,path.length()); // // hide default port from location // IMPORTANT: must match accountID in ServerInfo ! // if (port == VRS.DEFAULT_SSH_PORT) port = 0; VRL vrl = new VRL(VRS.SFTP_SCHEME, user, host, port, path); Debug("getPath:" + path); SftpATTRS attrs = null; try { synchronized(serverMutex) { checkState(); // Must throw the right Exception: /*// cd to dirname to speed up stat String pwd=sftpChannel.pwd(); String dirname=VRL.dirname(path); if (pwd.compareTo(dirname)!=0) { Debug("cd to:"+dirname); sftpChannel.cd(dirname); } attrs = sftpChannel.lstat(VRL.basename(path)); //attrs = sftpChannel.stat(VRL.basename(path)); */ // do not resolve (possivle errornous) link: attrs=this.getSftpAttrs(path,false); } } catch (Exception e) { throw convertException(e); } if (attrs == null) { throw new ResourceNotFoundException("Couldn't stat:" + path); } else if (attrs.isDir()) { return new SftpDir(this, vrl); } else if (attrs.isLink()) { // resolve link: check attributes SftpATTRS targetAttrs=null; try { targetAttrs=getSftpAttrs(path,true); // Link Target Error: return as file if (targetAttrs!=null) { // return linked directory as VDir ! (not file) if (targetAttrs.isDir()) { return new SftpDir(this, vrl); } } } catch (Exception e) { Debug("??? Exception when resolving link:"+vrl+" Exception="+e); } } // default: return as file return new SftpFile(this, vrl); } public void myDispose() { synchronized(serverMutex) { try { disconnect(); } catch (VlException e) { // TODO Auto-generated catch block e.printStackTrace(); } servers.remove(this); } } public String[] list(String path) throws VlException { Debug("listing:" + path); try { java.util.Vector<?> dirList; synchronized(serverMutex) { try { checkState(); dirList = sftpChannel.ls(path); } catch (Exception e) { checkState(); dirList = sftpChannel.ls(path); } } int index = 0; String childs[] = new String[dirList.size()]; for (int i = 0; i < dirList.size(); i++) { Object entry = dirList.elementAt(i); if (entry instanceof com.jcraft.jsch.ChannelSftp.LsEntry) { ChannelSftp.LsEntry lsEntry = (ChannelSftp.LsEntry) entry; childs[index] = lsEntry.getFilename(); } else { Global.errorPrintln(this,"ls() returned unknown entry[" + index + "]=" + entry.getClass().getCanonicalName()); childs[index] = null; } index++; } return childs; } catch (SftpException e) { throw convertException(e,"Could not list contents of remote path:"+path); } } private void checkState() throws VlException { try { synchronized(serverMutex) { if (this.session.isConnected() == false) { Global.errorPrintln(this, "Session disconnected: reconnecting:" + this); session = jschInstance.getSession(userInfo.getUsername(), getHostname(), getPort()); session.setUserInfo(userInfo); session.connect(); if (sftpChannel.isConnected()==true) sftpChannel.disconnect(); sftpChannel=null; } if ((this.sftpChannel==null) || this.sftpChannel.isConnected()==false) { Global.errorPrintln(this, "Channel closed: reconnecting:" + this); this.sftpChannel = (ChannelSftp) session.openChannel("sftp"); sftpChannel.connect(); } } } /*catch (SftpException e1) { throw convertException(e1); }*/ catch (JSchException e) { throw convertException(e); } } public boolean existsPath(String path, boolean checkDir) throws VlException { Debug("existsPath:"+path); try { synchronized(serverMutex) { SftpATTRS attrs; try { checkState(); attrs = sftpChannel.lstat(path); } catch (Exception e) { checkState(); attrs = sftpChannel.lstat(path); } // sadly stat generates an exception when the path doesn't exists, // so the following code will not be executed. if (attrs == null) { return false; } else { if (checkDir==true) { if (attrs.isDir()==true) { return true; } else { // exists but is NOT a directory ! return false; } } else { if (attrs.isDir()==false) { return true; } else { // exists but is NOT a file ! return false; } } } } } catch (Exception e) { if (e instanceof SftpException) { SftpException ex=(SftpException)e; //Global.messagePrintln(this,"after existsPath, session="+this.session.isConnected()); //Global.messagePrintln(this,"after existsPath, channel="+this.sftpChannel.isConnected()); // SftpException reason 2=no such file ! if (ex.id==2) return false; } // other reason: throw convertException(e,"Could not stat remote path:"+path); } } public void uploadFile(VFSTransfer transfer,String localfilepath, String remotefilepath) throws VlException { try { synchronized(serverMutex) { checkState(); // jCraft has a tranfer interface ! SftpTransferMonitor monitor=new SftpTransferMonitor(transfer); this.sftpChannel.put(localfilepath,remotefilepath,monitor); } } catch(Exception e) { throw convertException(e,"Error when uploading file to remote paths:"+remotefilepath); } } public void downloadFile(VFSTransfer transfer, String remotefilepath, String localfilepath) throws VlException { try { synchronized(serverMutex) { checkState(); // jCraft has a tranfer interface ! SftpTransferMonitor monitor=new SftpTransferMonitor(transfer); this.sftpChannel.get(remotefilepath,localfilepath,monitor); } } catch(Exception e) { throw convertException(e,"Error when downloading file to local path:"+localfilepath); } } public VDir createDir(String dirpath, boolean ignoreExisting) throws VlException { // check existing! SftpATTRS attrs=null; //checkAndCreateParentDir(VRL.dirname(dirpath),force); try { // check existing! attrs = this.getSftpAttrs(dirpath,ignoreExisting); } catch (Exception e) { ; // ignore } // exists: if (attrs!=null) { if (attrs.isDir()==false) throw new ResourceCreationFailedException("path already exists but is not a directory:"+this); if (ignoreExisting == false) throw new ResourceAlreadyExistsException("path already exists (use ignoreExisting==true to overwrite) :"+this); else return (VDir) getPath(dirpath); } try { synchronized(serverMutex) { checkState(); sftpChannel.mkdir(dirpath); } return (VDir) getPath(dirpath); } catch (SftpException e) { throw convertException(e,"Error when creating remote directory:"+dirpath); } } private void checkAndCreateParentDir(String dirname, boolean force) throws VlException { SftpATTRS parentAttrs=null; try { // check existing parent: parentAttrs = this.getSftpAttrs(dirname,force); } catch (Exception e) { ; // ignore } // create parent first if (parentAttrs==null) createDir(dirname,force); } public VFile createFile(String filepath, boolean force) throws VlException { SftpATTRS attrs=null; // checkAndCreateParentDir(VRL.dirname(filepath),force); try { // stat: attrs= this.getSftpAttrs(filepath); } catch (Exception e) { ; // ignore; } if (attrs!=null) { // exists: if (force == false) throw new ResourceAlreadyExistsException("path already exists:"+this); if (attrs.isDir()==true) throw new ResourceAlreadyExistsException("path already exists but is a directory:"+this); if (attrs.isLink()==true) throw new ResourceAlreadyExistsException("path already exists but is a symbolic link:"+this); // delete existing: delete(filepath, false); } // create new: // write null bytes byte nulbuf[] = new byte[0]; OutputStream out; try { synchronized(this.serverMutex) { checkState(); OutputStream output= this.sftpChannel.put(filepath,ChannelSftp.OVERWRITE); output.write(nulbuf); output.flush(); output.close(); } VFSNode node = getPath(filepath); if (node instanceof VFile) { return (VFile) node; } else { throw new ResourceCreationFailedException( "path exists, but is not a file:" + filepath); } } catch (Exception e) { throw this.convertException(e,"Could not create file:"+filepath); } } public SftpATTRS getSftpAttrs(String filepath) throws VlException { return getSftpAttrs(filepath,false); } public boolean delete(String path, boolean isDir) throws VlException { try { synchronized(serverMutex) { checkState(); if (isDir == false) { sftpChannel.rm(path); } else { sftpChannel.rmdir(path); } } return (existsPath(path,isDir) == false); } catch (Exception e) { throw convertException(e); } } /*public int isOwner() { SftpATTRS attrs=getSftpAttrs(path); attrs.getPermissions(); attrs.getUId(); }*/ public SftpATTRS getSftpAttrs(String path,boolean resolveLink) throws VlException { Debug("getSftpAttrs:"+path); try { synchronized(serverMutex) { try { checkState(); if (resolveLink==false) return sftpChannel.lstat(path); else return sftpChannel.stat(path); } catch (Exception e) { checkState(); if (resolveLink==false) return sftpChannel.lstat(path); else return sftpChannel.stat(path); } } } catch (Exception e) { //System.err.println("Exception when statting:"+path); throw convertException(e,"Could not stat remote path:"+path); } } private ChannelSftp createNewFTPChannel() throws VlException { Debug("createNewChannel:"+this); try { ChannelSftp channel; channel = (ChannelSftp)session.openChannel("sftp"); channel.connect(); return channel; } catch (JSchException e) { throw convertException(e,"Couldn't create new channel to:"+this); } } public void setSftpAttrs(String path,boolean isDir, SftpATTRS attrs) throws VlException { try { synchronized(serverMutex) { checkState(); sftpChannel.setStat(path, attrs); } } catch (SftpException e) { // find out what is wrong: if (this.existsPath(path,isDir) == false) { // Error Handling: return better Exception throw new ResourceNotFoundException("Path doesn't exists:" + path); } else { throw convertException(e); } } } public InputStream createInputStream(String path) throws VlException { try { ChannelSftp newChannel=null; synchronized(serverMutex) { checkState(); // old: // return this.sftpChannel.get(path); // open up a new channel for multithreaded viewing ! newChannel =(ChannelSftp) this.session.openChannel("sftp"); } newChannel.connect(); InputStream inps=newChannel.get(path); return new InputStreamWatcher(newChannel,inps); } catch (Exception e) { throw convertException(e); } //return null; } public int readBytes(String path, long fileOffset, byte[] buffer, int bufferOffset, int nrBytes) throws VlException { try { /*if (true) { ByteArrayOutputStream outpBuffer=new ByteArrayOutputStream(nrBytes); synchronized(serverMutex) { sftpChannel.get(path, outpBuffer, null,nrBytes,fileOffset); byte[] sourcebuf = outpBuffer.toByteArray(); System.arraycopy(sourcebuf,0,buffer,bufferOffset,nrBytes); int numread=nrBytes; return numread; } } else */ { // // Emulate Random Read by using StreamRead: // This method is also used in VFile.read(...) // InputStream inps; synchronized(serverMutex) { checkState(); inps = sftpChannel.get(path); } //DONE BY SYNC READ: inps.skip(fileOffset); int numread = StreamUtil.syncReadBytes(inps, fileOffset, buffer, bufferOffset,nrBytes); inps.close(); return numread; } } catch (Exception e) { throw convertException(e); } } /** * TODO: Still buggy */ public void writeBytes(String path, long fileOffset, byte[] buffer, int bufferOffset, int nrBytes) throws VlException { OutputStream outps; //int mode=ChannelSftp.RESUME; int mode=ChannelSftp.OVERWRITE; // must currently write in 32000 byte sized chunks int chunksize=32000; // skip existing bytes: if (fileOffset>0) mode=ChannelSftp.RESUME; try { synchronized(serverMutex) { checkState(); // TODO: MODE !!! outps = sftpChannel.put(path, (SftpProgressMonitor)null,mode, fileOffset); // chunk write: { // write in chunks: for (int i=0;i<nrBytes;i+=chunksize) { if (i+chunksize>nrBytes) chunksize=nrBytes-i; outps.write(buffer,bufferOffset+i,chunksize); } } /** { // write all at once: BUGGY ! // outps.write(buffer,bufferOffset,nrBytes); }*/ outps.flush(); outps.close(); } } catch (Exception e) { throw convertException(e); } } public OutputStream createOutputStream(String path, boolean append) throws VlException { try { synchronized(serverMutex) { checkState(); // create private channel: ChannelSftp outputChannel = (ChannelSftp)session.openChannel("sftp"); outputChannel.connect(); int mode = ChannelSftp.APPEND; if (append==false) mode=ChannelSftp.OVERWRITE; OutputStream outps = outputChannel.put(path,mode); return new OutputStreamWatcher(outps,outputChannel); // return this.sftpChannel.put(path,ChannelSftp.OVERWRITE); } } catch (Exception e) { throw convertException(e); } } public String rename(String path, String newName, boolean nameIsPath) throws VlException { String newPath = null; if (nameIsPath == false) newPath = VRL.dirname(path) + VRL.SEP_CHAR + newName; else newPath = newName; Global.infoPrintln(this,"rename:" + path + "->" + newPath); Debug("rename:" + path + "->" + newPath); try { synchronized(serverMutex) { checkState(); sftpChannel.rename(path, newPath); } } catch (SftpException e) { boolean destExists=false; try { if (sftpChannel.stat(newPath)!=null) destExists=true; } catch (Exception e2) { destExists=false ; //ignore } if (destExists==true) throw new nl.uva.vlet.exception.ResourceAlreadyExistsException("Couldn't rename: destination already exists:"+newPath); throw convertException(e); } return newPath; } // ======================================================================= // Misc. // ======================================================================= private static void Debug(String msg) { //Global.errorPrintln(SFTPServer.class,msg); Global.debugPrintln(SftpFileSystem.class,msg); } private static String getJschErrorString(int id) { // nr matches index in error list if ((id >= 0) && (id < errorStringsList.length)) return errorStringsList[id]; return "Unknown Error"; } /** Convert Exceptions to something more human readable */ private VlException convertException(Exception e) { return convertException(e,null); } private VlException convertException(Exception e, String optMessage) { if (e instanceof VlException) return (VlException)e; // keep my own; // extra message: String message=""; if (optMessage!=null) message=optMessage+"\n"; String emsg=e.getMessage(); // Translate japanese enklish to Dutch Enklish if (emsg.startsWith("Auth fail")) { message+="Authentication failure\n" + "---\n--- sftp message --- \n"+emsg; return new nl.uva.vlet.exception.VlAuthenticationException(message,e); } else if (e instanceof SftpException) { SftpException ex=(SftpException)e; String reason = "Error =" + ex.id + ":" + getJschErrorString(ex.id) + "\n" + "message =" + ex.getMessage() + "\n" + "Channel connected=" + sftpChannel.isConnected() + "\n" + "Session connected=" + session.isConnected() + "\n"; //Global.messagePrintln(this,"sftp error="+getJschErrorString(ex.id)); if (ex.id==1) return new VlException(message+"End of file error",reason,e); if (ex.id==2) // SftpException reason 2=no such file ! return new ResourceNotFoundException(message+"StfpException:"+reason,e); if (ex.id==3) // don't know whether it is read or write return new VlException("AccessDenied",message+reason,e); return new VlException("SFTP Exception",message+reason,e); } else { return new VlException("Exception",message+e.getMessage(),e); } } // === // Factory methods // === public static SftpFileSystem createFor(VRSContext context,ServerInfo info) throws VlException { SftpFileSystem server = null; int port = info.getPort(); // update port if (info.getPort() <= 0) port = VRS.DEFAULT_SSH_PORT; String serverID = createServerID(info.getHostname(), port, info .getUsername()); synchronized (servers) { if ((server = servers.get(serverID)) == null) { Debug("Adding new SFTP Server:" + info.getID()); //Global.messagePrint("SFTPServer", ">>> Adding new SFTP Server:" // + info); server = new SftpFileSystem(context,info,info.getServerVRL()); servers.put(server.getServerID(), server); } server.setFinalUserSubject(context); } return server; } public static boolean existsServerFor(ServerInfo info) { if (info == null) return false; return existsServerFor(info.getHostname(), info.getPort(), info .getUsername()); } public static boolean existsServerFor(String host, int port2, String user) { String serverID = createServerID(host, port2, user); return (servers.get(serverID) != null); } public String toString() { return getServerID(); } public String getServerID() { return this.serverID; } public boolean isWritable(String path) throws VlException { // check user writable: SftpATTRS attrs=getSftpAttrs(path); int mod=attrs.getPermissions(); return ((mod & 0200)>0); } public boolean isReadable(String path) throws VlException { // check user readable: SftpATTRS attrs=getSftpAttrs(path); int mod=attrs.getPermissions(); return ((mod & 0400)>0); } public boolean isLink(String path) throws VlException { SftpATTRS attrs=getSftpAttrs(path); boolean val = attrs.isLink(); if (val) { String strs[]=attrs.getExtended(); if (strs!=null) { int i=0; for (String str:strs) { System.err.println(""+(i++)+":"+str); } } } return val; } /** Returns/home/<username> */ public String getHomeDir() { return defaultHome; } public VAttribute[][] getACL(String path, boolean isDir) throws VlException { SftpATTRS attrs = getSftpAttrs(path); // sftp support unix styl file permissions int mode = attrs.getPermissions(); return VFS.convertFileMode2ACL(mode, isDir); } public void setACL(String path, VAttribute[][] acl, boolean isDir) throws VlException { int mode = VFS.convertACL2FileMode(acl, isDir); if (mode < 0) throw new VlException("Error converting ACL list"); setPermissions(path, isDir,mode); } private void setPermissions(String path,boolean isDir,int mode) throws VlException { //SftpATTRS attrs=new SftpATTRS(); SftpATTRS attrs = getSftpAttrs(path); attrs.setPERMISSIONS(mode); setSftpAttrs(path, isDir,attrs); } public int getOwnerID(String path) throws VlException { //SftpATTRS attrs=new SftpATTRS(); SftpATTRS attrs = getSftpAttrs(path); return attrs.getUId(); } public int getGroupID(String path) throws VlException { //SftpATTRS attrs=new SftpATTRS(); SftpATTRS attrs = getSftpAttrs(path); return attrs.getGId(); } SftpATTRS attrs=null; public VAttribute getAttribute(VFSNode node,SftpATTRS attrs, String name, boolean isDir, boolean update) throws VlException { Debug("getAttribute for:"+node.getPath()+":"+name); //Optimization: only update if a SftpAttribute AND an update is requested: if (name==null) return null; // initialize attributes if not yet fetched! if (attrs==null) { attrs=this.getSftpAttrs(node.getPath()); } // get attributes from same holder: if (name.compareTo(ATTR_MODIFICATION_TIME)==0) { return VAttribute.createDateSinceEpoch(name,getModificationTime(attrs)); } else if (name.compareTo(ATTR_ACCESS_TIME)==0) { return new VAttribute(VAttributeType.TIME,name,getAccessTime(attrs)); } else if (name.compareTo(ATTR_LENGTH)==0) { return new VAttribute(name,attrs.getSize()); } else if (name.compareTo(ATTR_UID)==0) { return new VAttribute(name,attrs.getUId()); } else if (name.compareTo(ATTR_GID)==0) { return new VAttribute(name,attrs.getGId()); } else if (name.compareTo(ATTR_UNIX_FILE_MODE)==0) { // note sftp attributes return higher value the (8)07777 (isdir and islink) return new VAttribute(name,"0"+Integer.toOctalString(attrs.getPermissions()%07777)); } return null; } public VAttribute[] getAttributes(VFSNode node,SftpATTRS holder,String[] names, boolean isDir) throws VlException { if (names==null) return null; VAttribute attrs[]=new VAttribute[names.length]; for (int i=0;i<names.length;i++) { attrs[i]=getAttribute(node,holder,names[i],isDir,(i==0)); } return attrs; } public String getPermissionsString(SftpATTRS attrs, boolean isDir) throws VlException { return attrs.getPermissionsString(); } public int getUnixMode(SftpATTRS attrs, boolean isDir) throws VlException { return attrs.getPermissions(); } public int getPermissions(SftpATTRS attrs) throws VlException { return attrs.getPermissions(); } public long getModificationTime(SftpATTRS attrs) { return attrs.getMTime()*1000L; } public long getAccessTime(SftpATTRS attrs) { return attrs.getATime()*1000L; } public long getLength(SftpATTRS attrs) { return attrs.getSize(); } //For the new clear() method: public static void clearServers() { for (Enumeration<String> keys = servers.keys();keys.hasMoreElements();) { String key=(String)keys.nextElement(); SftpFileSystem server = servers.get(key); try { server.disconnect(); } catch (VlException e) { // TODO Auto-generated catch block e.printStackTrace(); } } servers.clear(); } // ======================================================================= // VServer interface // ======================================================================= public void connect() throws VlException { this.jschInstance = new JSch(); ServerInfo info=this.getServerInfo(); String sshdir=Global.getUserHome()+"/.ssh"; String idFile=sshdir+"/"+getSSHIndentity();// check multiple files ? try { if (new java.io.File(idFile).exists()==false) idFile=null; jschInstance.setKnownHosts(sshdir+"/known_hosts"); if (idFile!=null) jschInstance.addIdentity(idFile); jschInstance.setKnownHosts(getKnowHostsFile()); } catch (Exception e) { Global.errorPrintln(this,"Error initializing jCraft SSH:"+e); Global.errorPrintStacktrace(e); } // System.out.println("s:" + server + " p:" + port + " u:" + user); try { int port=getPort(); if (port<=0) port=VRS.DEFAULT_SSH_PORT; this.session = jschInstance.getSession(userInfo.getUsername(), getHostname(),port); // ssh.setSocketTimeout(timeout); session.setUserInfo(userInfo); session.connect(); //channel.setExtOutputStream(new OutputLog()); //channel.setOutputStream(new OutputLog()); this.sftpChannel = createNewFTPChannel(); Debug("Connected to:" + getHostname() + ":" + getPort()); // valid authentication info.setHasValidAuthentication(true); info.store(); // update in registry ! try { defaultHome=this.sftpChannel.pwd(); } catch (SftpException e) { // can not get pwd() ? throw convertException(e); } Debug("defaultHome="+defaultHome); } catch (JSchException e) { info.setHasValidAuthentication(false); // invalidize authentication info ! info.store(); // Update in registry ! throw convertException(e); } try { HostKeyRepository hkr=jschInstance.getHostKeyRepository(); HostKey hk=session.getHostKey(); } catch (Exception e) { Global.errorPrintln(this,"Error initializing jCraft SSH:"+e); Global.errorPrintStacktrace(e); } } private String getSSHIndentity() { String idStr=getServerInfo().getStringProperty(ServerInfo.ATTR_SSH_IDENTITY); if (idStr!=null) return idStr; return "id_rsa"; } public void disconnect() throws VlException { synchronized(serverMutex) { this.sftpChannel.disconnect(); this.session.disconnect(); this.jschInstance=null; this.session=null; this.sftpChannel=null; } } public String getID() { return this.serverID; } public String getScheme() { return VFS.SFTP_SCHEME; } public boolean isConnected() { if (this.sftpChannel!=null) return this.sftpChannel.isConnected(); return false; } private String getKnowHostsFile() { ServerInfo info=this.getServerInfo(); VAttribute attr=info.getAttribute(SftpFSFactory.ATTR_KNOWN_HOSTS_FILE); if (attr==null) return getDefaultKnownHostsFile(); else return attr.getValue(); } public String getSSHConfigDir() { ServerInfo info=this.getServerInfo(); VAttribute attr=info.getAttribute(SftpFSFactory.ATTR_SSH_CONFIG_DIR); if (attr==null) return getDefaultSSHDir(); else return attr.getValue(); } public boolean getAllowUserInterAction() { return this.vrsContext.getConfigManager().getAllowUserInteraction(); } public String getDefaultKnownHostsFile() { return getDefaultSSHDir()+"/known_hosts"; } public String getDefaultSSHDir() { return vrsContext.getLocalUserHome()+VRL.SEP_CHAR_STR+".ssh"; } private void setFinalUserSubject(VRSContext newContext) throws VlAuthenticationException { String newSubject=newContext.getGridProxy().getSubject(); if (this.userSubject!=null) { if (this.userSubject.compareTo(newSubject)!=0) { // OOPSY!! throw new nl.uva.vlet.exception.VlAuthenticationException("Illegal User. Current server is not authenticated for new user:"+newSubject); } } else // May Be Set Only Once !!! this.userSubject=newSubject; } public String getUserSubject() { return this.userSubject; } public String getLinkTarget(String path) { return null; } @Override public VDir newDir(VRL path) throws VlException { return new SftpDir(this,path); } @Override public VFile newFile(VRL path) throws VlException { return new SftpFile(this,path); } /** * Create localPort which connected to remoteHost:remotePort * @throws VlException */ public void createOutgoingTunnel(int localPort,String remoteHost,int remotePort) throws VlException { try { String[] list = this.session.getPortForwardingL(); String optStr=""+localPort+":"+remoteHost.toLowerCase()+":"+remotePort; for (String s:list) { if (StringUtil.equalsIgnoreCase(optStr,s)) { Global.warnPrintln(this,"Outgoing port forwarding already exists:"+s); return; } } //jsch doesn it all: this.session.setPortForwardingL(localPort,remoteHost,remotePort); Global.errorPrintln(this,"New SSH tunnel="+optStr); } catch (JSchException e) { throw this.convertException(e,"Couldn't create remote port forwarding:"+localPort+":"+remoteHost+":"+remotePort); } } /** Create localPort which connected to remoteHost:remotePort * @throws VlException */ public void createIncomingTunnel(int remotePort,String localHost,int localPort) throws VlException { try { //jsch doesn it all: this.session.setPortForwardingR(remotePort,localHost,localPort); } catch (JSchException e) { throw this.convertException(e,"Couldn't create incoming port forwarding:"+remotePort+":"+localHost+":"+localPort); } } /** Creates a new outgoing SSH tunnel and return the local tunnel port * @throws VlException */ public int createOutgoingTunnel(String bdiiHost, int bdiiPort) throws VlException { VlException lastEx=null; for (int i=0;i<32;i++) { int lport=getFreeLocalPort(); try { this.createOutgoingTunnel(lport,bdiiHost, bdiiPort); usedLocalPorts.add(new Integer(lport)); return lport; } catch (VlException e) { lastEx=e; Global.errorPrintln(this,"Failed to create new local tunnel port:"+lport+"\n"+e); } } if (lastEx!=null) throw lastEx; throw new VlException("Failed to create new local tunnel port"); } public static int getFreeLocalPort() { // use randomizer for now: (is much faster!) int offset=10000; int max=65535; int port=0; for (int i=0;i<100;i++) { port=offset+portRandomizer.nextInt(max-offset); // Integer(A) equals Integer(B) when (int)A==(int)B. if (usedLocalPorts.contains(new Integer(port))==false) return port; } return -1; } public SSHChannel createShellChannel(VRL optLocation) throws VlException { SSHChannelOptions options = new SSHChannelOptions(); SSHChannel sshChannel = new SSHChannel(vrsContext, getUsername(), getHostname(), getPort(), options); String path=optLocation.getPath(); try { // connect but re-use current session and options; sshChannel.connectTo(session); sshChannel.setCWD(path); return sshChannel; } catch (IOException e) { throw new VlException(e); } } }
nl.uva.vlet.vfs.jcraft.ssh: - cleanup: changed VAttribute.getValue() to typed VAttribute.getStringValue()
source/core/nl.uva.vlet.vfs.jcraft.ssh/src/nl/uva/vlet/vfs/jcraft/ssh/SftpFileSystem.java
nl.uva.vlet.vfs.jcraft.ssh: - cleanup: changed VAttribute.getValue() to typed VAttribute.getStringValue()
<ide><path>ource/core/nl.uva.vlet.vfs.jcraft.ssh/src/nl/uva/vlet/vfs/jcraft/ssh/SftpFileSystem.java <ide> if (attr==null) <ide> return getDefaultKnownHostsFile(); <ide> else <del> return attr.getValue(); <add> return attr.getStringValue(); <ide> } <ide> <ide> public String getSSHConfigDir() <ide> if (attr==null) <ide> return getDefaultSSHDir(); <ide> else <del> return attr.getValue(); <add> return attr.getStringValue(); <ide> } <ide> <ide> public boolean getAllowUserInterAction()
Java
apache-2.0
0d2f130c575e00ea15d79ef2b6bf1fd604731ce1
0
BeauBouchard/HASTE
/** * Author: Beau Bouchard * Date: 4/4/2013 * Last Updated: 7/1/2013 * Description: tweetscrapeEngine - Class which will utilize Twitter4J * Twitter4J from http://twitter4j.org/en/index.html Copyright 2007 Yusuke Yamamoto * * **/ import twitter4j.*; import twitter4j.conf.*; import java.text.SimpleDateFormat; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class tweetscrapeEngine { private tweetscrapeGUI tsGUI; private tweetscrapeDB tsDB; private String currentFilter = ".*?(tornado|twister).*"; private String consumerKey = ""; private String consumerSecret = ""; private String authAccessToken = ""; private String authAccessTokenSecret = ""; //filter object? //demo filter "^.*\b(tornado|twister|hail)\b.*$" //.*?(tornado|twister|hail).* private Pattern pattern; private Matcher matcher; private boolean filterisset = false; private boolean keysareset = false; public tweetscrapeEngine() { } public tweetscrapeEngine(tweetscrapeGUI inc_tsGUI) throws TwitterException { tsGUI = new tweetscrapeGUI("run"); tsGUI = inc_tsGUI; try { tsDB = new tweetscrapeDB(tsGUI); } catch(Exception tw) { } } /* Mutators/setters */ public void setFilter(String inc_filtervalue){ currentFilter = inc_filtervalue; } public void setconsumerKey(String inc_value) { consumerKey = inc_value; } public void setconsumerSecret(String inc_value) { consumerSecret = inc_value; } public void setauthAccessToken(String inc_value) { authAccessToken = inc_value; } public void setauthAccessTokenSecret(String inc_value) { authAccessTokenSecret = inc_value; } public void setKeysareset(boolean inc_value) { keysareset = inc_value; } public void setFilterisset(boolean inc_value) { filterisset = inc_value; } /* Accessors/getters */ public String getFilter() { return currentFilter; } public String getconsumerKey() { return consumerKey; } public String getconsumerSecret() { return consumerSecret; } public String getauthAccessToken() { return authAccessToken; } public String getauthAccessTokenSecret() { return authAccessTokenSecret; } public boolean getKeysareset() { return keysareset; } public boolean getFilterisset() { return filterisset; } public ConfigurationBuilder getConfig() { ConfigurationBuilder configBuild = new ConfigurationBuilder(); configBuild.setDebugEnabled(true) .setOAuthConsumerKey(getconsumerKey()) .setOAuthConsumerSecret(getconsumerSecret()) .setOAuthAccessToken(getauthAccessToken()) .setOAuthAccessTokenSecret(getauthAccessTokenSecret()); return configBuild; } public void configureFilter() { if(!filterisset) { tsGUI.outputText("Setting up Filter"); pattern = Pattern.compile(getFilter(), Pattern.CASE_INSENSITIVE); filterisset = true; tsGUI.outputText("New REGEX filter: " + getFilter() ); } else { //filter already set, now resetting filter filterisset = true; } } public boolean filterTweet(Status status) { boolean passfail = false; String p = getFilter(); String message = status.getText(); //passfail if(filterisset) { matcher = pattern.matcher(message); passfail = matcher.matches(); //System.out.println("match"); } else if(!filterisset) { //filter not set System.out.println("Filter is not set"); } else { //error } return passfail; } public void startDatabase() { tsDB.startDatabase(); } /** * returns a string which is formated as yyyy-MM-dd HH:mm:ss * @return timeStamp - a string of the date and time, formated as yyyy-MM-dd HH:mm:ss */ public String getTimeStamp() { String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()); return timeStamp; } public void saveStatus(Status status) { tweetscrapeTweet tstobj = new tweetscrapeTweet(); tstobj.settext(status.getText()); tstobj.setcreated_at(status.getCreatedAt()); tstobj.setcaptured_at(getTimeStamp()); if(status.getGeoLocation() != null) {tstobj.setgeo(status.getGeoLocation());} tsDB.insertTweet(tstobj); //save to new tweet object? } public void startStreamSearch() { if(!filterisset) { configureFilter(); } tsGUI.outputText("Engine online"); ConfigurationBuilder cb = new ConfigurationBuilder(); cb = getConfig(); //TwitterFactory tf = new TwitterFactory(cb.build()); //Twitter twitter = tf.getInstance(); TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance(); StatusListener listener = new StatusListener() { @Override public void onStatus(Status status) { // if(filterTweet(status)) { tsGUI.outputText(status.getText() + " - " + "@" + status.getUser().getScreenName() ); // System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText()); saveStatus(status); } else{ // System.out.print("nope"); } } @Override public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { //System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId()); } @Override public void onTrackLimitationNotice(int numberOfLimitedStatuses) { // System.out.println("Got track limitation notice:" + numberOfLimitedStatuses); } @Override public void onScrubGeo(long userId, long upToStatusId) { //System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId); } @Override public void onStallWarning(StallWarning warning) { System.out.println("Got stall warning:" + warning); } @Override public void onException(Exception ex) { //ex.printStackTrace(); } }; twitterStream.addListener(listener); // sample() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously. twitterStream.sample(); } }
src/tweetscrapeEngine.java
/** * Author: Beau Bouchard * Date: 4/4/2013 * Last Updated: 7/1/2013 * Description: tweetscrapeEngine - Class which will utilize Twitter4J * Twitter4J from http://twitter4j.org/en/index.html Copyright 2007 Yusuke Yamamoto * * **/ import twitter4j.*; import twitter4j.conf.*; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class tweetscrapeEngine { private tweetscrapeGUI tsGUI; private String currentFilter = ".*?(tornado|twister|hail).*"; private String consumerKey = ""; private String consumerSecret = ""; private String authAccessToken = ""; private String authAccessTokenSecret = ""; //filter object? //demo filter "^.*\b(tornado|twister|hail)\b.*$" //.*?(tornado|twister|hail).* private Pattern pattern; private Matcher matcher; private boolean filterisset = false; private boolean keysareset = false; public tweetscrapeEngine() { } public tweetscrapeEngine(tweetscrapeGUI inc_tsGUI) throws TwitterException { tsGUI = new tweetscrapeGUI("run"); tsGUI = inc_tsGUI; } /* Mutators/setters */ public void setFilter(String inc_filtervalue){ currentFilter = inc_filtervalue; } public void setconsumerKey(String inc_value) { consumerKey = inc_value; } public void setconsumerSecret(String inc_value) { consumerSecret = inc_value; } public void setauthAccessToken(String inc_value) { authAccessToken = inc_value; } public void setauthAccessTokenSecret(String inc_value) { authAccessTokenSecret = inc_value; } public void setKeysareset(boolean inc_value) { keysareset = inc_value; } public void setFilterisset(boolean inc_value) { filterisset = inc_value; } /* Accessors/getters */ public String getFilter() { return currentFilter; } public String getconsumerKey() { return consumerKey; } public String getconsumerSecret() { return consumerSecret; } public String getauthAccessToken() { return authAccessToken; } public String getauthAccessTokenSecret() { return authAccessTokenSecret; } public boolean getKeysareset() { return keysareset; } public boolean getFilterisset() { return filterisset; } public ConfigurationBuilder getConfig() { ConfigurationBuilder configBuild = new ConfigurationBuilder(); configBuild.setDebugEnabled(true) .setOAuthConsumerKey(getconsumerKey()) .setOAuthConsumerSecret(getconsumerSecret()) .setOAuthAccessToken(getauthAccessToken()) .setOAuthAccessTokenSecret(getauthAccessTokenSecret()); return configBuild; } public void configureFilter() { if(!filterisset) { tsGUI.outputText("Setting up Filter"); pattern = Pattern.compile(getFilter(), Pattern.CASE_INSENSITIVE); filterisset = true; tsGUI.outputText("New REGEX filter: " + getFilter() ); } else { //filter already set, now resetting filter filterisset = true; } } public boolean filterTweet(Status status) { boolean passfail = false; String p = getFilter(); String message = status.getText(); //passfail if(filterisset) { matcher = pattern.matcher(message); passfail = matcher.matches(); //System.out.println("match"); } else if(!filterisset) { //filter not set System.out.println("Filter is not set"); } else { //error } return passfail; } public void saveStatus(Status status) { tsGUI.outputText("@" + status.getUser().getScreenName() + " - " + status.getText()); System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText()); //save to new tweet object? } public void startStreamSearch() { if(!filterisset) { configureFilter(); } tsGUI.outputText("Engine online"); ConfigurationBuilder cb = new ConfigurationBuilder(); cb = getConfig(); //TwitterFactory tf = new TwitterFactory(cb.build()); //Twitter twitter = tf.getInstance(); TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance(); StatusListener listener = new StatusListener() { @Override public void onStatus(Status status) { // if(filterTweet(status)) { saveStatus(status); } } @Override public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { //System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId()); } @Override public void onTrackLimitationNotice(int numberOfLimitedStatuses) { // System.out.println("Got track limitation notice:" + numberOfLimitedStatuses); } @Override public void onScrubGeo(long userId, long upToStatusId) { //System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId); } @Override public void onStallWarning(StallWarning warning) { //System.out.println("Got stall warning:" + warning); } @Override public void onException(Exception ex) { //ex.printStackTrace(); } }; twitterStream.addListener(listener); // sample() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously. twitterStream.sample(); } }
added ability to create Tweet objects, and then save them to database
src/tweetscrapeEngine.java
added ability to create Tweet objects, and then save them to database
<ide><path>rc/tweetscrapeEngine.java <ide> <ide> import twitter4j.*; <ide> import twitter4j.conf.*; <add> <add>import java.text.SimpleDateFormat; <ide> import java.util.*; <ide> import java.util.regex.Matcher; <ide> import java.util.regex.Pattern; <ide> public class tweetscrapeEngine <ide> { <ide> private tweetscrapeGUI tsGUI; <del> <del> <del> private String currentFilter = ".*?(tornado|twister|hail).*"; <add> private tweetscrapeDB tsDB; <add> <add> private String currentFilter = ".*?(tornado|twister).*"; <ide> private String consumerKey = ""; <ide> private String consumerSecret = ""; <ide> private String authAccessToken = ""; <ide> tsGUI = new tweetscrapeGUI("run"); <ide> tsGUI = inc_tsGUI; <ide> <add> try <add> { <add> tsDB = new tweetscrapeDB(tsGUI); <add> } <add> catch(Exception tw) <add> { <add> <add> } <add> <ide> } <ide> <ide> /* Mutators/setters */ <ide> return passfail; <ide> } <ide> <add> public void startDatabase() <add> { <add> <add> tsDB.startDatabase(); <add> } <add> <add> /** <add> * returns a string which is formated as yyyy-MM-dd HH:mm:ss <add> * @return timeStamp - a string of the date and time, formated as yyyy-MM-dd HH:mm:ss <add> */ <add> public String getTimeStamp() <add> { <add> String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime()); <add> return timeStamp; <add> } <add> <ide> public void saveStatus(Status status) <ide> { <del> tsGUI.outputText("@" + status.getUser().getScreenName() + " - " + status.getText()); <del> System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText()); <add> tweetscrapeTweet tstobj = new tweetscrapeTweet(); <add> tstobj.settext(status.getText()); <add> tstobj.setcreated_at(status.getCreatedAt()); <add> tstobj.setcaptured_at(getTimeStamp()); <add> if(status.getGeoLocation() != null) {tstobj.setgeo(status.getGeoLocation());} <add> <add> tsDB.insertTweet(tstobj); <add> <ide> <ide> //save to new tweet object? <ide> } <ide> // <ide> if(filterTweet(status)) <ide> { <add> <add> tsGUI.outputText(status.getText() + " - " + "@" + status.getUser().getScreenName() ); <add> // System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText()); <ide> saveStatus(status); <ide> } <add> else{ <add> // System.out.print("nope"); <add> } <ide> } <ide> <ide> @Override <ide> <ide> @Override <ide> public void onStallWarning(StallWarning warning) { <del> //System.out.println("Got stall warning:" + warning); <add> System.out.println("Got stall warning:" + warning); <ide> } <ide> <ide> @Override
Java
apache-2.0
f5bc73638e5b1b2c7dcf48582d0f57b75a44bc37
0
siom79/japicmp,siom79/japicmp,siom79/japicmp
package japicmp.compat; import japicmp.cmp.JarArchiveComparator; import japicmp.cmp.JarArchiveComparatorOptions; import japicmp.exception.JApiCmpException; import japicmp.model.*; import japicmp.util.ClassHelper; import japicmp.util.Optional; import japicmp.util.SignatureParser; import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; import java.util.*; import static japicmp.util.ModifierHelper.*; public class CompatibilityChanges { private final JarArchiveComparator jarArchiveComparator; public CompatibilityChanges(JarArchiveComparator jarArchiveComparator) { this.jarArchiveComparator = jarArchiveComparator; } public void evaluate(List<JApiClass> classes) { Map<String, JApiClass> classMap = buildClassMap(classes); for (JApiClass clazz : classes) { evaluateBinaryCompatibility(clazz, classMap); } } private Map<String, JApiClass> buildClassMap(List<JApiClass> classes) { Map<String, JApiClass> classMap = new HashMap<>(); for (JApiClass clazz : classes) { classMap.put(clazz.getFullyQualifiedName(), clazz); } return classMap; } private void evaluateBinaryCompatibility(JApiClass jApiClass, Map<String, JApiClass> classMap) { if (jApiClass.getChangeStatus() == JApiChangeStatus.REMOVED) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.CLASS_REMOVED); } else if (jApiClass.getChangeStatus() == JApiChangeStatus.MODIFIED) { // section 13.4.1 of "Java Language Specification" SE7 if (jApiClass.getAbstractModifier().hasChangedFromTo(AbstractModifier.NON_ABSTRACT, AbstractModifier.ABSTRACT)) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.CLASS_NOW_ABSTRACT); } // section 13.4.2 of "Java Language Specification" SE7 if (jApiClass.getFinalModifier().hasChangedFromTo(FinalModifier.NON_FINAL, FinalModifier.FINAL)) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.CLASS_NOW_FINAL); } // section 13.4.3 of "Java Language Specification" SE7 if (jApiClass.getAccessModifier().hasChangedFrom(AccessModifier.PUBLIC)) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.CLASS_NO_LONGER_PUBLIC); } } // section 13.4.4 of "Java Language Specification" SE7 checkIfSuperclassesOrInterfacesChangedIncompatible(jApiClass, classMap); checkIfMethodsHaveChangedIncompatible(jApiClass, classMap); checkIfConstructorsHaveChangedIncompatible(jApiClass, classMap); checkIfFieldsHaveChangedIncompatible(jApiClass, classMap); if (jApiClass.getClassType().getChangeStatus() == JApiChangeStatus.MODIFIED) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.CLASS_TYPE_CHANGED); } checkIfAnnotationDeprecatedAdded(jApiClass); if (hasModifierLevelDecreased(jApiClass)) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.CLASS_LESS_ACCESSIBLE); } checkIfGenericTemplatesHaveChanged(jApiClass); } private void checkIfGenericTemplatesHaveChanged(JApiHasGenericTemplates jApiHasGenericTemplates) { for (JApiGenericTemplate jApiGenericTemplate : jApiHasGenericTemplates.getGenericTemplates()) { if (jApiGenericTemplate.getChangeStatus() != JApiChangeStatus.UNCHANGED) { ((JApiCompatibility)jApiHasGenericTemplates).getCompatibilityChanges().add(JApiCompatibilityChange.CLASS_GENERIC_TEMPLATE_CHANGED); break; } } for (JApiGenericTemplate jApiGenericTemplate : jApiHasGenericTemplates.getGenericTemplates()) { JApiChangeStatus changeStatus = jApiGenericTemplate.getChangeStatus(); if (changeStatus == JApiChangeStatus.MODIFIED || changeStatus == JApiChangeStatus.UNCHANGED) { if (!SignatureParser.equalGenericTypes(jApiGenericTemplate.getOldGenericTypes(), jApiGenericTemplate.getNewGenericTypes())) { jApiGenericTemplate.getCompatibilityChanges().add(JApiCompatibilityChange.CLASS_GENERIC_TEMPLATE_GENERICS_CHANGED); ((JApiCompatibility)jApiHasGenericTemplates).getCompatibilityChanges().add(JApiCompatibilityChange.CLASS_GENERIC_TEMPLATE_GENERICS_CHANGED); break; } } } } private void checkIfFieldsHaveChangedIncompatible(JApiClass jApiClass, Map<String, JApiClass> classMap) { for (final JApiField field : jApiClass.getFields()) { // section 13.4.6 of "Java Language Specification" SE7 if (isNotPrivate(field) && field.getChangeStatus() == JApiChangeStatus.REMOVED) { ArrayList<Integer> returnValues = new ArrayList<>(); forAllSuperclasses(jApiClass, classMap, returnValues, (superclass, classMap1, changeStatusOfSuperclass) -> { int movedToSuperclass = 0; for (JApiField superclassField : superclass.getFields()) { if (superclassField.getName().equals(field.getName()) && fieldTypeMatches(superclassField, field) && isNotPrivate(superclassField)) { movedToSuperclass = 1; } } return movedToSuperclass; }); boolean movedToSuperclass = false; for (Integer returnValue : returnValues) { if (returnValue == 1) { movedToSuperclass = true; } } if (!movedToSuperclass) { addCompatibilityChange(field, JApiCompatibilityChange.FIELD_REMOVED); } } // section 13.4.7 of "Java Language Specification" SE7 if (hasModifierLevelDecreased(field)) { addCompatibilityChange(field, JApiCompatibilityChange.FIELD_LESS_ACCESSIBLE); } // section 13.4.8 of "Java Language Specification" SE7 if (isNotPrivate(field) && field.getChangeStatus() == JApiChangeStatus.NEW) { ArrayList<Integer> returnValues = new ArrayList<>(); forAllSuperclasses(jApiClass, classMap, returnValues, new OnSuperclassCallback<Integer>() { @Override public Integer callback(JApiClass superclass, Map<String, JApiClass> classMap, JApiChangeStatus changeStatusOfSuperclass) { int changedIncompatible = 0; for (JApiField superclassField : superclass.getFields()) { if (superclassField.getName().equals(field.getName()) && fieldTypeMatches(superclassField, field)) { boolean superclassFieldIsStatic = false; boolean subclassFieldIsStatic = false; boolean accessModifierSubclassLess = false; if (field.getStaticModifier().getNewModifier().isPresent() && field.getStaticModifier().getNewModifier().get() == StaticModifier.STATIC) { subclassFieldIsStatic = true; } if (superclassField.getStaticModifier().getNewModifier().isPresent() && superclassField.getStaticModifier().getNewModifier().get() == StaticModifier.STATIC && superclassField.getChangeStatus() != JApiChangeStatus.NEW) { superclassFieldIsStatic = true; } if (field.getAccessModifier().getNewModifier().isPresent() && superclassField.getAccessModifier().getNewModifier().isPresent()) { if (field.getAccessModifier().getNewModifier().get().getLevel() < superclassField.getAccessModifier().getNewModifier().get().getLevel() && superclassField.getChangeStatus() != JApiChangeStatus.NEW) { accessModifierSubclassLess = true; } } if (superclassFieldIsStatic) { if (subclassFieldIsStatic) { changedIncompatible = 1; } } if (accessModifierSubclassLess) { changedIncompatible = 2; } } } return changedIncompatible; } }); for (int returnValue : returnValues) { if (returnValue == 1) { addCompatibilityChange(field, JApiCompatibilityChange.FIELD_STATIC_AND_OVERRIDES_STATIC); } else if (returnValue == 2) { addCompatibilityChange(field, JApiCompatibilityChange.FIELD_LESS_ACCESSIBLE_THAN_IN_SUPERCLASS); } } } // section 13.4.9 of "Java Language Specification" SE7 if (isNotPrivate(field) && field.getFinalModifier().hasChangedFromTo(FinalModifier.NON_FINAL, FinalModifier.FINAL)) { addCompatibilityChange(field, JApiCompatibilityChange.FIELD_NOW_FINAL); } // section 13.4.10 of "Java Language Specification" SE7 if (isNotPrivate(field)) { if (field.getStaticModifier().hasChangedFromTo(StaticModifier.NON_STATIC, StaticModifier.STATIC)) { addCompatibilityChange(field, JApiCompatibilityChange.FIELD_NOW_STATIC); } if (field.getStaticModifier().hasChangedFromTo(StaticModifier.STATIC, StaticModifier.NON_STATIC)) { addCompatibilityChange(field, JApiCompatibilityChange.FIELD_NO_LONGER_STATIC); } } if (isNotPrivate(field) && field.getType().hasChanged()) { addCompatibilityChange(field, JApiCompatibilityChange.FIELD_TYPE_CHANGED); } checkIfAnnotationDeprecatedAdded(field); checkIfFieldGenericsChanged(field); } } private interface OnSuperclassCallback<T> { T callback(JApiClass superclass, Map<String, JApiClass> classMap, JApiChangeStatus changeStatusOfSuperclass); } private interface OnImplementedInterfaceCallback<T> { T callback(JApiClass implementedInterface, Map<String, JApiClass> classMap); } private <T> void forAllSuperclasses(JApiClass jApiClass, Map<String, JApiClass> classMap, List<T> returnValues, OnSuperclassCallback<T> onSuperclassCallback) { JApiSuperclass superclass = jApiClass.getSuperclass(); if (superclass.getNewSuperclassName().isPresent()) { String newSuperclassName = superclass.getNewSuperclassName().get(); JApiClass foundClass = classMap.get(newSuperclassName); if (foundClass == null) { Optional<JApiClass> superclassJApiClassOptional = superclass.getJApiClass(); if (superclassJApiClassOptional.isPresent()) { foundClass = superclassJApiClassOptional.get(); } else { foundClass = loadClass(newSuperclassName, EnumSet.of(Classpath.NEW_CLASSPATH)); evaluate(Collections.singletonList(foundClass)); } classMap.put(foundClass.getFullyQualifiedName(), foundClass); } T returnValue = onSuperclassCallback.callback(foundClass, classMap, superclass.getChangeStatus()); returnValues.add(returnValue); forAllSuperclasses(foundClass, classMap, returnValues, onSuperclassCallback); } } private enum Classpath { OLD_CLASSPATH, NEW_CLASSPATH } private JApiClass loadClass(String newSuperclassName, EnumSet<Classpath> classpaths) { JApiClass foundClass; Optional<CtClass> oldClassOptional = Optional.absent(); Optional<CtClass> newClassOptional = Optional.absent(); JarArchiveComparatorOptions.ClassPathMode classPathMode = this.jarArchiveComparator.getJarArchiveComparatorOptions().getClassPathMode(); if (classPathMode == JarArchiveComparatorOptions.ClassPathMode.ONE_COMMON_CLASSPATH) { ClassPool classPool = this.jarArchiveComparator.getCommonClassPool(); try { oldClassOptional = Optional.of(classPool.get(newSuperclassName)); } catch (NotFoundException ignored) {} try { newClassOptional = Optional.of(classPool.get(newSuperclassName)); } catch (NotFoundException ignored) {} } else { if (classpaths.contains(Classpath.OLD_CLASSPATH)) { ClassPool oldClassPool = this.jarArchiveComparator.getOldClassPool(); try { oldClassOptional = Optional.of(oldClassPool.get(newSuperclassName)); } catch (NotFoundException ignored) {} } if (classpaths.contains(Classpath.NEW_CLASSPATH)) { ClassPool newClassPool = this.jarArchiveComparator.getNewClassPool(); try { newClassOptional = Optional.of(newClassPool.get(newSuperclassName)); } catch (NotFoundException ignored) {} } } if (!oldClassOptional.isPresent() && !newClassOptional.isPresent()) { if (!this.jarArchiveComparator.getJarArchiveComparatorOptions().getIgnoreMissingClasses().ignoreClass(newSuperclassName)) { throw JApiCmpException.forClassLoading(newSuperclassName, this.jarArchiveComparator); } } JApiClassType classType; JApiChangeStatus changeStatus = JApiChangeStatus.UNCHANGED; if (oldClassOptional.isPresent() && newClassOptional.isPresent()) { classType = new JApiClassType(Optional.of(ClassHelper.getType(oldClassOptional.get())), Optional.of(ClassHelper.getType(newClassOptional.get())), JApiChangeStatus.UNCHANGED); } else if (oldClassOptional.isPresent() && !newClassOptional.isPresent()) { classType = new JApiClassType(Optional.of(ClassHelper.getType(oldClassOptional.get())), Optional.<JApiClassType.ClassType>absent(), JApiChangeStatus.REMOVED); } else if (!oldClassOptional.isPresent() && newClassOptional.isPresent()) { classType = new JApiClassType(Optional.<JApiClassType.ClassType>absent(), Optional.of(ClassHelper.getType(newClassOptional.get())), JApiChangeStatus.NEW); } else { classType = new JApiClassType(Optional.<JApiClassType.ClassType>absent(), Optional.<JApiClassType.ClassType>absent(), JApiChangeStatus.UNCHANGED); } foundClass = new JApiClass(this.jarArchiveComparator, newSuperclassName, oldClassOptional, newClassOptional, changeStatus, classType); return foundClass; } private boolean fieldTypeMatches(JApiField field1, JApiField field2) { boolean matches = true; JApiType type1 = field1.getType(); JApiType type2 = field2.getType(); if (type1.getNewTypeOptional().isPresent() && type2.getNewTypeOptional().isPresent()) { if (!type1.getNewTypeOptional().get().equals(type2.getNewTypeOptional().get())) { matches = false; } } return matches; } private void checkIfConstructorsHaveChangedIncompatible(JApiClass jApiClass, Map<String, JApiClass> classMap) { for (JApiConstructor constructor : jApiClass.getConstructors()) { // section 13.4.6 of "Java Language Specification" SE7 if (isNotPrivate(constructor) && constructor.getChangeStatus() == JApiChangeStatus.REMOVED) { addCompatibilityChange(constructor, JApiCompatibilityChange.CONSTRUCTOR_REMOVED); } // section 13.4.7 of "Java Language Specification" SE7 if (hasModifierLevelDecreased(constructor)) { if (isNotFinal(jApiClass) || constructor.getAccessModifier().hasChangedFrom(AccessModifier.PUBLIC)) { addCompatibilityChange(constructor, JApiCompatibilityChange.CONSTRUCTOR_LESS_ACCESSIBLE); } } checkIfExceptionIsNowChecked(constructor); checkIfAnnotationDeprecatedAdded(constructor); checkIfVarargsChanged(constructor); checkIfParametersGenericsChanged(constructor); checkIfGenericTemplatesHaveChanged(constructor); } } private static boolean isNotFinal(JApiClass jApiClass) { return !(jApiClass.getFinalModifier().getNewModifier().isPresent() && jApiClass.getFinalModifier().getNewModifier().get() == FinalModifier.FINAL); } private void checkIfMethodsHaveChangedIncompatible(JApiClass jApiClass, Map<String, JApiClass> classMap) { for (final JApiMethod method : jApiClass.getMethods()) { // section 13.4.6 of "Java Language Specification" SE7 if (isNotPrivate(method) && method.getChangeStatus() == JApiChangeStatus.REMOVED) { final List<Integer> returnValues = new ArrayList<>(); forAllSuperclasses(jApiClass, classMap, returnValues, new OnSuperclassCallback<Integer>() { @Override public Integer callback(JApiClass superclass, Map<String, JApiClass> classMap, JApiChangeStatus changeStatusOfSuperclass) { for (JApiMethod superMethod : superclass.getMethods()) { if (superMethod.getName().equals(method.getName()) && superMethod.hasSameSignature(method)) { return 1; } } return 0; } }); checkIfMethodHasBeenPulledUp(jApiClass, classMap, method, returnValues); boolean superclassHasSameMethod = false; for (Integer returnValue : returnValues) { if (returnValue == 1) { superclassHasSameMethod = true; } } if (!superclassHasSameMethod) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_REMOVED); } } if (!isInterface(jApiClass) && method.getChangeStatus() == JApiChangeStatus.NEW && method.getAccessModifier().getNewModifier().get().getLevel() == AccessModifier.PUBLIC.getLevel()) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_ADDED_TO_PUBLIC_CLASS); } // section 13.4.7 of "Java Language Specification" SE7 if (hasModifierLevelDecreased(method)) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_LESS_ACCESSIBLE); } // section 13.4.12 of "Java Language Specification" SE7 if (isNotPrivate(method) && method.getChangeStatus() == JApiChangeStatus.NEW) { List<Integer> returnValues = new ArrayList<>(); forAllSuperclasses(jApiClass, classMap, returnValues, new OnSuperclassCallback<Integer>() { @Override public Integer callback(JApiClass superclass, Map<String, JApiClass> classMap, JApiChangeStatus changeStatusOfSuperclass) { for (JApiMethod superMethod : superclass.getMethods()) { if (superMethod.getName().equals(method.getName()) && superMethod.hasSameSignature(method)) { if (superMethod.getAccessModifier().getNewModifier().isPresent() && method.getAccessModifier().getNewModifier().isPresent()) { if (superMethod.getAccessModifier().getNewModifier().get().getLevel() > method.getAccessModifier().getNewModifier().get().getLevel()) { return 1; } } if (superMethod.getStaticModifier().getNewModifier().isPresent() && method.getStaticModifier().getNewModifier().isPresent()) { if (superMethod.getStaticModifier().getNewModifier().get() == StaticModifier.NON_STATIC && method.getStaticModifier().getNewModifier().get() == StaticModifier.STATIC) { return 2; } } } } return 0; } }); for (Integer returnValue : returnValues) { if (returnValue == 1) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_LESS_ACCESSIBLE_THAN_IN_SUPERCLASS); } else if (returnValue == 2) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_IS_STATIC_AND_OVERRIDES_NOT_STATIC); } } } checkIfReturnTypeChanged(method); // section 13.4.16 of "Java Language Specification" SE7 if (isNotPrivate(method) && method.getAbstractModifier().hasChangedFromTo(AbstractModifier.NON_ABSTRACT, AbstractModifier.ABSTRACT)) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_NOW_ABSTRACT); } // section 13.4.17 of "Java Language Specification" SE7 if (isNotPrivate(method) && method.getFinalModifier().hasChangedFromTo(FinalModifier.NON_FINAL, FinalModifier.FINAL)) { if ((jApiClass.getFinalModifier().getOldModifier().isPresent() && jApiClass.getFinalModifier().getOldModifier().get() != FinalModifier.FINAL) && !(method.getStaticModifier().getOldModifier().isPresent() && method.getStaticModifier().getOldModifier().get() == StaticModifier.STATIC)) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_NOW_FINAL); } } // section 13.4.18 of "Java Language Specification" SE7 if (isNotPrivate(method)) { if (method.getStaticModifier().hasChangedFromTo(StaticModifier.NON_STATIC, StaticModifier.STATIC)) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_NOW_STATIC); } if (method.getStaticModifier().hasChangedFromTo(StaticModifier.STATIC, StaticModifier.NON_STATIC)) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_NO_LONGER_STATIC); } } checkAbstractMethod(jApiClass, classMap, method); checkIfExceptionIsNowChecked(method); checkIfAnnotationDeprecatedAdded(method); checkIfVarargsChanged(method); checkIfParametersGenericsChanged(method); checkIfGenericTemplatesHaveChanged(method); } } private void checkIfReturnTypeChanged(JApiMethod method) { // section 13.4.15 of "Java Language Specification" SE7 (Method Result Type) if (method.getReturnType().getChangeStatus() == JApiChangeStatus.MODIFIED) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_RETURN_TYPE_CHANGED); } if (method.getChangeStatus() == JApiChangeStatus.MODIFIED || method.getChangeStatus() == JApiChangeStatus.UNCHANGED) { if (!SignatureParser.equalGenericTypes(method.getReturnType().getOldGenericTypes(), method.getReturnType().getNewGenericTypes())) { addCompatibilityChange(method.getReturnType(), JApiCompatibilityChange.METHOD_RETURN_TYPE_GENERICS_CHANGED); } } } private void checkIfParametersGenericsChanged(JApiBehavior jApiBehavior) { if (jApiBehavior.getChangeStatus() == JApiChangeStatus.MODIFIED || jApiBehavior.getChangeStatus() == JApiChangeStatus.UNCHANGED) { for (JApiParameter jApiParameter : jApiBehavior.getParameters()) { if (!SignatureParser.equalGenericTypes(jApiParameter.getOldGenericTypes(), jApiParameter.getNewGenericTypes())) { jApiParameter.getCompatibilityChanges().add(JApiCompatibilityChange.METHOD_PARAMETER_GENERICS_CHANGED); } } } } private void checkIfFieldGenericsChanged(JApiField jApiField) { if (jApiField.getChangeStatus() == JApiChangeStatus.MODIFIED || jApiField.getChangeStatus() == JApiChangeStatus.UNCHANGED) { if (!SignatureParser.equalGenericTypes(jApiField.getOldGenericTypes(), jApiField.getNewGenericTypes())) { jApiField.getCompatibilityChanges().add(JApiCompatibilityChange.FIELD_GENERICS_CHANGED); } } } private void checkIfAnnotationDeprecatedAdded(JApiHasAnnotations jApiHasAnnotations) { for (JApiAnnotation annotation : jApiHasAnnotations.getAnnotations()) { if (annotation.getChangeStatus() == JApiChangeStatus.NEW || annotation.getChangeStatus() == JApiChangeStatus.MODIFIED) { if (annotation.getFullyQualifiedName().equals(Deprecated.class.getName())) { addCompatibilityChange((JApiCompatibility) jApiHasAnnotations, JApiCompatibilityChange.ANNOTATION_DEPRECATED_ADDED); } } } } private void checkIfVarargsChanged(JApiBehavior behavior) { if (behavior.getVarargsModifier().hasChangedFromTo(VarargsModifier.VARARGS, VarargsModifier.NON_VARARGS)) { addCompatibilityChange(behavior, JApiCompatibilityChange.METHOD_NO_LONGER_VARARGS); } if (behavior.getVarargsModifier().hasChangedFromTo(VarargsModifier.NON_VARARGS, VarargsModifier.VARARGS)) { addCompatibilityChange(behavior, JApiCompatibilityChange.METHOD_NOW_VARARGS); } } private void checkAbstractMethod(JApiClass jApiClass, Map<String, JApiClass> classMap, JApiMethod method) { if (isInterface(jApiClass)) { if (jApiClass.getChangeStatus() != JApiChangeStatus.NEW) { if (method.getChangeStatus() == JApiChangeStatus.NEW && !isSynthetic(method)) { List<JApiMethod> methodsWithSameSignature = getMethodsInImplementedInterfacesWithSameSignature(jApiClass, classMap, method); if (methodsWithSameSignature.size() == 0) { // new default method in interface if (method.getAbstractModifier().hasChangedTo(AbstractModifier.NON_ABSTRACT)) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_NEW_DEFAULT); } else { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_ADDED_TO_INTERFACE); } } else { boolean allNew = true; for (JApiMethod jApiMethod : methodsWithSameSignature) { if (jApiMethod.getChangeStatus() != JApiChangeStatus.NEW) { allNew = false; } } if (allNew) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_ADDED_TO_INTERFACE); } } } else if (method.getChangeStatus() == JApiChangeStatus.MODIFIED || method.getChangeStatus() == JApiChangeStatus.UNCHANGED) { JApiModifier<AbstractModifier> abstractModifier = method.getAbstractModifier(); // method changed from abstract to default if (abstractModifier.getOldModifier().isPresent() && abstractModifier.getOldModifier().get() == AbstractModifier.ABSTRACT && abstractModifier.getNewModifier().isPresent() && abstractModifier.getNewModifier().get() == AbstractModifier.NON_ABSTRACT) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_ABSTRACT_NOW_DEFAULT); } } } } else { if (isAbstract(method)) { if (jApiClass.getChangeStatus() != JApiChangeStatus.NEW) { if (method.getChangeStatus() == JApiChangeStatus.NEW && !isSynthetic(method)) { List<JApiMethod> overriddenMethods = getOverriddenMethods(jApiClass, classMap, method); boolean overridesAbstract = false; for (JApiMethod jApiMethod : overriddenMethods) { if (isAbstract(jApiMethod) && jApiMethod.getChangeStatus() != JApiChangeStatus.NEW) { overridesAbstract = true; } } List<JApiMethod> implementedMethods = getMethodsInImplementedInterfacesWithSameSignature(jApiClass, classMap, method); if (implementedMethods.size() > 0) { overridesAbstract = true; } if (!overridesAbstract) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_ABSTRACT_ADDED_TO_CLASS); } } } } } } private List<JApiMethod> getOverriddenMethods(final JApiClass jApiClass, final Map<String, JApiClass> classMap, final JApiMethod method) { ArrayList<JApiMethod> jApiMethods = new ArrayList<>(); forAllSuperclasses(jApiClass, classMap, jApiMethods, new OnSuperclassCallback<JApiMethod>() { @Override public JApiMethod callback(JApiClass superclass, Map<String, JApiClass> classMap, JApiChangeStatus changeStatusOfSuperclass) { for (JApiMethod jApiMethod : superclass.getMethods()) { if (isAbstract(jApiMethod)) { if (jApiMethod.getName().equals(method.getName()) && jApiMethod.hasSameSignature(method)) { return jApiMethod; } } } return null; } }); return removeNullValues(jApiMethods); } private List<JApiMethod> removeNullValues(ArrayList<JApiMethod> jApiMethods) { ArrayList<JApiMethod> returnValues = new ArrayList<>(); for (JApiMethod jApiMethod : jApiMethods) { if (jApiMethod != null) { returnValues.add(jApiMethod); } } return returnValues; } private List<JApiMethod> getMethodsInImplementedInterfacesWithSameSignature(final JApiClass jApiClass, final Map<String, JApiClass> classMap, final JApiMethod method) { ArrayList<JApiMethod> jApiMethods = new ArrayList<>(); forAllImplementedInterfaces(jApiClass, classMap, jApiMethods, new ArrayList<>(), new OnImplementedInterfaceCallback<JApiMethod>() { @Override public JApiMethod callback(JApiClass implementedInterface, Map<String, JApiClass> classMap) { for (JApiMethod jApiMethod : implementedInterface.getMethods()) { if (jApiMethod.getName().equals(method.getName()) && jApiMethod.hasSameSignature(method)) { return jApiMethod; } } return null; } }); return removeNullValues(jApiMethods); } private boolean isAbstract(JApiHasAbstractModifier jApiHasAbstractModifier) { boolean isAbstract = false; if (jApiHasAbstractModifier.getAbstractModifier().hasChangedTo(AbstractModifier.ABSTRACT)) { isAbstract = true; } return isAbstract; } private void checkIfExceptionIsNowChecked(JApiBehavior behavior) { for (JApiException exception : behavior.getExceptions()) { if (exception.getChangeStatus() == JApiChangeStatus.NEW && exception.isCheckedException() && behavior.getChangeStatus() != JApiChangeStatus.NEW) { addCompatibilityChange(behavior, JApiCompatibilityChange.METHOD_NOW_THROWS_CHECKED_EXCEPTION); } if (exception.getChangeStatus() == JApiChangeStatus.REMOVED && exception.isCheckedException() && behavior.getChangeStatus() != JApiChangeStatus.REMOVED) { addCompatibilityChange(behavior, JApiCompatibilityChange.METHOD_NO_LONGER_THROWS_CHECKED_EXCEPTION); } } } private boolean isClass(final JApiClass jApiClass) { return jApiClass.getClassType().getNewTypeOptional().isPresent() && jApiClass.getClassType().getNewTypeOptional().get() == JApiClassType.ClassType.CLASS; } private boolean isInterface(final JApiClass jApiClass) { return jApiClass.getClassType().getNewTypeOptional().isPresent() && jApiClass.getClassType().getNewTypeOptional().get() == JApiClassType.ClassType.INTERFACE; } private boolean isAnnotation(final JApiClass jApiClass) { return jApiClass.getClassType().getNewTypeOptional().isPresent() && jApiClass.getClassType().getNewTypeOptional().get() == JApiClassType.ClassType.ANNOTATION; } private boolean isEnum(final JApiClass jApiClass) { return jApiClass.getClassType().getNewTypeOptional().isPresent() && jApiClass.getClassType().getNewTypeOptional().get() == JApiClassType.ClassType.ENUM; } private void checkIfMethodHasBeenPulledUp(JApiClass jApiClass, Map<String, JApiClass> classMap, final JApiMethod method, List<Integer> returnValues) { forAllImplementedInterfaces(jApiClass, classMap, returnValues, new ArrayList<>(), (implementedInterface, classMap1) -> { for (JApiMethod superMethod : implementedInterface.getMethods()) { if (superMethod.getName().equals(method.getName()) && superMethod.hasSameSignature(method)) { return 1; } } return 0; }); } private <T> void forAllImplementedInterfaces(JApiClass jApiClass, Map<String, JApiClass> classMap, List<T> returnValues, List<JApiImplementedInterface> visited, OnImplementedInterfaceCallback<T> onImplementedInterfaceCallback) { List<JApiImplementedInterface> interfaces = jApiClass.getInterfaces(); for (JApiImplementedInterface implementedInterface : interfaces) { String fullyQualifiedName = implementedInterface.getFullyQualifiedName(); JApiClass foundClass = classMap.get(fullyQualifiedName); if (foundClass != null && visited.stream().noneMatch(v -> v.getFullyQualifiedName().equals(implementedInterface.getFullyQualifiedName()))) { T returnValue = onImplementedInterfaceCallback.callback(foundClass, classMap); returnValues.add(returnValue); visited.add(implementedInterface); forAllImplementedInterfaces(foundClass, classMap, returnValues, visited, onImplementedInterfaceCallback); } } } /** * Is a method implemented in a super class * @param jApiMethod the method * @return <code>true</code> if it is implemented in a super class */ private boolean isImplemented(JApiMethod jApiMethod, JApiClass aClass) { while(aClass != null) { for (JApiMethod method : aClass.getMethods()) { if (jApiMethod.getName().equals(method.getName()) && jApiMethod.hasSameParameter(method) && !isAbstract(method) && method.getChangeStatus() != JApiChangeStatus.REMOVED && isNotPrivate(method)) { return true; } } if(aClass.getSuperclass() != null && aClass.getSuperclass().getJApiClass().isPresent()) { aClass = aClass.getSuperclass().getJApiClass().get(); } else { aClass = null; } } return false; } private void checkIfSuperclassesOrInterfacesChangedIncompatible(final JApiClass jApiClass, Map<String, JApiClass> classMap) { final JApiSuperclass superclass = jApiClass.getSuperclass(); // section 13.4.4 of "Java Language Specification" SE7 if (superclass.getChangeStatus() == JApiChangeStatus.UNCHANGED || superclass.getChangeStatus() == JApiChangeStatus.MODIFIED || superclass.getChangeStatus() == JApiChangeStatus.REMOVED) { final List<JApiMethod> implementedMethods = new ArrayList<>(); final List<JApiMethod> removedAndNotOverriddenMethods = new ArrayList<>(); final List<JApiField> fields = new ArrayList<>(); final List<JApiField> removedAndNotOverriddenFields = new ArrayList<>(); for (JApiMethod jApiMethod : jApiClass.getMethods()) { if (!isAbstract(jApiMethod) && jApiMethod.getChangeStatus() != JApiChangeStatus.REMOVED && isNotPrivate(jApiMethod)) { implementedMethods.add(jApiMethod); } } for (JApiField jApiField : jApiClass.getFields()) { if (jApiField.getChangeStatus() != JApiChangeStatus.REMOVED && isNotPrivate(jApiField)) { fields.add(jApiField); } } forAllSuperclasses(jApiClass, classMap, new ArrayList<Integer>(), new OnSuperclassCallback<Integer>() { @Override public Integer callback(JApiClass superclass, Map<String, JApiClass> classMap, JApiChangeStatus changeStatusOfSuperclass) { for (JApiMethod jApiMethod : superclass.getMethods()) { if (!isAbstract(jApiMethod) && jApiMethod.getChangeStatus() != JApiChangeStatus.REMOVED && isNotPrivate(jApiMethod)) { implementedMethods.add(jApiMethod); } Iterator<JApiMethod> iterator = removedAndNotOverriddenMethods.iterator(); while (iterator.hasNext()) { JApiMethod removedAndNotOverriddenMethod = iterator.next(); if (jApiMethod.getName().equals(removedAndNotOverriddenMethod.getName()) && jApiMethod.hasSameSignature(removedAndNotOverriddenMethod)) { iterator.remove(); } } } for (JApiField jApiField : superclass.getFields()) { if (jApiField.getChangeStatus() != JApiChangeStatus.REMOVED && isNotPrivate(jApiField)) { fields.add(jApiField); } Iterator<JApiField> iterator = removedAndNotOverriddenFields.iterator(); while (iterator.hasNext()) { JApiField removedAndNotOverriddenField = iterator.next(); if (jApiField.getName().equals(removedAndNotOverriddenField.getName()) && hasSameType(jApiField, removedAndNotOverriddenField)) { iterator.remove(); } } } for (JApiMethod jApiMethod : superclass.getMethods()) { if (jApiMethod.getChangeStatus() == JApiChangeStatus.REMOVED && !isImplemented(jApiMethod, jApiMethod.getjApiClass())) { boolean implemented = false; for (JApiMethod implementedMethod : implementedMethods) { if (jApiMethod.getName().equals(implementedMethod.getName()) && jApiMethod.hasSameSignature(implementedMethod)) { implemented = true; break; } } if (!implemented) { removedAndNotOverriddenMethods.add(jApiMethod); } } } for (JApiField jApiField : superclass.getFields()) { if (jApiField.getChangeStatus() == JApiChangeStatus.REMOVED) { boolean overridden = false; for (JApiField field : fields) { if (field.getName().equals(jApiField.getName()) && hasSameType(jApiField, field)) { overridden = true; } } if (!overridden) { removedAndNotOverriddenFields.add(jApiField); } } } return 0; } }); if (removedAndNotOverriddenMethods.size() > 0) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.METHOD_REMOVED_IN_SUPERCLASS); } if (removedAndNotOverriddenFields.size() > 0) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.FIELD_REMOVED_IN_SUPERCLASS); } if (superclass.getOldSuperclassName().isPresent() && superclass.getNewSuperclassName().isPresent()) { if (!superclass.getOldSuperclassName().get().equals(superclass.getNewSuperclassName().get())) { boolean superClassChangedToObject = false; boolean superClassChangedFromObject = false; if (!superclass.getOldSuperclassName().get().equals("java.lang.Object") && superclass.getNewSuperclassName().get().equals("java.lang.Object")) { superClassChangedToObject = true; } if (superclass.getOldSuperclassName().get().equals("java.lang.Object") && !superclass.getNewSuperclassName().get().equals("java.lang.Object")) { superClassChangedFromObject = true; } if (superClassChangedToObject) { addCompatibilityChange(superclass, JApiCompatibilityChange.SUPERCLASS_REMOVED); } else if (superClassChangedFromObject) { addCompatibilityChange(superclass, JApiCompatibilityChange.SUPERCLASS_ADDED); } else { // check if the old superclass is still an ancestor of the new superclass List<JApiSuperclass> ancestors = new ArrayList<>(); final List<JApiSuperclass> matchingAncestors = new ArrayList<>(); forAllSuperclasses(jApiClass, classMap, ancestors, new OnSuperclassCallback<JApiSuperclass>() { @Override public JApiSuperclass callback(JApiClass clazz, Map<String, JApiClass> classMap, JApiChangeStatus changeStatusOfSuperclass) { JApiSuperclass ancestor = clazz.getSuperclass(); if (ancestor.getNewSuperclassName().isPresent() && ancestor.getNewSuperclassName().get().equals(superclass.getOldSuperclassName().get())) { matchingAncestors.add(ancestor); } return ancestor; } }); if (matchingAncestors.isEmpty()) { addCompatibilityChange(superclass, JApiCompatibilityChange.SUPERCLASS_REMOVED); } else { // really, superclass(es) inserted - but the old superclass is still an ancestor addCompatibilityChange(superclass, JApiCompatibilityChange.SUPERCLASS_ADDED); } } } } else { if (superclass.getOldSuperclassName().isPresent()) { addCompatibilityChange(superclass, JApiCompatibilityChange.SUPERCLASS_REMOVED); } else if (superclass.getNewSuperclassName().isPresent()) { addCompatibilityChange(superclass, JApiCompatibilityChange.SUPERCLASS_ADDED); } } } // section 13.4.4 of "Java Language Specification" SE7 for (JApiImplementedInterface implementedInterface : jApiClass.getInterfaces()) { if (implementedInterface.getChangeStatus() == JApiChangeStatus.REMOVED) { addCompatibilityChange(implementedInterface, JApiCompatibilityChange.INTERFACE_REMOVED); } else { JApiClass interfaceClass = classMap.get(implementedInterface.getFullyQualifiedName()); if (interfaceClass == null) { interfaceClass = loadClass(implementedInterface.getFullyQualifiedName(), EnumSet.allOf(Classpath.class)); } if (implementedInterface.getChangeStatus() == JApiChangeStatus.MODIFIED || implementedInterface.getChangeStatus() == JApiChangeStatus.UNCHANGED) { implementedInterface.setJApiClass(interfaceClass); checkIfMethodsHaveChangedIncompatible(interfaceClass, classMap); checkIfFieldsHaveChangedIncompatible(interfaceClass, classMap); } else if (implementedInterface.getChangeStatus() == JApiChangeStatus.NEW) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.INTERFACE_ADDED); // no marker interface, no abstract class, no interface and annotation if (!interfaceClass.getMethods().isEmpty() && !isAbstract(jApiClass) && !isInterface(jApiClass) && !isAnnotation(jApiClass) && !isEnum(jApiClass)) { boolean allInterfaceMethodsImplemented = true; for (JApiMethod interfaceMethod : interfaceClass.getMethods()) { boolean interfaceMethodImplemented = false; if (isSynthetic(interfaceMethod)) { continue; } if (!isAbstract(interfaceMethod)) { //default implementation continue; } if (isImplemented(interfaceMethod, jApiClass)) { interfaceMethodImplemented = true; break; } if (!interfaceMethodImplemented) { allInterfaceMethodsImplemented = false; break; } } if (!allInterfaceMethodsImplemented) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.METHOD_ABSTRACT_ADDED_IN_IMPLEMENTED_INTERFACE); } } } } } checkIfClassNowCheckedException(jApiClass); checkIfAbstractMethodAddedInSuperclass(jApiClass, classMap); checkIfAbstractMethodAdded(jApiClass, classMap); } private boolean isAbstract(JApiMethod jApiMethod) { if (jApiMethod.getAbstractModifier().getNewModifier().isPresent()) { AbstractModifier abstractModifier = jApiMethod.getAbstractModifier().getNewModifier().get(); return abstractModifier == AbstractModifier.ABSTRACT; } return false; } private boolean hasSameType(JApiField field, JApiField otherField) { boolean hasSameNewType = false; if (field.getType().getNewTypeOptional().isPresent() && otherField.getType().getNewTypeOptional().isPresent()) { hasSameNewType = field.getType().getNewTypeOptional().get().equals(otherField.getType().getNewTypeOptional().get()); } else if (field.getType().getOldTypeOptional().isPresent() && otherField.getType().getNewTypeOptional().isPresent()) { hasSameNewType = field.getType().getOldTypeOptional().get().equals(otherField.getType().getNewTypeOptional().get()); } else if (field.getType().getOldTypeOptional().isPresent() && otherField.getType().getOldTypeOptional().isPresent()) { hasSameNewType = field.getType().getOldTypeOptional().get().equals(otherField.getType().getOldTypeOptional().get()); } else if (field.getType().getNewTypeOptional().isPresent() && otherField.getType().getOldTypeOptional().isPresent()) { hasSameNewType = field.getType().getNewTypeOptional().get().equals(otherField.getType().getOldTypeOptional().get()); } return hasSameNewType; } private void checkIfAbstractMethodAdded(JApiClass jApiClass, Map<String, JApiClass> classMap) { if (jApiClass.getChangeStatus() != JApiChangeStatus.NEW && !isAbstract(jApiClass)) { //TODO compute hull of all methods and check if there are any abstract methods not implemented } } private void checkIfAbstractMethodAddedInSuperclass(final JApiClass jApiClass, Map<String, JApiClass> classMap) { if (jApiClass.getChangeStatus() != JApiChangeStatus.NEW && isClass(jApiClass)) { final List<JApiMethod> abstractMethods = new ArrayList<>(); final List<JApiMethod> defaultMethods = new ArrayList<>(); final List<JApiMethod> implementedMethods = new ArrayList<>(); final List<JApiImplementedInterface> implementedInterfaces = new ArrayList<>(); for (JApiMethod jApiMethod : jApiClass.getMethods()) { if (!isAbstract(jApiMethod)) { implementedMethods.add(jApiMethod); } } forAllSuperclasses(jApiClass, classMap, new ArrayList<Integer>(), new OnSuperclassCallback<Integer>() { @Override public Integer callback(JApiClass superclass, Map<String, JApiClass> classMap, JApiChangeStatus changeStatusOfSuperclass) { for (JApiMethod jApiMethod : superclass.getMethods()) { if (!isAbstract(jApiMethod)) { implementedMethods.add(jApiMethod); } } for (JApiMethod jApiMethod : superclass.getMethods()) { if (isAbstract(jApiMethod)) { boolean isImplemented = false; for (JApiMethod implementedMethod : implementedMethods) { if (jApiMethod.getName().equals(implementedMethod.getName()) && jApiMethod.hasSameSignature(implementedMethod)) { isImplemented = true; break; } } if (!isImplemented) { if (jApiMethod.getChangeStatus() == JApiChangeStatus.NEW || changeStatusOfSuperclass == JApiChangeStatus.NEW || changeStatusOfSuperclass == JApiChangeStatus.MODIFIED) { if (jApiMethod.getAbstractModifier().getNewModifier().isPresent()) { AbstractModifier abstractModifier = jApiMethod.getAbstractModifier().getNewModifier().get(); if (abstractModifier == AbstractModifier.ABSTRACT) { abstractMethods.add(jApiMethod); } else { defaultMethods.add(jApiMethod); } } } } } } implementedInterfaces.addAll(superclass.getInterfaces()); return 0; } }); implementedInterfaces.addAll(jApiClass.getInterfaces()); if (abstractMethods.size() > 0) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.METHOD_ABSTRACT_ADDED_IN_SUPERCLASS); } abstractMethods.clear(); for (JApiImplementedInterface jApiImplementedInterface : implementedInterfaces) { JApiClass interfaceClass = getJApiClass(jApiImplementedInterface, classMap); for (JApiMethod interfaceMethod : interfaceClass.getMethods()) { boolean isImplemented = false; for (JApiMethod implementedMethod : implementedMethods) { if (areMatching(interfaceMethod, implementedMethod)) { isImplemented = true; break; } } if (!isImplemented) { if (interfaceMethod.getChangeStatus() == JApiChangeStatus.NEW || jApiImplementedInterface.getChangeStatus() == JApiChangeStatus.NEW) { if (interfaceMethod.getAbstractModifier().getNewModifier().isPresent()) { AbstractModifier abstractModifier = interfaceMethod.getAbstractModifier().getNewModifier().get(); if (abstractModifier == AbstractModifier.ABSTRACT) { abstractMethods.add(interfaceMethod); } else { defaultMethods.add(interfaceMethod); } } } } } } final List<JApiMethod> abstractMethodsWithDefaultInInterface = new ArrayList<>(); for (JApiMethod abstractMethod : abstractMethods) { for (JApiImplementedInterface implementedInterface : implementedInterfaces) { final JApiClass interfaceClass = getJApiClass(implementedInterface, classMap); for (JApiMethod defaultMethodCandidate : interfaceClass.getMethods()) { if (!isAbstract(defaultMethodCandidate) && areMatching(abstractMethod, defaultMethodCandidate)) { // we have a default implementation for this method // double-check that we extend interface that the method comes from for (JApiImplementedInterface extendedInterface : interfaceClass.getInterfaces()) { JApiClass extendedInterfaceClass = getJApiClass(extendedInterface, classMap); if (abstractMethod.getjApiClass().equals(extendedInterfaceClass)) { abstractMethodsWithDefaultInInterface.add(abstractMethod); } } } } } } abstractMethods.removeAll(abstractMethodsWithDefaultInInterface); if (!abstractMethods.isEmpty()) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.METHOD_ABSTRACT_ADDED_IN_IMPLEMENTED_INTERFACE); } if (!defaultMethods.isEmpty()) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.METHOD_DEFAULT_ADDED_IN_IMPLEMENTED_INTERFACE); } } } private static boolean areMatching(JApiMethod left, JApiMethod right) { return left.getName().equals(right.getName()) && left.hasSameSignature(right); } private JApiClass getJApiClass(JApiImplementedInterface implementedInterface, Map<String, JApiClass> classMap) { String fullyQualifiedName = implementedInterface.getFullyQualifiedName(); JApiClass interfaceClass = classMap.get(fullyQualifiedName); if (interfaceClass == null) { interfaceClass = loadClass(fullyQualifiedName, EnumSet.allOf(Classpath.class)); } return interfaceClass; } private void checkIfClassNowCheckedException(JApiClass jApiClass) { JApiSuperclass jApiClassSuperclass = jApiClass.getSuperclass(); if (jApiClassSuperclass.getChangeStatus() == JApiChangeStatus.MODIFIED) { if (jApiClassSuperclass.getNewSuperclassName().isPresent()) { String fqn = jApiClassSuperclass.getNewSuperclassName().get(); if ("java.lang.Exception".equals(fqn)) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.CLASS_NOW_CHECKED_EXCEPTION); } } } } private void addCompatibilityChange(JApiCompatibility binaryCompatibility, JApiCompatibilityChange compatibilityChange) { List<JApiCompatibilityChange> compatibilityChanges = binaryCompatibility.getCompatibilityChanges(); if (!compatibilityChanges.contains(compatibilityChange)) { compatibilityChanges.add(compatibilityChange); } } }
japicmp/src/main/java/japicmp/compat/CompatibilityChanges.java
package japicmp.compat; import japicmp.cmp.JarArchiveComparator; import japicmp.cmp.JarArchiveComparatorOptions; import japicmp.exception.JApiCmpException; import japicmp.model.*; import japicmp.util.ClassHelper; import japicmp.util.Optional; import japicmp.util.SignatureParser; import javassist.ClassPool; import javassist.CtClass; import javassist.NotFoundException; import java.util.*; import static japicmp.util.ModifierHelper.*; public class CompatibilityChanges { private final JarArchiveComparator jarArchiveComparator; public CompatibilityChanges(JarArchiveComparator jarArchiveComparator) { this.jarArchiveComparator = jarArchiveComparator; } public void evaluate(List<JApiClass> classes) { Map<String, JApiClass> classMap = buildClassMap(classes); for (JApiClass clazz : classes) { evaluateBinaryCompatibility(clazz, classMap); } } private Map<String, JApiClass> buildClassMap(List<JApiClass> classes) { Map<String, JApiClass> classMap = new HashMap<>(); for (JApiClass clazz : classes) { classMap.put(clazz.getFullyQualifiedName(), clazz); } return classMap; } private void evaluateBinaryCompatibility(JApiClass jApiClass, Map<String, JApiClass> classMap) { if (jApiClass.getChangeStatus() == JApiChangeStatus.REMOVED) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.CLASS_REMOVED); } else if (jApiClass.getChangeStatus() == JApiChangeStatus.MODIFIED) { // section 13.4.1 of "Java Language Specification" SE7 if (jApiClass.getAbstractModifier().hasChangedFromTo(AbstractModifier.NON_ABSTRACT, AbstractModifier.ABSTRACT)) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.CLASS_NOW_ABSTRACT); } // section 13.4.2 of "Java Language Specification" SE7 if (jApiClass.getFinalModifier().hasChangedFromTo(FinalModifier.NON_FINAL, FinalModifier.FINAL)) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.CLASS_NOW_FINAL); } // section 13.4.3 of "Java Language Specification" SE7 if (jApiClass.getAccessModifier().hasChangedFrom(AccessModifier.PUBLIC)) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.CLASS_NO_LONGER_PUBLIC); } } // section 13.4.4 of "Java Language Specification" SE7 checkIfSuperclassesOrInterfacesChangedIncompatible(jApiClass, classMap); checkIfMethodsHaveChangedIncompatible(jApiClass, classMap); checkIfConstructorsHaveChangedIncompatible(jApiClass, classMap); checkIfFieldsHaveChangedIncompatible(jApiClass, classMap); if (jApiClass.getClassType().getChangeStatus() == JApiChangeStatus.MODIFIED) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.CLASS_TYPE_CHANGED); } checkIfAnnotationDeprecatedAdded(jApiClass); if (hasModifierLevelDecreased(jApiClass)) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.CLASS_LESS_ACCESSIBLE); } checkIfGenericTemplatesHaveChanged(jApiClass); } private void checkIfGenericTemplatesHaveChanged(JApiHasGenericTemplates jApiHasGenericTemplates) { for (JApiGenericTemplate jApiGenericTemplate : jApiHasGenericTemplates.getGenericTemplates()) { if (jApiGenericTemplate.getChangeStatus() != JApiChangeStatus.UNCHANGED) { ((JApiCompatibility)jApiHasGenericTemplates).getCompatibilityChanges().add(JApiCompatibilityChange.CLASS_GENERIC_TEMPLATE_CHANGED); break; } } for (JApiGenericTemplate jApiGenericTemplate : jApiHasGenericTemplates.getGenericTemplates()) { JApiChangeStatus changeStatus = jApiGenericTemplate.getChangeStatus(); if (changeStatus == JApiChangeStatus.MODIFIED || changeStatus == JApiChangeStatus.UNCHANGED) { if (!SignatureParser.equalGenericTypes(jApiGenericTemplate.getOldGenericTypes(), jApiGenericTemplate.getNewGenericTypes())) { jApiGenericTemplate.getCompatibilityChanges().add(JApiCompatibilityChange.CLASS_GENERIC_TEMPLATE_GENERICS_CHANGED); ((JApiCompatibility)jApiHasGenericTemplates).getCompatibilityChanges().add(JApiCompatibilityChange.CLASS_GENERIC_TEMPLATE_GENERICS_CHANGED); break; } } } } private void checkIfFieldsHaveChangedIncompatible(JApiClass jApiClass, Map<String, JApiClass> classMap) { for (final JApiField field : jApiClass.getFields()) { // section 13.4.6 of "Java Language Specification" SE7 if (isNotPrivate(field) && field.getChangeStatus() == JApiChangeStatus.REMOVED) { ArrayList<Integer> returnValues = new ArrayList<>(); forAllSuperclasses(jApiClass, classMap, returnValues, (superclass, classMap1, changeStatusOfSuperclass) -> { int movedToSuperclass = 0; for (JApiField superclassField : superclass.getFields()) { if (superclassField.getName().equals(field.getName()) && fieldTypeMatches(superclassField, field) && isNotPrivate(superclassField)) { movedToSuperclass = 1; } } return movedToSuperclass; }); boolean movedToSuperclass = false; for (Integer returnValue : returnValues) { if (returnValue == 1) { movedToSuperclass = true; } } if (!movedToSuperclass) { addCompatibilityChange(field, JApiCompatibilityChange.FIELD_REMOVED); } } // section 13.4.7 of "Java Language Specification" SE7 if (hasModifierLevelDecreased(field)) { addCompatibilityChange(field, JApiCompatibilityChange.FIELD_LESS_ACCESSIBLE); } // section 13.4.8 of "Java Language Specification" SE7 if (isNotPrivate(field) && field.getChangeStatus() == JApiChangeStatus.NEW) { ArrayList<Integer> returnValues = new ArrayList<>(); forAllSuperclasses(jApiClass, classMap, returnValues, new OnSuperclassCallback<Integer>() { @Override public Integer callback(JApiClass superclass, Map<String, JApiClass> classMap, JApiChangeStatus changeStatusOfSuperclass) { int changedIncompatible = 0; for (JApiField superclassField : superclass.getFields()) { if (superclassField.getName().equals(field.getName()) && fieldTypeMatches(superclassField, field)) { boolean superclassFieldIsStatic = false; boolean subclassFieldIsStatic = false; boolean accessModifierSubclassLess = false; if (field.getStaticModifier().getNewModifier().isPresent() && field.getStaticModifier().getNewModifier().get() == StaticModifier.STATIC) { subclassFieldIsStatic = true; } if (superclassField.getStaticModifier().getNewModifier().isPresent() && superclassField.getStaticModifier().getNewModifier().get() == StaticModifier.STATIC && superclassField.getChangeStatus() != JApiChangeStatus.NEW) { superclassFieldIsStatic = true; } if (field.getAccessModifier().getNewModifier().isPresent() && superclassField.getAccessModifier().getNewModifier().isPresent()) { if (field.getAccessModifier().getNewModifier().get().getLevel() < superclassField.getAccessModifier().getNewModifier().get().getLevel() && superclassField.getChangeStatus() != JApiChangeStatus.NEW) { accessModifierSubclassLess = true; } } if (superclassFieldIsStatic) { if (subclassFieldIsStatic) { changedIncompatible = 1; } } if (accessModifierSubclassLess) { changedIncompatible = 2; } } } return changedIncompatible; } }); for (int returnValue : returnValues) { if (returnValue == 1) { addCompatibilityChange(field, JApiCompatibilityChange.FIELD_STATIC_AND_OVERRIDES_STATIC); } else if (returnValue == 2) { addCompatibilityChange(field, JApiCompatibilityChange.FIELD_LESS_ACCESSIBLE_THAN_IN_SUPERCLASS); } } } // section 13.4.9 of "Java Language Specification" SE7 if (isNotPrivate(field) && field.getFinalModifier().hasChangedFromTo(FinalModifier.NON_FINAL, FinalModifier.FINAL)) { addCompatibilityChange(field, JApiCompatibilityChange.FIELD_NOW_FINAL); } // section 13.4.10 of "Java Language Specification" SE7 if (isNotPrivate(field)) { if (field.getStaticModifier().hasChangedFromTo(StaticModifier.NON_STATIC, StaticModifier.STATIC)) { addCompatibilityChange(field, JApiCompatibilityChange.FIELD_NOW_STATIC); } if (field.getStaticModifier().hasChangedFromTo(StaticModifier.STATIC, StaticModifier.NON_STATIC)) { addCompatibilityChange(field, JApiCompatibilityChange.FIELD_NO_LONGER_STATIC); } } if (isNotPrivate(field) && field.getType().hasChanged()) { addCompatibilityChange(field, JApiCompatibilityChange.FIELD_TYPE_CHANGED); } checkIfAnnotationDeprecatedAdded(field); checkIfFieldGenericsChanged(field); } } private interface OnSuperclassCallback<T> { T callback(JApiClass superclass, Map<String, JApiClass> classMap, JApiChangeStatus changeStatusOfSuperclass); } private interface OnImplementedInterfaceCallback<T> { T callback(JApiClass implementedInterface, Map<String, JApiClass> classMap); } private <T> void forAllSuperclasses(JApiClass jApiClass, Map<String, JApiClass> classMap, List<T> returnValues, OnSuperclassCallback<T> onSuperclassCallback) { JApiSuperclass superclass = jApiClass.getSuperclass(); if (superclass.getNewSuperclassName().isPresent()) { String newSuperclassName = superclass.getNewSuperclassName().get(); JApiClass foundClass = classMap.get(newSuperclassName); if (foundClass == null) { Optional<JApiClass> superclassJApiClassOptional = superclass.getJApiClass(); if (superclassJApiClassOptional.isPresent()) { foundClass = superclassJApiClassOptional.get(); } else { foundClass = loadClass(newSuperclassName, EnumSet.of(Classpath.NEW_CLASSPATH)); evaluate(Collections.singletonList(foundClass)); } classMap.put(foundClass.getFullyQualifiedName(), foundClass); } T returnValue = onSuperclassCallback.callback(foundClass, classMap, superclass.getChangeStatus()); returnValues.add(returnValue); forAllSuperclasses(foundClass, classMap, returnValues, onSuperclassCallback); } } private enum Classpath { OLD_CLASSPATH, NEW_CLASSPATH } private JApiClass loadClass(String newSuperclassName, EnumSet<Classpath> classpaths) { JApiClass foundClass; Optional<CtClass> oldClassOptional = Optional.absent(); Optional<CtClass> newClassOptional = Optional.absent(); JarArchiveComparatorOptions.ClassPathMode classPathMode = this.jarArchiveComparator.getJarArchiveComparatorOptions().getClassPathMode(); if (classPathMode == JarArchiveComparatorOptions.ClassPathMode.ONE_COMMON_CLASSPATH) { ClassPool classPool = this.jarArchiveComparator.getCommonClassPool(); try { oldClassOptional = Optional.of(classPool.get(newSuperclassName)); } catch (NotFoundException ignored) {} try { newClassOptional = Optional.of(classPool.get(newSuperclassName)); } catch (NotFoundException ignored) {} } else { if (classpaths.contains(Classpath.OLD_CLASSPATH)) { ClassPool oldClassPool = this.jarArchiveComparator.getOldClassPool(); try { oldClassOptional = Optional.of(oldClassPool.get(newSuperclassName)); } catch (NotFoundException ignored) {} } if (classpaths.contains(Classpath.NEW_CLASSPATH)) { ClassPool newClassPool = this.jarArchiveComparator.getNewClassPool(); try { newClassOptional = Optional.of(newClassPool.get(newSuperclassName)); } catch (NotFoundException ignored) {} } } if (!oldClassOptional.isPresent() && !newClassOptional.isPresent()) { if (!this.jarArchiveComparator.getJarArchiveComparatorOptions().getIgnoreMissingClasses().ignoreClass(newSuperclassName)) { throw JApiCmpException.forClassLoading(newSuperclassName, this.jarArchiveComparator); } } JApiClassType classType; JApiChangeStatus changeStatus = JApiChangeStatus.UNCHANGED; if (oldClassOptional.isPresent() && newClassOptional.isPresent()) { classType = new JApiClassType(Optional.of(ClassHelper.getType(oldClassOptional.get())), Optional.of(ClassHelper.getType(newClassOptional.get())), JApiChangeStatus.UNCHANGED); } else if (oldClassOptional.isPresent() && !newClassOptional.isPresent()) { classType = new JApiClassType(Optional.of(ClassHelper.getType(oldClassOptional.get())), Optional.<JApiClassType.ClassType>absent(), JApiChangeStatus.REMOVED); } else if (!oldClassOptional.isPresent() && newClassOptional.isPresent()) { classType = new JApiClassType(Optional.<JApiClassType.ClassType>absent(), Optional.of(ClassHelper.getType(newClassOptional.get())), JApiChangeStatus.NEW); } else { classType = new JApiClassType(Optional.<JApiClassType.ClassType>absent(), Optional.<JApiClassType.ClassType>absent(), JApiChangeStatus.UNCHANGED); } foundClass = new JApiClass(this.jarArchiveComparator, newSuperclassName, oldClassOptional, newClassOptional, changeStatus, classType); return foundClass; } private boolean fieldTypeMatches(JApiField field1, JApiField field2) { boolean matches = true; JApiType type1 = field1.getType(); JApiType type2 = field2.getType(); if (type1.getNewTypeOptional().isPresent() && type2.getNewTypeOptional().isPresent()) { if (!type1.getNewTypeOptional().get().equals(type2.getNewTypeOptional().get())) { matches = false; } } return matches; } private void checkIfConstructorsHaveChangedIncompatible(JApiClass jApiClass, Map<String, JApiClass> classMap) { for (JApiConstructor constructor : jApiClass.getConstructors()) { // section 13.4.6 of "Java Language Specification" SE7 if (isNotPrivate(constructor) && constructor.getChangeStatus() == JApiChangeStatus.REMOVED) { addCompatibilityChange(constructor, JApiCompatibilityChange.CONSTRUCTOR_REMOVED); } // section 13.4.7 of "Java Language Specification" SE7 if (hasModifierLevelDecreased(constructor)) { if (isNotFinal(jApiClass) || constructor.getAccessModifier().hasChangedFrom(AccessModifier.PUBLIC)) { addCompatibilityChange(constructor, JApiCompatibilityChange.CONSTRUCTOR_LESS_ACCESSIBLE); } } checkIfExceptionIsNowChecked(constructor); checkIfAnnotationDeprecatedAdded(constructor); checkIfVarargsChanged(constructor); checkIfParametersGenericsChanged(constructor); checkIfGenericTemplatesHaveChanged(constructor); } } private static boolean isNotFinal(JApiClass jApiClass) { return !(jApiClass.getFinalModifier().getNewModifier().isPresent() && jApiClass.getFinalModifier().getNewModifier().get() == FinalModifier.FINAL); } private void checkIfMethodsHaveChangedIncompatible(JApiClass jApiClass, Map<String, JApiClass> classMap) { for (final JApiMethod method : jApiClass.getMethods()) { // section 13.4.6 of "Java Language Specification" SE7 if (isNotPrivate(method) && method.getChangeStatus() == JApiChangeStatus.REMOVED) { final List<Integer> returnValues = new ArrayList<>(); forAllSuperclasses(jApiClass, classMap, returnValues, new OnSuperclassCallback<Integer>() { @Override public Integer callback(JApiClass superclass, Map<String, JApiClass> classMap, JApiChangeStatus changeStatusOfSuperclass) { for (JApiMethod superMethod : superclass.getMethods()) { if (superMethod.getName().equals(method.getName()) && superMethod.hasSameParameter(method) && superMethod.hasSameReturnType(method)) { return 1; } } return 0; } }); checkIfMethodHasBeenPulledUp(jApiClass, classMap, method, returnValues); boolean superclassHasSameMethod = false; for (Integer returnValue : returnValues) { if (returnValue == 1) { superclassHasSameMethod = true; } } if (!superclassHasSameMethod) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_REMOVED); } } if (!isInterface(jApiClass) && method.getChangeStatus() == JApiChangeStatus.NEW && method.getAccessModifier().getNewModifier().get().getLevel() == AccessModifier.PUBLIC.getLevel()) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_ADDED_TO_PUBLIC_CLASS); } // section 13.4.7 of "Java Language Specification" SE7 if (hasModifierLevelDecreased(method)) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_LESS_ACCESSIBLE); } // section 13.4.12 of "Java Language Specification" SE7 if (isNotPrivate(method) && method.getChangeStatus() == JApiChangeStatus.NEW) { List<Integer> returnValues = new ArrayList<>(); forAllSuperclasses(jApiClass, classMap, returnValues, new OnSuperclassCallback<Integer>() { @Override public Integer callback(JApiClass superclass, Map<String, JApiClass> classMap, JApiChangeStatus changeStatusOfSuperclass) { for (JApiMethod superMethod : superclass.getMethods()) { if (superMethod.getName().equals(method.getName()) && superMethod.hasSameParameter(method) && superMethod.hasSameReturnType(method)) { if (superMethod.getAccessModifier().getNewModifier().isPresent() && method.getAccessModifier().getNewModifier().isPresent()) { if (superMethod.getAccessModifier().getNewModifier().get().getLevel() > method.getAccessModifier().getNewModifier().get().getLevel()) { return 1; } } if (superMethod.getStaticModifier().getNewModifier().isPresent() && method.getStaticModifier().getNewModifier().isPresent()) { if (superMethod.getStaticModifier().getNewModifier().get() == StaticModifier.NON_STATIC && method.getStaticModifier().getNewModifier().get() == StaticModifier.STATIC) { return 2; } } } } return 0; } }); for (Integer returnValue : returnValues) { if (returnValue == 1) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_LESS_ACCESSIBLE_THAN_IN_SUPERCLASS); } else if (returnValue == 2) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_IS_STATIC_AND_OVERRIDES_NOT_STATIC); } } } checkIfReturnTypeChanged(method); // section 13.4.16 of "Java Language Specification" SE7 if (isNotPrivate(method) && method.getAbstractModifier().hasChangedFromTo(AbstractModifier.NON_ABSTRACT, AbstractModifier.ABSTRACT)) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_NOW_ABSTRACT); } // section 13.4.17 of "Java Language Specification" SE7 if (isNotPrivate(method) && method.getFinalModifier().hasChangedFromTo(FinalModifier.NON_FINAL, FinalModifier.FINAL)) { if ((jApiClass.getFinalModifier().getOldModifier().isPresent() && jApiClass.getFinalModifier().getOldModifier().get() != FinalModifier.FINAL) && !(method.getStaticModifier().getOldModifier().isPresent() && method.getStaticModifier().getOldModifier().get() == StaticModifier.STATIC)) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_NOW_FINAL); } } // section 13.4.18 of "Java Language Specification" SE7 if (isNotPrivate(method)) { if (method.getStaticModifier().hasChangedFromTo(StaticModifier.NON_STATIC, StaticModifier.STATIC)) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_NOW_STATIC); } if (method.getStaticModifier().hasChangedFromTo(StaticModifier.STATIC, StaticModifier.NON_STATIC)) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_NO_LONGER_STATIC); } } checkAbstractMethod(jApiClass, classMap, method); checkIfExceptionIsNowChecked(method); checkIfAnnotationDeprecatedAdded(method); checkIfVarargsChanged(method); checkIfParametersGenericsChanged(method); checkIfGenericTemplatesHaveChanged(method); } } private void checkIfReturnTypeChanged(JApiMethod method) { // section 13.4.15 of "Java Language Specification" SE7 (Method Result Type) if (method.getReturnType().getChangeStatus() == JApiChangeStatus.MODIFIED) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_RETURN_TYPE_CHANGED); } if (method.getChangeStatus() == JApiChangeStatus.MODIFIED || method.getChangeStatus() == JApiChangeStatus.UNCHANGED) { if (!SignatureParser.equalGenericTypes(method.getReturnType().getOldGenericTypes(), method.getReturnType().getNewGenericTypes())) { addCompatibilityChange(method.getReturnType(), JApiCompatibilityChange.METHOD_RETURN_TYPE_GENERICS_CHANGED); } } } private void checkIfParametersGenericsChanged(JApiBehavior jApiBehavior) { if (jApiBehavior.getChangeStatus() == JApiChangeStatus.MODIFIED || jApiBehavior.getChangeStatus() == JApiChangeStatus.UNCHANGED) { for (JApiParameter jApiParameter : jApiBehavior.getParameters()) { if (!SignatureParser.equalGenericTypes(jApiParameter.getOldGenericTypes(), jApiParameter.getNewGenericTypes())) { jApiParameter.getCompatibilityChanges().add(JApiCompatibilityChange.METHOD_PARAMETER_GENERICS_CHANGED); } } } } private void checkIfFieldGenericsChanged(JApiField jApiField) { if (jApiField.getChangeStatus() == JApiChangeStatus.MODIFIED || jApiField.getChangeStatus() == JApiChangeStatus.UNCHANGED) { if (!SignatureParser.equalGenericTypes(jApiField.getOldGenericTypes(), jApiField.getNewGenericTypes())) { jApiField.getCompatibilityChanges().add(JApiCompatibilityChange.FIELD_GENERICS_CHANGED); } } } private void checkIfAnnotationDeprecatedAdded(JApiHasAnnotations jApiHasAnnotations) { for (JApiAnnotation annotation : jApiHasAnnotations.getAnnotations()) { if (annotation.getChangeStatus() == JApiChangeStatus.NEW || annotation.getChangeStatus() == JApiChangeStatus.MODIFIED) { if (annotation.getFullyQualifiedName().equals(Deprecated.class.getName())) { addCompatibilityChange((JApiCompatibility) jApiHasAnnotations, JApiCompatibilityChange.ANNOTATION_DEPRECATED_ADDED); } } } } private void checkIfVarargsChanged(JApiBehavior behavior) { if (behavior.getVarargsModifier().hasChangedFromTo(VarargsModifier.VARARGS, VarargsModifier.NON_VARARGS)) { addCompatibilityChange(behavior, JApiCompatibilityChange.METHOD_NO_LONGER_VARARGS); } if (behavior.getVarargsModifier().hasChangedFromTo(VarargsModifier.NON_VARARGS, VarargsModifier.VARARGS)) { addCompatibilityChange(behavior, JApiCompatibilityChange.METHOD_NOW_VARARGS); } } private void checkAbstractMethod(JApiClass jApiClass, Map<String, JApiClass> classMap, JApiMethod method) { if (isInterface(jApiClass)) { if (jApiClass.getChangeStatus() != JApiChangeStatus.NEW) { if (method.getChangeStatus() == JApiChangeStatus.NEW && !isSynthetic(method)) { List<JApiMethod> methodsWithSameSignature = getMethodsInImplementedInterfacesWithSameSignature(jApiClass, classMap, method); if (methodsWithSameSignature.size() == 0) { // new default method in interface if (method.getAbstractModifier().hasChangedTo(AbstractModifier.NON_ABSTRACT)) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_NEW_DEFAULT); } else { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_ADDED_TO_INTERFACE); } } else { boolean allNew = true; for (JApiMethod jApiMethod : methodsWithSameSignature) { if (jApiMethod.getChangeStatus() != JApiChangeStatus.NEW) { allNew = false; } } if (allNew) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_ADDED_TO_INTERFACE); } } } else if (method.getChangeStatus() == JApiChangeStatus.MODIFIED || method.getChangeStatus() == JApiChangeStatus.UNCHANGED) { JApiModifier<AbstractModifier> abstractModifier = method.getAbstractModifier(); // method changed from abstract to default if (abstractModifier.getOldModifier().isPresent() && abstractModifier.getOldModifier().get() == AbstractModifier.ABSTRACT && abstractModifier.getNewModifier().isPresent() && abstractModifier.getNewModifier().get() == AbstractModifier.NON_ABSTRACT) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_ABSTRACT_NOW_DEFAULT); } } } } else { if (isAbstract(method)) { if (jApiClass.getChangeStatus() != JApiChangeStatus.NEW) { if (method.getChangeStatus() == JApiChangeStatus.NEW && !isSynthetic(method)) { List<JApiMethod> overriddenMethods = getOverriddenMethods(jApiClass, classMap, method); boolean overridesAbstract = false; for (JApiMethod jApiMethod : overriddenMethods) { if (isAbstract(jApiMethod) && jApiMethod.getChangeStatus() != JApiChangeStatus.NEW) { overridesAbstract = true; } } List<JApiMethod> implementedMethods = getMethodsInImplementedInterfacesWithSameSignature(jApiClass, classMap, method); if (implementedMethods.size() > 0) { overridesAbstract = true; } if (!overridesAbstract) { addCompatibilityChange(method, JApiCompatibilityChange.METHOD_ABSTRACT_ADDED_TO_CLASS); } } } } } } private List<JApiMethod> getOverriddenMethods(final JApiClass jApiClass, final Map<String, JApiClass> classMap, final JApiMethod method) { ArrayList<JApiMethod> jApiMethods = new ArrayList<>(); forAllSuperclasses(jApiClass, classMap, jApiMethods, new OnSuperclassCallback<JApiMethod>() { @Override public JApiMethod callback(JApiClass superclass, Map<String, JApiClass> classMap, JApiChangeStatus changeStatusOfSuperclass) { for (JApiMethod jApiMethod : superclass.getMethods()) { if (isAbstract(jApiMethod)) { if (jApiMethod.getName().equals(method.getName()) && jApiMethod.hasSameSignature(method)) { return jApiMethod; } } } return null; } }); return removeNullValues(jApiMethods); } private List<JApiMethod> removeNullValues(ArrayList<JApiMethod> jApiMethods) { ArrayList<JApiMethod> returnValues = new ArrayList<>(); for (JApiMethod jApiMethod : jApiMethods) { if (jApiMethod != null) { returnValues.add(jApiMethod); } } return returnValues; } private List<JApiMethod> getMethodsInImplementedInterfacesWithSameSignature(final JApiClass jApiClass, final Map<String, JApiClass> classMap, final JApiMethod method) { ArrayList<JApiMethod> jApiMethods = new ArrayList<>(); forAllImplementedInterfaces(jApiClass, classMap, jApiMethods, new ArrayList<>(), new OnImplementedInterfaceCallback<JApiMethod>() { @Override public JApiMethod callback(JApiClass implementedInterface, Map<String, JApiClass> classMap) { for (JApiMethod jApiMethod : implementedInterface.getMethods()) { if (jApiMethod.getName().equals(method.getName()) && jApiMethod.hasSameSignature(method)) { return jApiMethod; } } return null; } }); return removeNullValues(jApiMethods); } private boolean isAbstract(JApiHasAbstractModifier jApiHasAbstractModifier) { boolean isAbstract = false; if (jApiHasAbstractModifier.getAbstractModifier().hasChangedTo(AbstractModifier.ABSTRACT)) { isAbstract = true; } return isAbstract; } private void checkIfExceptionIsNowChecked(JApiBehavior behavior) { for (JApiException exception : behavior.getExceptions()) { if (exception.getChangeStatus() == JApiChangeStatus.NEW && exception.isCheckedException() && behavior.getChangeStatus() != JApiChangeStatus.NEW) { addCompatibilityChange(behavior, JApiCompatibilityChange.METHOD_NOW_THROWS_CHECKED_EXCEPTION); } if (exception.getChangeStatus() == JApiChangeStatus.REMOVED && exception.isCheckedException() && behavior.getChangeStatus() != JApiChangeStatus.REMOVED) { addCompatibilityChange(behavior, JApiCompatibilityChange.METHOD_NO_LONGER_THROWS_CHECKED_EXCEPTION); } } } private boolean isClass(final JApiClass jApiClass) { return jApiClass.getClassType().getNewTypeOptional().isPresent() && jApiClass.getClassType().getNewTypeOptional().get() == JApiClassType.ClassType.CLASS; } private boolean isInterface(final JApiClass jApiClass) { return jApiClass.getClassType().getNewTypeOptional().isPresent() && jApiClass.getClassType().getNewTypeOptional().get() == JApiClassType.ClassType.INTERFACE; } private boolean isAnnotation(final JApiClass jApiClass) { return jApiClass.getClassType().getNewTypeOptional().isPresent() && jApiClass.getClassType().getNewTypeOptional().get() == JApiClassType.ClassType.ANNOTATION; } private boolean isEnum(final JApiClass jApiClass) { return jApiClass.getClassType().getNewTypeOptional().isPresent() && jApiClass.getClassType().getNewTypeOptional().get() == JApiClassType.ClassType.ENUM; } private void checkIfMethodHasBeenPulledUp(JApiClass jApiClass, Map<String, JApiClass> classMap, final JApiMethod method, List<Integer> returnValues) { forAllImplementedInterfaces(jApiClass, classMap, returnValues, new ArrayList<>(), (implementedInterface, classMap1) -> { for (JApiMethod superMethod : implementedInterface.getMethods()) { if (superMethod.getName().equals(method.getName()) && superMethod.hasSameParameter(method) && superMethod.hasSameReturnType(method)) { return 1; } } return 0; }); } private <T> void forAllImplementedInterfaces(JApiClass jApiClass, Map<String, JApiClass> classMap, List<T> returnValues, List<JApiImplementedInterface> visited, OnImplementedInterfaceCallback<T> onImplementedInterfaceCallback) { List<JApiImplementedInterface> interfaces = jApiClass.getInterfaces(); for (JApiImplementedInterface implementedInterface : interfaces) { String fullyQualifiedName = implementedInterface.getFullyQualifiedName(); JApiClass foundClass = classMap.get(fullyQualifiedName); if (foundClass != null && visited.stream().noneMatch(v -> v.getFullyQualifiedName().equals(implementedInterface.getFullyQualifiedName()))) { T returnValue = onImplementedInterfaceCallback.callback(foundClass, classMap); returnValues.add(returnValue); visited.add(implementedInterface); forAllImplementedInterfaces(foundClass, classMap, returnValues, visited, onImplementedInterfaceCallback); } } } /** * Is a method implemented in a super class * @param jApiMethod the method * @return <code>true</code> if it is implemented in a super class */ private boolean isImplemented(JApiMethod jApiMethod, JApiClass aClass) { while(aClass != null) { for (JApiMethod method : aClass.getMethods()) { if (jApiMethod.getName().equals(method.getName()) && jApiMethod.hasSameParameter(method) && !isAbstract(method) && method.getChangeStatus() != JApiChangeStatus.REMOVED && isNotPrivate(method)) { return true; } } if(aClass.getSuperclass() != null && aClass.getSuperclass().getJApiClass().isPresent()) { aClass = aClass.getSuperclass().getJApiClass().get(); } else { aClass = null; } } return false; } private void checkIfSuperclassesOrInterfacesChangedIncompatible(final JApiClass jApiClass, Map<String, JApiClass> classMap) { final JApiSuperclass superclass = jApiClass.getSuperclass(); // section 13.4.4 of "Java Language Specification" SE7 if (superclass.getChangeStatus() == JApiChangeStatus.UNCHANGED || superclass.getChangeStatus() == JApiChangeStatus.MODIFIED || superclass.getChangeStatus() == JApiChangeStatus.REMOVED) { final List<JApiMethod> implementedMethods = new ArrayList<>(); final List<JApiMethod> removedAndNotOverriddenMethods = new ArrayList<>(); final List<JApiField> fields = new ArrayList<>(); final List<JApiField> removedAndNotOverriddenFields = new ArrayList<>(); for (JApiMethod jApiMethod : jApiClass.getMethods()) { if (!isAbstract(jApiMethod) && jApiMethod.getChangeStatus() != JApiChangeStatus.REMOVED && isNotPrivate(jApiMethod)) { implementedMethods.add(jApiMethod); } } for (JApiField jApiField : jApiClass.getFields()) { if (jApiField.getChangeStatus() != JApiChangeStatus.REMOVED && isNotPrivate(jApiField)) { fields.add(jApiField); } } forAllSuperclasses(jApiClass, classMap, new ArrayList<Integer>(), new OnSuperclassCallback<Integer>() { @Override public Integer callback(JApiClass superclass, Map<String, JApiClass> classMap, JApiChangeStatus changeStatusOfSuperclass) { for (JApiMethod jApiMethod : superclass.getMethods()) { if (!isAbstract(jApiMethod) && jApiMethod.getChangeStatus() != JApiChangeStatus.REMOVED && isNotPrivate(jApiMethod)) { implementedMethods.add(jApiMethod); } Iterator<JApiMethod> iterator = removedAndNotOverriddenMethods.iterator(); while (iterator.hasNext()) { JApiMethod removedAndNotOverriddenMethod = iterator.next(); if (jApiMethod.getName().equals(removedAndNotOverriddenMethod.getName()) && jApiMethod.hasSameSignature(removedAndNotOverriddenMethod)) { iterator.remove(); } } } for (JApiField jApiField : superclass.getFields()) { if (jApiField.getChangeStatus() != JApiChangeStatus.REMOVED && isNotPrivate(jApiField)) { fields.add(jApiField); } Iterator<JApiField> iterator = removedAndNotOverriddenFields.iterator(); while (iterator.hasNext()) { JApiField removedAndNotOverriddenField = iterator.next(); if (jApiField.getName().equals(removedAndNotOverriddenField.getName()) && hasSameType(jApiField, removedAndNotOverriddenField)) { iterator.remove(); } } } for (JApiMethod jApiMethod : superclass.getMethods()) { if (jApiMethod.getChangeStatus() == JApiChangeStatus.REMOVED && !isImplemented(jApiMethod, jApiMethod.getjApiClass())) { boolean implemented = false; for (JApiMethod implementedMethod : implementedMethods) { if (jApiMethod.getName().equals(implementedMethod.getName()) && jApiMethod.hasSameSignature(implementedMethod)) { implemented = true; break; } } if (!implemented) { removedAndNotOverriddenMethods.add(jApiMethod); } } } for (JApiField jApiField : superclass.getFields()) { if (jApiField.getChangeStatus() == JApiChangeStatus.REMOVED) { boolean overridden = false; for (JApiField field : fields) { if (field.getName().equals(jApiField.getName()) && hasSameType(jApiField, field)) { overridden = true; } } if (!overridden) { removedAndNotOverriddenFields.add(jApiField); } } } return 0; } }); if (removedAndNotOverriddenMethods.size() > 0) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.METHOD_REMOVED_IN_SUPERCLASS); } if (removedAndNotOverriddenFields.size() > 0) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.FIELD_REMOVED_IN_SUPERCLASS); } if (superclass.getOldSuperclassName().isPresent() && superclass.getNewSuperclassName().isPresent()) { if (!superclass.getOldSuperclassName().get().equals(superclass.getNewSuperclassName().get())) { boolean superClassChangedToObject = false; boolean superClassChangedFromObject = false; if (!superclass.getOldSuperclassName().get().equals("java.lang.Object") && superclass.getNewSuperclassName().get().equals("java.lang.Object")) { superClassChangedToObject = true; } if (superclass.getOldSuperclassName().get().equals("java.lang.Object") && !superclass.getNewSuperclassName().get().equals("java.lang.Object")) { superClassChangedFromObject = true; } if (superClassChangedToObject) { addCompatibilityChange(superclass, JApiCompatibilityChange.SUPERCLASS_REMOVED); } else if (superClassChangedFromObject) { addCompatibilityChange(superclass, JApiCompatibilityChange.SUPERCLASS_ADDED); } else { // check if the old superclass is still an ancestor of the new superclass List<JApiSuperclass> ancestors = new ArrayList<>(); final List<JApiSuperclass> matchingAncestors = new ArrayList<>(); forAllSuperclasses(jApiClass, classMap, ancestors, new OnSuperclassCallback<JApiSuperclass>() { @Override public JApiSuperclass callback(JApiClass clazz, Map<String, JApiClass> classMap, JApiChangeStatus changeStatusOfSuperclass) { JApiSuperclass ancestor = clazz.getSuperclass(); if (ancestor.getNewSuperclassName().isPresent() && ancestor.getNewSuperclassName().get().equals(superclass.getOldSuperclassName().get())) { matchingAncestors.add(ancestor); } return ancestor; } }); if (matchingAncestors.isEmpty()) { addCompatibilityChange(superclass, JApiCompatibilityChange.SUPERCLASS_REMOVED); } else { // really, superclass(es) inserted - but the old superclass is still an ancestor addCompatibilityChange(superclass, JApiCompatibilityChange.SUPERCLASS_ADDED); } } } } else { if (superclass.getOldSuperclassName().isPresent()) { addCompatibilityChange(superclass, JApiCompatibilityChange.SUPERCLASS_REMOVED); } else if (superclass.getNewSuperclassName().isPresent()) { addCompatibilityChange(superclass, JApiCompatibilityChange.SUPERCLASS_ADDED); } } } // section 13.4.4 of "Java Language Specification" SE7 for (JApiImplementedInterface implementedInterface : jApiClass.getInterfaces()) { if (implementedInterface.getChangeStatus() == JApiChangeStatus.REMOVED) { addCompatibilityChange(implementedInterface, JApiCompatibilityChange.INTERFACE_REMOVED); } else { JApiClass interfaceClass = classMap.get(implementedInterface.getFullyQualifiedName()); if (interfaceClass == null) { interfaceClass = loadClass(implementedInterface.getFullyQualifiedName(), EnumSet.allOf(Classpath.class)); } if (implementedInterface.getChangeStatus() == JApiChangeStatus.MODIFIED || implementedInterface.getChangeStatus() == JApiChangeStatus.UNCHANGED) { implementedInterface.setJApiClass(interfaceClass); checkIfMethodsHaveChangedIncompatible(interfaceClass, classMap); checkIfFieldsHaveChangedIncompatible(interfaceClass, classMap); } else if (implementedInterface.getChangeStatus() == JApiChangeStatus.NEW) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.INTERFACE_ADDED); // no marker interface, no abstract class, no interface and annotation if (!interfaceClass.getMethods().isEmpty() && !isAbstract(jApiClass) && !isInterface(jApiClass) && !isAnnotation(jApiClass) && !isEnum(jApiClass)) { boolean allInterfaceMethodsImplemented = true; for (JApiMethod interfaceMethod : interfaceClass.getMethods()) { boolean interfaceMethodImplemented = false; if (isSynthetic(interfaceMethod)) { continue; } if (!isAbstract(interfaceMethod)) { //default implementation continue; } if (isImplemented(interfaceMethod, jApiClass)) { interfaceMethodImplemented = true; break; } if (!interfaceMethodImplemented) { allInterfaceMethodsImplemented = false; break; } } if (!allInterfaceMethodsImplemented) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.METHOD_ABSTRACT_ADDED_IN_IMPLEMENTED_INTERFACE); } } } } } checkIfClassNowCheckedException(jApiClass); checkIfAbstractMethodAddedInSuperclass(jApiClass, classMap); checkIfAbstractMethodAdded(jApiClass, classMap); } private boolean isAbstract(JApiMethod jApiMethod) { if (jApiMethod.getAbstractModifier().getNewModifier().isPresent()) { AbstractModifier abstractModifier = jApiMethod.getAbstractModifier().getNewModifier().get(); return abstractModifier == AbstractModifier.ABSTRACT; } return false; } private boolean hasSameType(JApiField field, JApiField otherField) { boolean hasSameNewType = false; if (field.getType().getNewTypeOptional().isPresent() && otherField.getType().getNewTypeOptional().isPresent()) { hasSameNewType = field.getType().getNewTypeOptional().get().equals(otherField.getType().getNewTypeOptional().get()); } else if (field.getType().getOldTypeOptional().isPresent() && otherField.getType().getNewTypeOptional().isPresent()) { hasSameNewType = field.getType().getOldTypeOptional().get().equals(otherField.getType().getNewTypeOptional().get()); } else if (field.getType().getOldTypeOptional().isPresent() && otherField.getType().getOldTypeOptional().isPresent()) { hasSameNewType = field.getType().getOldTypeOptional().get().equals(otherField.getType().getOldTypeOptional().get()); } else if (field.getType().getNewTypeOptional().isPresent() && otherField.getType().getOldTypeOptional().isPresent()) { hasSameNewType = field.getType().getNewTypeOptional().get().equals(otherField.getType().getOldTypeOptional().get()); } return hasSameNewType; } private void checkIfAbstractMethodAdded(JApiClass jApiClass, Map<String, JApiClass> classMap) { if (jApiClass.getChangeStatus() != JApiChangeStatus.NEW && !isAbstract(jApiClass)) { //TODO compute hull of all methods and check if there are any abstract methods not implemented } } private void checkIfAbstractMethodAddedInSuperclass(final JApiClass jApiClass, Map<String, JApiClass> classMap) { if (jApiClass.getChangeStatus() != JApiChangeStatus.NEW && isClass(jApiClass)) { final List<JApiMethod> abstractMethods = new ArrayList<>(); final List<JApiMethod> defaultMethods = new ArrayList<>(); final List<JApiMethod> implementedMethods = new ArrayList<>(); final List<JApiImplementedInterface> implementedInterfaces = new ArrayList<>(); for (JApiMethod jApiMethod : jApiClass.getMethods()) { if (!isAbstract(jApiMethod)) { implementedMethods.add(jApiMethod); } } forAllSuperclasses(jApiClass, classMap, new ArrayList<Integer>(), new OnSuperclassCallback<Integer>() { @Override public Integer callback(JApiClass superclass, Map<String, JApiClass> classMap, JApiChangeStatus changeStatusOfSuperclass) { for (JApiMethod jApiMethod : superclass.getMethods()) { if (!isAbstract(jApiMethod)) { implementedMethods.add(jApiMethod); } } for (JApiMethod jApiMethod : superclass.getMethods()) { if (isAbstract(jApiMethod)) { boolean isImplemented = false; for (JApiMethod implementedMethod : implementedMethods) { if (jApiMethod.getName().equals(implementedMethod.getName()) && jApiMethod.hasSameSignature(implementedMethod)) { isImplemented = true; break; } } if (!isImplemented) { if (jApiMethod.getChangeStatus() == JApiChangeStatus.NEW || changeStatusOfSuperclass == JApiChangeStatus.NEW || changeStatusOfSuperclass == JApiChangeStatus.MODIFIED) { if (jApiMethod.getAbstractModifier().getNewModifier().isPresent()) { AbstractModifier abstractModifier = jApiMethod.getAbstractModifier().getNewModifier().get(); if (abstractModifier == AbstractModifier.ABSTRACT) { abstractMethods.add(jApiMethod); } else { defaultMethods.add(jApiMethod); } } } } } } implementedInterfaces.addAll(superclass.getInterfaces()); return 0; } }); implementedInterfaces.addAll(jApiClass.getInterfaces()); if (abstractMethods.size() > 0) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.METHOD_ABSTRACT_ADDED_IN_SUPERCLASS); } abstractMethods.clear(); for (JApiImplementedInterface jApiImplementedInterface : implementedInterfaces) { JApiClass interfaceClass = getJApiClass(jApiImplementedInterface, classMap); for (JApiMethod interfaceMethod : interfaceClass.getMethods()) { boolean isImplemented = false; for (JApiMethod implementedMethod : implementedMethods) { if (areMatching(interfaceMethod, implementedMethod)) { isImplemented = true; break; } } if (!isImplemented) { if (interfaceMethod.getChangeStatus() == JApiChangeStatus.NEW || jApiImplementedInterface.getChangeStatus() == JApiChangeStatus.NEW) { if (interfaceMethod.getAbstractModifier().getNewModifier().isPresent()) { AbstractModifier abstractModifier = interfaceMethod.getAbstractModifier().getNewModifier().get(); if (abstractModifier == AbstractModifier.ABSTRACT) { abstractMethods.add(interfaceMethod); } else { defaultMethods.add(interfaceMethod); } } } } } } final List<JApiMethod> abstractMethodsWithDefaultInInterface = new ArrayList<>(); for (JApiMethod abstractMethod : abstractMethods) { for (JApiImplementedInterface implementedInterface : implementedInterfaces) { final JApiClass interfaceClass = getJApiClass(implementedInterface, classMap); for (JApiMethod defaultMethodCandidate : interfaceClass.getMethods()) { if (!isAbstract(defaultMethodCandidate) && areMatching(abstractMethod, defaultMethodCandidate)) { // we have a default implementation for this method // double-check that we extend interface that the method comes from for (JApiImplementedInterface extendedInterface : interfaceClass.getInterfaces()) { JApiClass extendedInterfaceClass = getJApiClass(extendedInterface, classMap); if (abstractMethod.getjApiClass().equals(extendedInterfaceClass)) { abstractMethodsWithDefaultInInterface.add(abstractMethod); } } } } } } abstractMethods.removeAll(abstractMethodsWithDefaultInInterface); if (!abstractMethods.isEmpty()) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.METHOD_ABSTRACT_ADDED_IN_IMPLEMENTED_INTERFACE); } if (!defaultMethods.isEmpty()) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.METHOD_DEFAULT_ADDED_IN_IMPLEMENTED_INTERFACE); } } } private static boolean areMatching(JApiMethod left, JApiMethod right) { return left.getName().equals(right.getName()) && left.hasSameSignature(right); } private JApiClass getJApiClass(JApiImplementedInterface implementedInterface, Map<String, JApiClass> classMap) { String fullyQualifiedName = implementedInterface.getFullyQualifiedName(); JApiClass interfaceClass = classMap.get(fullyQualifiedName); if (interfaceClass == null) { interfaceClass = loadClass(fullyQualifiedName, EnumSet.allOf(Classpath.class)); } return interfaceClass; } private void checkIfClassNowCheckedException(JApiClass jApiClass) { JApiSuperclass jApiClassSuperclass = jApiClass.getSuperclass(); if (jApiClassSuperclass.getChangeStatus() == JApiChangeStatus.MODIFIED) { if (jApiClassSuperclass.getNewSuperclassName().isPresent()) { String fqn = jApiClassSuperclass.getNewSuperclassName().get(); if ("java.lang.Exception".equals(fqn)) { addCompatibilityChange(jApiClass, JApiCompatibilityChange.CLASS_NOW_CHECKED_EXCEPTION); } } } } private void addCompatibilityChange(JApiCompatibility binaryCompatibility, JApiCompatibilityChange compatibilityChange) { List<JApiCompatibilityChange> compatibilityChanges = binaryCompatibility.getCompatibilityChanges(); if (!compatibilityChanges.contains(compatibilityChange)) { compatibilityChanges.add(compatibilityChange); } } }
Use JApiMethod#hasSameSignature
japicmp/src/main/java/japicmp/compat/CompatibilityChanges.java
Use JApiMethod#hasSameSignature
<ide><path>apicmp/src/main/java/japicmp/compat/CompatibilityChanges.java <ide> @Override <ide> public Integer callback(JApiClass superclass, Map<String, JApiClass> classMap, JApiChangeStatus changeStatusOfSuperclass) { <ide> for (JApiMethod superMethod : superclass.getMethods()) { <del> if (superMethod.getName().equals(method.getName()) && superMethod.hasSameParameter(method) && superMethod.hasSameReturnType(method)) { <add> if (superMethod.getName().equals(method.getName()) && superMethod.hasSameSignature(method)) { <ide> return 1; <ide> } <ide> } <ide> @Override <ide> public Integer callback(JApiClass superclass, Map<String, JApiClass> classMap, JApiChangeStatus changeStatusOfSuperclass) { <ide> for (JApiMethod superMethod : superclass.getMethods()) { <del> if (superMethod.getName().equals(method.getName()) && superMethod.hasSameParameter(method) && superMethod.hasSameReturnType(method)) { <add> if (superMethod.getName().equals(method.getName()) && superMethod.hasSameSignature(method)) { <ide> if (superMethod.getAccessModifier().getNewModifier().isPresent() && method.getAccessModifier().getNewModifier().isPresent()) { <ide> if (superMethod.getAccessModifier().getNewModifier().get().getLevel() > method.getAccessModifier().getNewModifier().get().getLevel()) { <ide> return 1; <ide> private void checkIfMethodHasBeenPulledUp(JApiClass jApiClass, Map<String, JApiClass> classMap, final JApiMethod method, List<Integer> returnValues) { <ide> forAllImplementedInterfaces(jApiClass, classMap, returnValues, new ArrayList<>(), (implementedInterface, classMap1) -> { <ide> for (JApiMethod superMethod : implementedInterface.getMethods()) { <del> if (superMethod.getName().equals(method.getName()) && superMethod.hasSameParameter(method) && superMethod.hasSameReturnType(method)) { <add> if (superMethod.getName().equals(method.getName()) && superMethod.hasSameSignature(method)) { <ide> return 1; <ide> } <ide> }
Java
lgpl-2.1
bf5b863eec987bd898673056001ff118636ca7c5
0
xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.xpn.xwiki.tool.backup; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuilder; import org.apache.maven.repository.RepositorySystem; import org.hibernate.cfg.Environment; import org.xwiki.component.manager.ComponentLookupException; import org.xwiki.component.manager.ComponentManager; import org.xwiki.extension.Extension; import org.xwiki.extension.InstallException; import org.xwiki.extension.LocalExtension; import org.xwiki.extension.repository.InstalledExtensionRepository; import org.xwiki.extension.repository.LocalExtensionRepository; import org.xwiki.extension.repository.LocalExtensionRepositoryException; import org.xwiki.extension.repository.internal.local.DefaultLocalExtension; import org.xwiki.properties.ConverterManager; import org.xwiki.tool.utils.LogUtils; import com.xpn.xwiki.XWikiContext; /** * Maven 2 plugin to import aset of XWiki documents into an existing database. * * @version $Id$ * @goal import * @requiresDependencyResolution compile * @requiresProject */ public class ImportMojo extends AbstractMojo { public static final String MPKEYPREFIX = "xwiki.extension."; public static final String MPNAME_NAME = "name"; public static final String MPNAME_SUMMARY = "summary"; public static final String MPNAME_WEBSITE = "website"; public static final String MPNAME_FEATURES = "features"; /** * @parameter default-value = "xwiki" * @see com.xpn.xwiki.tool.backup.Importer#importDocuments(java.io.File, String, java.io.File) */ private String databaseName; /** * @parameter default-value = "${basedir}/src/main/packager/hibernate.cfg.xml" * @see com.xpn.xwiki.tool.backup.Importer#importDocuments(java.io.File, String, java.io.File) */ private File hibernateConfig; /** * @parameter * @see com.xpn.xwiki.tool.backup.Importer#importDocuments(java.io.File, String, java.io.File) */ private File sourceDirectory; /** * @parameter default-value = "${project.build.directory}/data/" * @see com.xpn.xwiki.tool.backup.Importer#importDocuments(java.io.File, String, java.io.File) */ private File xwikiDataDir; /** * The maven project. * * @parameter expression="${project}" * @required * @readonly */ private MavenProject project; /** * Project builder -- builds a model from a pom.xml. * * @component role="org.apache.maven.project.ProjectBuilder" * @required * @readonly */ protected ProjectBuilder projectBuilder; /** * Used to look up Artifacts in the remote repository. * * @component * @required */ protected RepositorySystem repositorySystem; @Override public void execute() throws MojoExecutionException, MojoFailureException { LogUtils.configureXWikiLogs(); Importer importer = new Importer(); System.setProperty("xwiki.data.dir", this.xwikiDataDir.getAbsolutePath()); // If the package mojo was executed before, it might have left a different database connection URL in the // environment, which apparently overrides the value in the configuration file System.clearProperty(Environment.URL); if (this.sourceDirectory != null) { try { importer.importDocuments(this.sourceDirectory, this.databaseName, this.hibernateConfig); } catch (Exception e) { throw new MojoExecutionException("Failed to import XWiki documents", e); } } else { try { importDependencies(importer, this.databaseName, this.hibernateConfig); } catch (Exception e) { throw new MojoExecutionException("Failed to import XAR dependencies", e); } } } /** * @param importer the importer * @param databaseName some database name (TODO: find out what this name is really) * @param hibernateConfig the Hibernate config fill containing the database definition (JDBC driver, username and * password, etc) * @throws Exception failed to import dependencies */ private void importDependencies(Importer importer, String databaseName, File hibernateConfig) throws Exception { XWikiContext xcontext = importer.createXWikiContext(databaseName, hibernateConfig); // Reverse artifact order to have dependencies first (despite the fact that it's a Set it's actually an ordered // LinkedHashSet behind the scene) List<Artifact> dependenciesFirstArtifacts = new ArrayList<Artifact>(this.project.getArtifacts()); Collections.reverse(dependenciesFirstArtifacts); for (Artifact artifact : dependenciesFirstArtifacts) { if (!artifact.isOptional()) { if ("xar".equals(artifact.getType())) { getLog().info(" ... Importing XAR file: " + artifact.getFile()); // Import XAR into database int nb = importer.importXAR(artifact.getFile(), null, xcontext); getLog().info(" ..... Imported " + nb + " documents"); // Install extension installExtension(artifact, xcontext); } } } // We MUST shutdown HSQLDB because otherwise the last transactions will not be flushed // to disk and will be lost. In practice this means the last Document imported has a // very high chance of not making it... // TODO: Find a way to implement this generically for all databases and inside // XWikiHibernateStore (cf http://jira.xwiki.org/jira/browse/XWIKI-471). importer.shutdownHSQLDB(xcontext); importer.disposeXWikiContext(xcontext); } private void installExtension(Artifact artifact, XWikiContext xcontext) throws ComponentLookupException, InstallException, LocalExtensionRepositoryException { ComponentManager componentManager = (ComponentManager) xcontext.get(ComponentManager.class.getName()); LocalExtensionRepository localExtensionRepository = componentManager.getInstance(LocalExtensionRepository.class); InstalledExtensionRepository installedExtensionRepository = componentManager.getInstance(InstalledExtensionRepository.class); ConverterManager converter = componentManager.getInstance(ConverterManager.class); Extension mavenExtension = converter.convert(Extension.class, this.project.getModel()); DefaultLocalExtension extension = new DefaultLocalExtension(null, mavenExtension); extension.setFile(artifact.getFile()); LocalExtension localExtension = localExtensionRepository.storeExtension(extension); installedExtensionRepository.installExtension(localExtension, "wiki:xwiki", true); } }
xwiki-platform-tools/xwiki-platform-tool-packager-plugin/src/main/java/com/xpn/xwiki/tool/backup/ImportMojo.java
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package com.xpn.xwiki.tool.backup; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Dependency; import org.apache.maven.model.Developer; import org.apache.maven.model.License; import org.apache.maven.model.Model; import org.apache.maven.model.building.ModelBuildingRequest; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.project.DefaultProjectBuildingRequest; import org.apache.maven.project.MavenProject; import org.apache.maven.project.ProjectBuilder; import org.apache.maven.project.ProjectBuildingException; import org.apache.maven.project.ProjectBuildingRequest; import org.apache.maven.project.ProjectBuildingResult; import org.apache.maven.repository.RepositorySystem; import org.xwiki.component.manager.ComponentLookupException; import org.xwiki.component.manager.ComponentManager; import org.xwiki.extension.DefaultExtensionAuthor; import org.xwiki.extension.DefaultExtensionDependency; import org.xwiki.extension.ExtensionId; import org.xwiki.extension.ExtensionLicense; import org.xwiki.extension.ExtensionLicenseManager; import org.xwiki.extension.InstallException; import org.xwiki.extension.LocalExtension; import org.xwiki.extension.repository.InstalledExtensionRepository; import org.xwiki.extension.repository.LocalExtensionRepository; import org.xwiki.extension.repository.LocalExtensionRepositoryException; import org.xwiki.extension.repository.internal.local.DefaultLocalExtension; import org.xwiki.extension.version.internal.DefaultVersionConstraint; import org.xwiki.properties.ConverterManager; import org.xwiki.tool.utils.LogUtils; import org.hibernate.cfg.Environment; import com.xpn.xwiki.XWikiContext; /** * Maven 2 plugin to import aset of XWiki documents into an existing database. * * @version $Id$ * @goal import * @requiresDependencyResolution compile * @requiresProject */ public class ImportMojo extends AbstractMojo { public static final String MPKEYPREFIX = "xwiki.extension."; public static final String MPNAME_NAME = "name"; public static final String MPNAME_SUMMARY = "summary"; public static final String MPNAME_WEBSITE = "website"; public static final String MPNAME_FEATURES = "features"; /** * @parameter default-value = "xwiki" * @see com.xpn.xwiki.tool.backup.Importer#importDocuments(java.io.File, String, java.io.File) */ private String databaseName; /** * @parameter default-value = "${basedir}/src/main/packager/hibernate.cfg.xml" * @see com.xpn.xwiki.tool.backup.Importer#importDocuments(java.io.File, String, java.io.File) */ private File hibernateConfig; /** * @parameter * @see com.xpn.xwiki.tool.backup.Importer#importDocuments(java.io.File, String, java.io.File) */ private File sourceDirectory; /** * @parameter default-value = "${project.build.directory}/data/" * @see com.xpn.xwiki.tool.backup.Importer#importDocuments(java.io.File, String, java.io.File) */ private File xwikiDataDir; /** * The maven project. * * @parameter expression="${project}" * @required * @readonly */ private MavenProject project; /** * Project builder -- builds a model from a pom.xml. * * @component role="org.apache.maven.project.ProjectBuilder" * @required * @readonly */ protected ProjectBuilder projectBuilder; /** * Used to look up Artifacts in the remote repository. * * @component * @required */ protected RepositorySystem repositorySystem; /** * The current Maven session being executed. * * @parameter default-value="${session}" * @readonly */ private MavenSession session; @Override public void execute() throws MojoExecutionException, MojoFailureException { LogUtils.configureXWikiLogs(); Importer importer = new Importer(); System.setProperty("xwiki.data.dir", this.xwikiDataDir.getAbsolutePath()); // If the package mojo was executed before, it might have left a different database connection URL in the // environment, which apparently overrides the value in the configuration file System.clearProperty(Environment.URL); if (this.sourceDirectory != null) { try { importer.importDocuments(this.sourceDirectory, this.databaseName, this.hibernateConfig); } catch (Exception e) { throw new MojoExecutionException("Failed to import XWiki documents", e); } } else { try { importDependencies(importer, this.databaseName, this.hibernateConfig); } catch (Exception e) { throw new MojoExecutionException("Failed to import XAR dependencies", e); } } } /** * @param importer the importer * @param databaseName some database name (TODO: find out what this name is really) * @param hibernateConfig the Hibernate config fill containing the database definition (JDBC driver, username and * password, etc) * @throws Exception failed to import dependencies */ private void importDependencies(Importer importer, String databaseName, File hibernateConfig) throws Exception { XWikiContext xcontext = importer.createXWikiContext(databaseName, hibernateConfig); // Reverse artifact order to have dependencies first (despite the fact that it's a Set it's actually an ordered // LinkedHashSet behind the scene) List<Artifact> dependenciesFirstArtifacts = new ArrayList<Artifact>(this.project.getArtifacts()); Collections.reverse(dependenciesFirstArtifacts); for (Artifact artifact : dependenciesFirstArtifacts) { if (!artifact.isOptional()) { if ("xar".equals(artifact.getType())) { getLog().info(" ... Importing XAR file: " + artifact.getFile()); // Import XAR into database int nb = importer.importXAR(artifact.getFile(), null, xcontext); getLog().info(" ..... Imported " + nb + " documents"); // Install extension installExtension(artifact, xcontext); } } } // We MUST shutdown HSQLDB because otherwise the last transactions will not be flushed // to disk and will be lost. In practice this means the last Document imported has a // very high chance of not making it... // TODO: Find a way to implement this generically for all databases and inside // XWikiHibernateStore (cf http://jira.xwiki.org/jira/browse/XWIKI-471). importer.shutdownHSQLDB(xcontext); importer.disposeXWikiContext(xcontext); } private void installExtension(Artifact artifact, XWikiContext xcontext) throws ComponentLookupException, InstallException, LocalExtensionRepositoryException, MojoExecutionException { ComponentManager componentManager = (ComponentManager) xcontext.get(ComponentManager.class.getName()); LocalExtensionRepository localExtensionRepository = componentManager.getInstance(LocalExtensionRepository.class); InstalledExtensionRepository installedExtensionRepository = componentManager.getInstance(InstalledExtensionRepository.class); DefaultLocalExtension extension = new DefaultLocalExtension(null, new ExtensionId(artifact.getGroupId() + ':' + artifact.getArtifactId(), artifact.getBaseVersion()), artifact.getType()); extension.setFile(artifact.getFile()); MavenProject project = getMavenProject(artifact); toExtension(extension, project.getModel(), componentManager); LocalExtension localExtension = localExtensionRepository.storeExtension(extension); installedExtensionRepository.installExtension(localExtension, "wiki:xwiki", true); } // Maven -> Extension // TODO: put all this, what's on core extension scanner and maven repository handler in a commons module private void toExtension(DefaultLocalExtension extension, Model model, ComponentManager componentManager) throws ComponentLookupException { extension.setName(getPropertyString(model, MPNAME_NAME, model.getName())); extension.setSummary(getPropertyString(model, MPNAME_SUMMARY, model.getDescription())); extension.setWebsite(getPropertyString(model, MPNAME_WEBSITE, model.getUrl())); // authors for (Developer developer : model.getDevelopers()) { URL authorURL = null; if (developer.getUrl() != null) { try { authorURL = new URL(developer.getUrl()); } catch (MalformedURLException e) { // TODO: log ? } } extension.addAuthor(new DefaultExtensionAuthor(StringUtils.defaultIfBlank(developer.getName(), developer.getId()), authorURL)); } // licenses if (!model.getLicenses().isEmpty()) { ExtensionLicenseManager licenseManager = componentManager.getInstance(ExtensionLicenseManager.class); for (License license : model.getLicenses()) { extension.addLicense(getExtensionLicense(license, licenseManager)); } } // features String featuresString = getProperty(model, MPNAME_FEATURES); if (StringUtils.isNotBlank(featuresString)) { featuresString = featuresString.replaceAll("[\r\n]", ""); ConverterManager converter = componentManager.getInstance(ConverterManager.class); extension.setFeatures(converter.<Collection<String>>convert(List.class, featuresString)); } // dependencies for (Dependency mavenDependency : model.getDependencies()) { if (!mavenDependency.isOptional() && (mavenDependency.getScope().equals("compile") || mavenDependency.getScope().equals("runtime"))) { extension.addDependency(new DefaultExtensionDependency(mavenDependency.getGroupId() + ':' + mavenDependency.getArtifactId(), new DefaultVersionConstraint(mavenDependency.getVersion()))); } } } private MavenProject getMavenProject(Artifact artifact) throws MojoExecutionException { try { ProjectBuildingRequest request = new DefaultProjectBuildingRequest(this.session.getProjectBuildingRequest()) // We don't want to execute any plugin here .setProcessPlugins(false) // It's not this plugin job to validate this pom.xml .setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL) // Use the repositories configured for the built project instead of the default Maven ones .setRemoteRepositories(this.session.getCurrentProject().getRemoteArtifactRepositories()); // Note: build() will automatically get the POM artifact corresponding to the passed artifact. ProjectBuildingResult result = this.projectBuilder.build(artifact, request); return result.getProject(); } catch (ProjectBuildingException e) { throw new MojoExecutionException(String.format("Failed to build project for [%s]", artifact), e); } } private String getProperty(Model model, String propertyName) { return model.getProperties().getProperty(MPKEYPREFIX + propertyName); } private String getPropertyString(Model model, String propertyName, String def) { return StringUtils.defaultString(getProperty(model, propertyName), def); } // TODO: download custom licenses content private ExtensionLicense getExtensionLicense(License license, ExtensionLicenseManager licenseManager) { if (license.getName() == null) { return new ExtensionLicense("noname", null); } return createLicenseByName(license.getName(), licenseManager); } private ExtensionLicense createLicenseByName(String name, ExtensionLicenseManager licenseManager) { ExtensionLicense extensionLicense = licenseManager.getLicense(name); return extensionLicense != null ? extensionLicense : new ExtensionLicense(name, null); } }
[misc] Improve reusability
xwiki-platform-tools/xwiki-platform-tool-packager-plugin/src/main/java/com/xpn/xwiki/tool/backup/ImportMojo.java
[misc] Improve reusability
<ide><path>wiki-platform-tools/xwiki-platform-tool-packager-plugin/src/main/java/com/xpn/xwiki/tool/backup/ImportMojo.java <ide> package com.xpn.xwiki.tool.backup; <ide> <ide> import java.io.File; <del>import java.net.MalformedURLException; <del>import java.net.URL; <ide> import java.util.ArrayList; <del>import java.util.Collection; <ide> import java.util.Collections; <ide> import java.util.List; <ide> <del>import org.apache.commons.lang3.StringUtils; <ide> import org.apache.maven.artifact.Artifact; <del>import org.apache.maven.execution.MavenSession; <del>import org.apache.maven.model.Dependency; <del>import org.apache.maven.model.Developer; <del>import org.apache.maven.model.License; <del>import org.apache.maven.model.Model; <del>import org.apache.maven.model.building.ModelBuildingRequest; <ide> import org.apache.maven.plugin.AbstractMojo; <ide> import org.apache.maven.plugin.MojoExecutionException; <ide> import org.apache.maven.plugin.MojoFailureException; <del>import org.apache.maven.project.DefaultProjectBuildingRequest; <ide> import org.apache.maven.project.MavenProject; <ide> import org.apache.maven.project.ProjectBuilder; <del>import org.apache.maven.project.ProjectBuildingException; <del>import org.apache.maven.project.ProjectBuildingRequest; <del>import org.apache.maven.project.ProjectBuildingResult; <ide> import org.apache.maven.repository.RepositorySystem; <add>import org.hibernate.cfg.Environment; <ide> import org.xwiki.component.manager.ComponentLookupException; <ide> import org.xwiki.component.manager.ComponentManager; <del>import org.xwiki.extension.DefaultExtensionAuthor; <del>import org.xwiki.extension.DefaultExtensionDependency; <del>import org.xwiki.extension.ExtensionId; <del>import org.xwiki.extension.ExtensionLicense; <del>import org.xwiki.extension.ExtensionLicenseManager; <add>import org.xwiki.extension.Extension; <ide> import org.xwiki.extension.InstallException; <ide> import org.xwiki.extension.LocalExtension; <ide> import org.xwiki.extension.repository.InstalledExtensionRepository; <ide> import org.xwiki.extension.repository.LocalExtensionRepository; <ide> import org.xwiki.extension.repository.LocalExtensionRepositoryException; <ide> import org.xwiki.extension.repository.internal.local.DefaultLocalExtension; <del>import org.xwiki.extension.version.internal.DefaultVersionConstraint; <ide> import org.xwiki.properties.ConverterManager; <ide> import org.xwiki.tool.utils.LogUtils; <del>import org.hibernate.cfg.Environment; <ide> <ide> import com.xpn.xwiki.XWikiContext; <ide> <ide> * @required <ide> */ <ide> protected RepositorySystem repositorySystem; <del> <del> /** <del> * The current Maven session being executed. <del> * <del> * @parameter default-value="${session}" <del> * @readonly <del> */ <del> private MavenSession session; <ide> <ide> @Override <ide> public void execute() throws MojoExecutionException, MojoFailureException <ide> } <ide> <ide> private void installExtension(Artifact artifact, XWikiContext xcontext) throws ComponentLookupException, <del> InstallException, LocalExtensionRepositoryException, MojoExecutionException <add> InstallException, LocalExtensionRepositoryException <ide> { <ide> ComponentManager componentManager = (ComponentManager) xcontext.get(ComponentManager.class.getName()); <ide> <ide> InstalledExtensionRepository installedExtensionRepository = <ide> componentManager.getInstance(InstalledExtensionRepository.class); <ide> <del> DefaultLocalExtension extension = <del> new DefaultLocalExtension(null, new ExtensionId(artifact.getGroupId() + ':' + artifact.getArtifactId(), <del> artifact.getBaseVersion()), artifact.getType()); <add> ConverterManager converter = componentManager.getInstance(ConverterManager.class); <add> Extension mavenExtension = converter.convert(Extension.class, this.project.getModel()); <add> <add> DefaultLocalExtension extension = new DefaultLocalExtension(null, mavenExtension); <ide> <ide> extension.setFile(artifact.getFile()); <del> <del> MavenProject project = getMavenProject(artifact); <del> <del> toExtension(extension, project.getModel(), componentManager); <ide> <ide> LocalExtension localExtension = localExtensionRepository.storeExtension(extension); <ide> installedExtensionRepository.installExtension(localExtension, "wiki:xwiki", true); <ide> } <del> <del> // Maven -> Extension <del> // TODO: put all this, what's on core extension scanner and maven repository handler in a commons module <del> <del> private void toExtension(DefaultLocalExtension extension, Model model, ComponentManager componentManager) <del> throws ComponentLookupException <del> { <del> extension.setName(getPropertyString(model, MPNAME_NAME, model.getName())); <del> extension.setSummary(getPropertyString(model, MPNAME_SUMMARY, model.getDescription())); <del> extension.setWebsite(getPropertyString(model, MPNAME_WEBSITE, model.getUrl())); <del> <del> // authors <del> for (Developer developer : model.getDevelopers()) { <del> URL authorURL = null; <del> if (developer.getUrl() != null) { <del> try { <del> authorURL = new URL(developer.getUrl()); <del> } catch (MalformedURLException e) { <del> // TODO: log ? <del> } <del> } <del> <del> extension.addAuthor(new DefaultExtensionAuthor(StringUtils.defaultIfBlank(developer.getName(), <del> developer.getId()), authorURL)); <del> } <del> <del> // licenses <del> if (!model.getLicenses().isEmpty()) { <del> ExtensionLicenseManager licenseManager = componentManager.getInstance(ExtensionLicenseManager.class); <del> for (License license : model.getLicenses()) { <del> extension.addLicense(getExtensionLicense(license, licenseManager)); <del> } <del> } <del> <del> // features <del> String featuresString = getProperty(model, MPNAME_FEATURES); <del> if (StringUtils.isNotBlank(featuresString)) { <del> featuresString = featuresString.replaceAll("[\r\n]", ""); <del> ConverterManager converter = componentManager.getInstance(ConverterManager.class); <del> extension.setFeatures(converter.<Collection<String>>convert(List.class, featuresString)); <del> } <del> <del> // dependencies <del> for (Dependency mavenDependency : model.getDependencies()) { <del> if (!mavenDependency.isOptional() <del> && (mavenDependency.getScope().equals("compile") || mavenDependency.getScope().equals("runtime"))) { <del> extension.addDependency(new DefaultExtensionDependency(mavenDependency.getGroupId() + ':' <del> + mavenDependency.getArtifactId(), new DefaultVersionConstraint(mavenDependency.getVersion()))); <del> } <del> } <del> } <del> <del> private MavenProject getMavenProject(Artifact artifact) throws MojoExecutionException <del> { <del> try { <del> ProjectBuildingRequest request = <del> new DefaultProjectBuildingRequest(this.session.getProjectBuildingRequest()) <del> // We don't want to execute any plugin here <del> .setProcessPlugins(false) <del> // It's not this plugin job to validate this pom.xml <del> .setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL) <del> // Use the repositories configured for the built project instead of the default Maven ones <del> .setRemoteRepositories(this.session.getCurrentProject().getRemoteArtifactRepositories()); <del> // Note: build() will automatically get the POM artifact corresponding to the passed artifact. <del> ProjectBuildingResult result = this.projectBuilder.build(artifact, request); <del> return result.getProject(); <del> } catch (ProjectBuildingException e) { <del> throw new MojoExecutionException(String.format("Failed to build project for [%s]", artifact), e); <del> } <del> } <del> <del> private String getProperty(Model model, String propertyName) <del> { <del> return model.getProperties().getProperty(MPKEYPREFIX + propertyName); <del> } <del> <del> private String getPropertyString(Model model, String propertyName, String def) <del> { <del> return StringUtils.defaultString(getProperty(model, propertyName), def); <del> } <del> <del> // TODO: download custom licenses content <del> private ExtensionLicense getExtensionLicense(License license, ExtensionLicenseManager licenseManager) <del> { <del> if (license.getName() == null) { <del> return new ExtensionLicense("noname", null); <del> } <del> <del> return createLicenseByName(license.getName(), licenseManager); <del> } <del> <del> private ExtensionLicense createLicenseByName(String name, ExtensionLicenseManager licenseManager) <del> { <del> ExtensionLicense extensionLicense = licenseManager.getLicense(name); <del> <del> return extensionLicense != null ? extensionLicense : new ExtensionLicense(name, null); <del> } <ide> }
Java
apache-2.0
44115e2708fa48bbf56c98b8a442324af879c9e4
0
google/mug,google/mug
package com.google.mu.util.stream; import static java.util.Objects.requireNonNull; import java.util.Collections; import java.util.Set; import java.util.StringJoiner; import java.util.function.BiConsumer; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collector; import java.util.stream.Collectors; /** * An joiner of strings. * * <p>When used to join a pair of objects (for example in a BiStream), it can be used for BiFunction: * <pre>{@code * BiStream.zip(userIds, names) * .mapToObj(Joiner.on('=')::join) // (id, name) -> id + "=" + name * ....; * }</pre> * * <p>Alternatively, it can be used as a Collector. For example, * {@code names.collect(Joiner.on(','))} is equivalent to {@code names.collect(Collectors.joining(","))}. * * Except that JDK {@code joining()} requires the inputs to be strings; while Joiner can join any input, * e.g. numbers. * * <p>You can also chain {@link #between} to further enclose the joined result between a pair of strings. * The following code joins a list of ids and their corresponding names in the format of * {@code "[id1:name1, id2:name2, id3:name3, ...]"}: * <pre>{@code * BiStream.zip(userIds, names) * .mapToObj(Joiner.on('=')::join) * .collect(Joiner.on(", ").between('[', ']')); * }</pre> * Which reads clearer than using JDK {@link Collectors#joining}: * <pre>{@code * BiStream.zip(userIds, names) * .mapToObj(id, name) -> id + ":" + name) * .collect(Collectors.joining(", ", "[", "]")); * }</pre> * * <p>Or, you can format the {@code (id, name)} pairs in the format of * {@code "[(id1, name1), (id2, name2). ...]"}: * <pre>{@code * BiStream.zip(userIds, names) * .mapToObj(Joiner.on(", ").between('(', ')')::join) * .collect(Joiner.on(", ").between('[', ']')); * }</pre> * * <p>Unlike {@link com.google.common.base.Joiner}, nulls don't cause NullPointerException, instead, * they are stringified using {@link String#valueOf}. * * @since 5.6 */ public abstract class Joiner implements Collector<Object, StringJoiner, String> { /** Joining the inputs on the {@code delimiter} character */ public static Joiner on(char delimiter) { return on(Character.toString(delimiter)); } /** Joining the inputs on the {@code delimiter} string */ public static Joiner on(String delimiter) { requireNonNull(delimiter); return new Joiner() { @Override public Supplier<StringJoiner> supplier() { return () -> new StringJoiner(delimiter); } @Override public String join(Object l, Object r) { return l + delimiter + r; } }; } /** Joins {@code l} and {@code r} together. */ public abstract String join(Object l, Object r); /** Returns an instance that wraps the join result between {@code before} and {@code after}. */ public final Joiner between(char before, char after) { return between(Character.toString(before), Character.toString(after)); } /** Returns an instance that wraps the join result between {@code before} and {@code after}. */ public final Joiner between(String before, String after) { requireNonNull(before); requireNonNull(after); Joiner base = this; return new Joiner() { @Override public Supplier<StringJoiner> supplier() { return base.supplier(); } @Override public Function<StringJoiner, String> finisher() { return base.finisher().andThen(r -> before + r + after); } @Override public String join(Object l, Object r) { return before + base.join(l, r) + after; } }; } @Override public BiConsumer<StringJoiner, Object> accumulator() { return (joiner, obj) -> joiner.add(String.valueOf(obj)); } @Override public BinaryOperator<StringJoiner> combiner() { return StringJoiner::merge; } @Override public Function<StringJoiner, String> finisher() { return StringJoiner::toString; } @Override public Set<Characteristics> characteristics() { return Collections.emptySet(); } Joiner() {} }
mug/src/main/java/com/google/mu/util/stream/Joiner.java
package com.google.mu.util.stream; import static java.util.Objects.requireNonNull; import java.util.Collections; import java.util.Set; import java.util.StringJoiner; import java.util.function.BiConsumer; import java.util.function.BinaryOperator; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collector; import java.util.stream.Collectors; /** * An joiner of strings. * * <p>When used to join a pair of objects (for example in a BiStream), it can be used for BiFunction: * <pre>{@code * BiStream.zip(userIds, names) * .mapToObj(Joiner.on('=')::join) // (id, name) -> id + "=" + name * ....; * }</pre> * * <p>Alternatively, it can be used as a Collector. For example, * {@code names.collect(Joiner.on(','))} is equivalent to {@code names.collect(Collectors.joining(","))}. * * Except that JDK {@code joining()} requires the inputs to be strings; while Joiner can join any input, * e.g. numbers. * * <p>You can also chain {@link #between} to further enclose the joined result between a pair of strings. * The following code joins a list of ids and their corresponding names in the format of * {@code "[id1:name1, id2:name2, id3:name3, ...]"}: * <pre>{@code * BiStream.zip(userIds, names) * .mapToObj(Joiner.on('=')::join) * .collect(Joiner.on(", ").between('[', ']')); * }</pre> * Which reads clearer than using JDK {@link Collectors#joining}: * <pre>{@code * BiStream.zip(userIds, names) * .mapToObj(id, name) -> id + ":" + name) * .collect(Collectors.joining(", ", "[", "]")); * }</pre> * * <p>Or, you can format the {@code (id, name)} pairs in the format of * {@code "[(id1, name1), (id2, name2). ...]": * <pre>{@code * BiStream.zip(userIds, names) * .mapToObj(Joiner.on(", ").between('(', ')')::join) * .collect(Joiner.on(", ").between('[', ']')); * }</pre> * * <p>Unlike {@link com.google.common.base.Joiner}, nulls don't cause NullPointerException, instead, * they are stringified using {@link String#valueOf}. * * @since 5.6 */ public abstract class Joiner implements Collector<Object, StringJoiner, String> { /** Joining the inputs on the {@code delimiter} character */ public static Joiner on(char delimiter) { return on(Character.toString(delimiter)); } /** Joining the inputs on the {@code delimiter} string */ public static Joiner on(String delimiter) { requireNonNull(delimiter); return new Joiner() { @Override public Supplier<StringJoiner> supplier() { return () -> new StringJoiner(delimiter); } @Override public String join(Object l, Object r) { return l + delimiter + r; } }; } /** Joins {@code l} and {@code r} together. */ public abstract String join(Object l, Object r); /** Returns an instance that wraps the join result between {@code before} and {@code after}. */ public final Joiner between(char before, char after) { return between(Character.toString(before), Character.toString(after)); } /** Returns an instance that wraps the join result between {@code before} and {@code after}. */ public final Joiner between(String before, String after) { requireNonNull(before); requireNonNull(after); Joiner base = this; return new Joiner() { @Override public Supplier<StringJoiner> supplier() { return base.supplier(); } @Override public Function<StringJoiner, String> finisher() { return base.finisher().andThen(r -> before + r + after); } @Override public String join(Object l, Object r) { return before + base.join(l, r) + after; } }; } @Override public BiConsumer<StringJoiner, Object> accumulator() { return (joiner, obj) -> joiner.add(String.valueOf(obj)); } @Override public BinaryOperator<StringJoiner> combiner() { return StringJoiner::merge; } @Override public Function<StringJoiner, String> finisher() { return StringJoiner::toString; } @Override public Set<Characteristics> characteristics() { return Collections.emptySet(); } Joiner() {} }
fix Joiner javadoc:
mug/src/main/java/com/google/mu/util/stream/Joiner.java
fix Joiner javadoc:
<ide><path>ug/src/main/java/com/google/mu/util/stream/Joiner.java <ide> * }</pre> <ide> * <ide> * <p>Or, you can format the {@code (id, name)} pairs in the format of <del> * {@code "[(id1, name1), (id2, name2). ...]": <add> * {@code "[(id1, name1), (id2, name2). ...]"}: <ide> * <pre>{@code <ide> * BiStream.zip(userIds, names) <ide> * .mapToObj(Joiner.on(", ").between('(', ')')::join)
Java
apache-2.0
7b5cab4ca83b6fdace1348e34e275d55c724a339
0
isomorphic-software/isc-maven-plugin
package com.isomorphic.maven.mojo.reify; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.OutputStream; import java.io.StringWriter; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.settings.Proxy; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.hash.Hashing; import com.google.common.io.Files; import com.isomorphic.maven.mojo.AbstractBaseMojo; import com.isomorphic.maven.util.ArchiveUtils; import com.isomorphic.maven.util.HttpRequestManager; import com.isomorphic.maven.util.LoggingCountingOutputStream; import freemarker.cache.ClassTemplateLoader; import freemarker.template.Configuration; import freemarker.template.TemplateExceptionHandler; /** * Provides for single-step download and extraction of assets hosted on the Reify platform. * While there is nothing to prevent a user from modifying the imported resources, changes * should almost always be made using Reify and then re-imported. If necessary, use the API * (e.g., RPCManager.createScreen, Canvas.getByLocalId) to modify imported screen definitions * at runtime. Imported MockDataSources can simply be replaced using e.g., SQLDataSources * having the same ID in another directory - there is no reason to modify the contents of the * 'mock' subdirectory. * <p> * To encourage recommended usage, the reify-import goal takes steps to detect local changes * and fail when any are found. Refer to the {@link #skipOverwriteProtection} * parameter for details. */ // Set requiresProject: false so that we can run the whole thing from an Ant project w/ no POM @Mojo(name="reify-import", requiresProject=false) public class ImportMojo extends AbstractBaseMojo { private static final Logger LOGGER = LoggerFactory.getLogger(ImportMojo.class); /** * The id of a <a href="http://maven.apache.org/settings.html#Servers">server * configuration</a> containing authentication credentials for the * reify.com website, used to download exported projects. * * @since 1.4.0 */ @Parameter(property = "serverId", defaultValue = "smartclient-developer") protected String serverId; /** * The directory to which the archive is downloaded and unpacked. Note that this is * not the final destination of exported assets. For that, see {@link ImportMojo#webappDir}. * * @since 1.4.0 */ @Parameter(property = "workdir", defaultValue = "${project.build.directory}/reify") private File workdir; /** * The directory containing web application sources. * * @since 1.4.0 */ @Parameter(property = "webappDir", defaultValue = "${project.basedir}/src/main/webapp") private File webappDir; /** * The directory to which exported DataSources should ultimately reside, relative to {@link ImportMojo#webappDir}. * Note that this will need to conform to the webapp's server.properties <code>project.datasources</code> configuration. * Also note that MockDataSources will be imported to a 'mock' subdirectory. e.g., WEB-INF/ds/mock. * * @since 1.4.0 */ @Parameter(property = "datasourcesDir", defaultValue = "WEB-INF/ds") private String datasourcesDir; /** * The directory to which exported screens should ultimately reside, relative to {@link ImportMojo#webappDir}. * Note that this will need to conform to the webapp's server.properties <code>project.ui</code> configuration. * * @since 1.4.0 */ @Parameter(property = "uiDir", defaultValue = "WEB-INF/ui") private String uiDir; /** * The directory to which the exported project file should ultimately reside, relative to {@link ImportMojo#webappDir}. * Note that this will need to conform to the webapp's server.properties <code>project.project</code> configuration. * * @since 1.4.0 */ @Parameter(property="projectFileDir", defaultValue = "WEB-INF/ui") private String projectFileDir; /** * The name of the project as its known by the reify.com environment. */ @Parameter(property="projectName", defaultValue = "${project.artifactId}", required=true) private String projectName; private String projectFileName; private String zipFileName; /** * When a project is imported, its screen and datasource assets are marked with a checksum * representing the contents of each file. Subsequent imports are preceded by a check to * make sure each of these checksums still match the file's content. In the event that * any do not, the import fails by default. * <p> * To override this behavior, you may set this parameter value to <code>true</code>, in * which case the file will simply be overwritten. Use this feature at your own risk. */ @Parameter(property="skipOverwriteProtection", defaultValue = "false") private boolean skipOverwriteProtection; private UsernamePasswordCredentials credentials; private Configuration freemarkerConfig; private Proxy proxy; private HttpHost host; private HttpRequestManager httpWorker; public ImportMojo() { // undocumented parameter to allow for testing against QA environment String hostname = System.getProperty("reify-hostname"); if (hostname == null) { hostname = "app.reify.com"; } host = new HttpHost(hostname, -1, "https"); // we'll use a freemarker template to construct the request for project metadata ClassTemplateLoader ctl = new ClassTemplateLoader(getClass(), ""); freemarkerConfig = new Configuration(Configuration.VERSION_2_3_28); freemarkerConfig.setTemplateLoader(ctl); freemarkerConfig.setDefaultEncoding("UTF-8"); freemarkerConfig.setLogTemplateExceptions(false); freemarkerConfig.setWrapUncheckedExceptions(true); freemarkerConfig.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); } /** * After ensuring there are no local modifications (unless otherwise configured), downloads * and installs Reify project contents to the local project environment. */ @Override public void execute() throws MojoExecutionException, MojoFailureException { try { // derive filenames from project name zipFileName = projectName + ".proj.zip"; projectFileName = projectName + ".proj.xml"; // check to make sure there are no local changes, unless configured otherwise if (! skipOverwriteProtection) { checkForLocalModifications(); } // allow explicit configuration from ImportTask (for Ant builds) if (credentials == null) { credentials = getCredentials(serverId); } if (credentials == null) { throw new MojoExecutionException("Reify credentials have not been configured. Check Maven settings for the '" + serverId + "' server."); } // allow for manual construction of the Proxy (again, for Ant builds) httpWorker = new HttpRequestManager(host, credentials, settings != null ? settings.getActiveProxy() : proxy); httpWorker.login(); // get fresh project metadata and archive from the server Document project = downloadProjectDocument(); File archive = downloadProjectArchive(project); LOGGER.info("Importing Reify project assets from download at '{}'...", archive.getCanonicalPath()); File unpacked = new File(workdir, projectName); ArchiveUtils.unzip(archive, unpacked); // update the new project file with checksums of file content for overwrite protection on future imports writeProjectFile(project, unpacked); // and copy the result to application source FileUtils.copyDirectory(unpacked, webappDir); } catch (MojoExecutionException e) { throw e; } catch (Exception e) { throw new MojoExecutionException("Import Error", e); } finally { try { httpWorker.logout(); } catch (Exception ignore) {} } } /** * Checks for local modifications, as documented at {@link #skipOverwriteProtection}}, * and fails when any local changes are detected. * <p> * Note that files are expected in the configured locations - screens in {@link #uiDir} * and datasources in {@link #datasourcesDir} (or the {@link #datasourcesDir}/mock * subdirectory). * * @throws MojoExecutionException when any local changes are detected * @throws Exception on any other error */ private void checkForLocalModifications() throws MojoExecutionException, Exception { File projectFile = new File(webappDir, projectFileDir + "/" + projectFileName); if (! projectFile.exists()) { LOGGER.info("Project file does not exist at '{}', but will be created during import.", projectFile.getCanonicalPath()); return; } SAXReader reader = new SAXReader(); Document document = reader.read(projectFile); String msg = "File '%s' appears to have been modified since the last import. Aborting to provide an opprtunity to investigate. \n" + "You can either revert your changes, delete the file, or remove its checksum from the project file to continue. \n" + "You can also disable the check for this and all other files using the skipOverwriteProtection parameter."; List<Node> screens = getScreenNodes(document); for (Node screen : screens) { String expected = screen.valueOf("checksum"); if (expected.isEmpty()) { continue; } File file = getScreen(screen, webappDir); if (! file.exists()) { continue; } String actual = Files.asByteSource(file).hash(Hashing.sha256()).toString(); if (!actual.equals(expected)) { LOGGER.debug("Checksum mismatch - Expected: '{}' Actual: '{}'", expected, actual); throw new MojoExecutionException(String.format(msg, file.getCanonicalPath())); } } List<Node> datasources = getDataSourceNodes(document); for (Node ds : datasources) { String expected = ds.valueOf("checksum"); if (expected.isEmpty()) { continue; } File file = getDataSource(ds, webappDir); if (! file.exists()) { continue; } String actual = Files.asByteSource(file).hash(Hashing.sha256()).toString(); if (!actual.equals(expected)) { LOGGER.debug("Checksum mismatch - Expected: '{}' Actual: '{}'", expected, actual); throw new MojoExecutionException(String.format(msg, file.getCanonicalPath())); } } } /** * Requests the named project's metadata from the reify server. * * @return Document containing the result. * @throws Exception when any error occurs */ private Document downloadProjectDocument() throws Exception { LOGGER.info("Contacting server for Reify project metadata..."); HttpGet request = new HttpGet("/isomorphic/RESTHandler/hostedProjects?fileName=" + URLEncoder.encode(projectName) + "&isc_dataFormat=xml"); HttpResponse response = httpWorker.execute(request); String body = null; try { body = EntityUtils.toString(response.getEntity()); Document metadata = DocumentHelper.parseText(body); Node fileContents = metadata.selectSingleNode("//fileContents"); String project = fileContents.getText(); return DocumentHelper.parseText(project); } catch (Exception e) { LOGGER.error("Response from server:" + System.getProperty("line.separator") + body); throw new Exception(String.format("Unexpected response to request for project file. Check that user '%s' is able to access the project named '%s'", credentials.getUserName(), projectName)); } } /** * Requests the named project's export archive, including all screens and all datasources, * downloads it, and saves it to {@link #workdir}. * * @param project metadata used to provide the names of requested assets * @return zip file containing the export result * @throws Exception when any error occurs */ private File downloadProjectArchive(Document project) throws Exception { Map<String, Object> context = new HashMap<String, Object>(); context.put("datasourcesDir", datasourcesDir); context.put("uiDir", uiDir); context.put("projectFileDir", projectFileDir); context.put("projectFileName", projectFileName); context.put("zipFileName", zipFileName); context.put("screens", getScreenNames(project)); context.put("datasources", getDataSourceNames(project)); StringWriter writer = new StringWriter(); freemarkerConfig.getTemplate("transaction.ftl").process(context, writer); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("_transaction", writer.toString())); HttpPost request = new HttpPost("/isomorphic/IDACall?isc_rpc=1"); request.setEntity(new UrlEncodedFormEntity(params)); LOGGER.info("Downloading '{}' project export from '{}'...", projectName, host.getHostName()); HttpResponse response = httpWorker.execute(request); HttpEntity entity = response.getEntity(); if (! "application/zip".equals(entity.getContentType().getValue())) { throw new MojoExecutionException("Response does not contain zip file contents:\n" + EntityUtils.toString(entity)); } FileUtils.forceMkdir(workdir); FileUtils.cleanDirectory(workdir); File zip = new File(workdir + "/" + zipFileName); OutputStream outputStream = null; try { outputStream = new LoggingCountingOutputStream(new FileOutputStream(zip), entity.getContentLength()); entity.writeTo(outputStream); } catch (Exception e) { throw new MojoExecutionException("Error writing file to '" + zip.getAbsolutePath() + "'", e); } finally { IOUtils.closeQuietly(outputStream); } return zip; } /** * Calculates checksums for every file in the downloaded archive, writes them to * the given project file, and stores the result on disk at a folder named for * {@link #projectFileDir}, relative to the given parent. * * @param project metadata used to provide the names of requested assets * @param parent the parent directory * @throws Exception whenany error occurs */ private void writeProjectFile(Document project, File parent) throws Exception { for (Node screen : getScreenNodes(project)) { File file = getScreen(screen, parent); String checksum = Files.asByteSource(file).hash(Hashing.sha256()).toString(); Element element = ((Element) screen).addElement("checksum"); element.setText(checksum); } for (Node datasource : getDataSourceNodes(project)) { File file = getDataSource(datasource, parent); String checksum = Files.asByteSource(file).hash(Hashing.sha256()).toString(); Element element = ((Element) datasource).addElement("checksum"); element.setText(checksum); } // pretty print the file with changes File projectFile = FileUtils.getFile(parent, projectFileDir, projectFileName); OutputFormat purdy = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter(projectFile), purdy); writer.write(project); writer.flush(); writer.close(); } /* * Convenience methods for returning various representations of screens from xml document */ private List<Node> getScreenNodes(Document project) { return project.selectNodes("/Project/screens/root/children/TreeNode"); } private List<String> getScreenNames(Document project) { List<Node> nodes = getScreenNodes(project); List<String> names = new ArrayList<String>(); for (Node node : nodes) { names.add(getScreenName(node)); } return names; } private String getScreenName(Node screen) { return screen.valueOf("fileName"); } private File getScreen(Node metadata, File parent) { return FileUtils.getFile(parent, uiDir, getScreenName(metadata) + ".ui.xml"); } /* * Convenience methods for returning various representations of datasources from xml doc */ private List<Node> getDataSourceNodes(Document project) { return project.selectNodes("/Project/datasources/Record"); } private List<String> getDataSourceNames(Document project) { List<Node> nodes = getDataSourceNodes(project); List<String> names = new ArrayList<String>(); for (Node node : nodes) { names.add(getDataSourceName(node)); } return names; } private String getDataSourceName(Node ds) { return ds.valueOf("dsName"); } private File getDataSource(Node metadata, File parent) { String name = getDataSourceName(metadata); // Check 'mock' subdirectory first, fallback to datasourcesDir if not found. File file = FileUtils.getFile(parent, datasourcesDir, "mock", name + ".ds.xml"); if (! file.exists()) { file = FileUtils.getFile(parent, datasourcesDir, name + ".ds.xml"); } return file; } /* * Setters to allow execution from an Ant build (ImportTask) */ protected void setWorkdir(File workdir) { this.workdir = workdir; } protected void setWebappDir(File webappDir) { this.webappDir = webappDir; } protected void setDatasourcesDir(String datasourcesDir) { this.datasourcesDir = datasourcesDir; } protected void setUiDir(String uiDir) { this.uiDir = uiDir; } protected void setProjectFileDir(String projectFileDir) { this.projectFileDir = projectFileDir; } protected void setProjectName(String projectName) { this.projectName = projectName; } protected void setProjectFileName(String projectFileName) { this.projectFileName = projectFileName; } protected void setZipFileName(String zipFileName) { this.zipFileName = zipFileName; } protected void setCredentials(UsernamePasswordCredentials credentials) { this.credentials = credentials; } protected void setProxy(Proxy proxy) { this.proxy = proxy; } }
src/main/java/com/isomorphic/maven/mojo/reify/ImportMojo.java
package com.isomorphic.maven.mojo.reify; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.OutputStream; import java.io.StringWriter; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.settings.Proxy; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.Node; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.hash.Hashing; import com.google.common.io.Files; import com.isomorphic.maven.mojo.AbstractBaseMojo; import com.isomorphic.maven.util.ArchiveUtils; import com.isomorphic.maven.util.HttpRequestManager; import com.isomorphic.maven.util.LoggingCountingOutputStream; import freemarker.cache.ClassTemplateLoader; import freemarker.template.Configuration; import freemarker.template.TemplateExceptionHandler; /** * Provides for single-step download and extraction of assets hosted on the Reify platform. * While there is nothing to prevent a user from modifying the imported resources, changes * should almost always be made using Reify and then re-imported. * <p> * If necessary, use the API (e.g., RPCManager.createScreen, Canvas.getByLocalId) to modify * imported screen definitions at runtime. * <p> * Imported MockDataSources can be replaced using e.g., SQLDataSources having the same ID in * another directory - there is no reason to modify the contents of the 'mock' subdirectory. * <p> * To encourage recommended usage, the reify-import goal takes steps to detect local changes * and fail when any are found. Refer to the {@link #skipOverwriteProtection} * parameter for details. */ // Set requiresProject: false so that we can run the whole thing from an Ant project w/ no POM @Mojo(name="reify-import", requiresProject=false) public class ImportMojo extends AbstractBaseMojo { private static final Logger LOGGER = LoggerFactory.getLogger(ImportMojo.class); /** * The id of a <a href="http://maven.apache.org/settings.html#Servers">server * configuration</a> containing authentication credentials for the * reify.com website, used to download exported projects. * * @since 1.4.0 */ @Parameter(property = "serverId", defaultValue = "smartclient-developer") protected String serverId; /** * The directory to which the archive is downloaded and unpacked. Note that this is * not the final destination of exported assets. For that, see {@link ImportMojo#webappDir}. * * @since 1.4.0 */ @Parameter(property = "workdir", defaultValue = "${project.build.directory}/reify") private File workdir; /** * The directory containing web application sources. * * @since 1.4.0 */ @Parameter(property = "webappDir", defaultValue = "${project.basedir}/src/main/webapp") private File webappDir; /** * The directory to which exported DataSources should ultimately reside, relative to {@link ImportMojo#webappDir}. * Note that this will need to conform to the webapp's server.properties <code>project.datasources</code> configuration. * Also note that MockDataSources will be imported to a 'mock' subdirectory. e.g., WEB-INF/ds/mock. * * @since 1.4.0 */ @Parameter(property = "datasourcesDir", defaultValue = "WEB-INF/ds") private String datasourcesDir; /** * The directory to which exported screens should ultimately reside, relative to {@link ImportMojo#webappDir}. * Note that this will need to conform to the webapp's server.properties <code>project.ui</code> configuration. * * @since 1.4.0 */ @Parameter(property = "uiDir", defaultValue = "WEB-INF/ui") private String uiDir; /** * The directory to which the exported project file should ultimately reside, relative to {@link ImportMojo#webappDir}. * Note that this will need to conform to the webapp's server.properties <code>project.project</code> configuration. * * @since 1.4.0 */ @Parameter(property="projectFileDir", defaultValue = "WEB-INF/ui") private String projectFileDir; /** * The name of the project as its known by the reify.com environment. */ @Parameter(property="projectName", defaultValue = "${project.artifactId}", required=true) private String projectName; private String projectFileName; private String zipFileName; /** * When a project is imported, its screen and datasource assets are marked with a checksum * representing the contents of each file. Subsequent imports are preceded by a check to * make sure each of these checksums still match the file's content. In the event that * any do not, the import fails by default. * <p> * To override this behavior, you may set this parameter value to <code>true</code>, in * which case the file will simply be overwritten. Use this feature at your own risk. */ @Parameter(property="skipOverwriteProtection", defaultValue = "false") private boolean skipOverwriteProtection; private UsernamePasswordCredentials credentials; private Configuration freemarkerConfig; private Proxy proxy; private HttpHost host; private HttpRequestManager httpWorker; public ImportMojo() { // undocumented parameter to allow for testing against QA environment String hostname = System.getProperty("reify-hostname"); if (hostname == null) { hostname = "app.reify.com"; } host = new HttpHost(hostname, -1, "https"); // we'll use a freemarker template to construct the request for project metadata ClassTemplateLoader ctl = new ClassTemplateLoader(getClass(), ""); freemarkerConfig = new Configuration(Configuration.VERSION_2_3_28); freemarkerConfig.setTemplateLoader(ctl); freemarkerConfig.setDefaultEncoding("UTF-8"); freemarkerConfig.setLogTemplateExceptions(false); freemarkerConfig.setWrapUncheckedExceptions(true); freemarkerConfig.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); } /** * After ensuring there are no local modifications (unless otherwise configured), downloads * and installs Reify project contents to the local project environment. */ @Override public void execute() throws MojoExecutionException, MojoFailureException { try { // derive filenames from project name zipFileName = projectName + ".proj.zip"; projectFileName = projectName + ".proj.xml"; // check to make sure there are no local changes, unless configured otherwise if (! skipOverwriteProtection) { checkForLocalModifications(); } // allow explicit configuration from ImportTask (for Ant builds) if (credentials == null) { credentials = getCredentials(serverId); } if (credentials == null) { throw new MojoExecutionException("Reify credentials have not been configured. Check Maven settings for the '" + serverId + "' server."); } // allow for manual construction of the Proxy (again, for Ant builds) httpWorker = new HttpRequestManager(host, credentials, settings != null ? settings.getActiveProxy() : proxy); httpWorker.login(); // get fresh project metadata and archive from the server Document project = downloadProjectDocument(); File archive = downloadProjectArchive(project); LOGGER.info("Importing Reify project assets from download at '{}'...", archive.getCanonicalPath()); File unpacked = new File(workdir, projectName); ArchiveUtils.unzip(archive, unpacked); // update the new project file with checksums of file content for overwrite protection on future imports writeProjectFile(project, unpacked); // and copy the result to application source FileUtils.copyDirectory(unpacked, webappDir); } catch (MojoExecutionException e) { throw e; } catch (Exception e) { throw new MojoExecutionException("Import Error", e); } finally { try { httpWorker.logout(); } catch (Exception ignore) {} } } /** * Checks for local modifications, as documented at {@link #skipOverwriteProtection}}, * and fails when any local changes are detected. * <p> * Note that files are expected in the configured locations - screens in {@link #uiDir} * and datasources in {@link #datasourcesDir} (or the {@link #datasourcesDir}/mock * subdirectory). * * @throws MojoExecutionException when any local changes are detected * @throws Exception on any other error */ private void checkForLocalModifications() throws MojoExecutionException, Exception { File projectFile = new File(webappDir, projectFileDir + "/" + projectFileName); if (! projectFile.exists()) { LOGGER.info("Project file does not exist at '{}', but will be created during import.", projectFile.getCanonicalPath()); return; } SAXReader reader = new SAXReader(); Document document = reader.read(projectFile); String msg = "File '%s' appears to have been modified since the last import. Aborting to provide an opprtunity to investigate. \n" + "You can either revert your changes, delete the file, or remove its checksum from the project file to continue. \n" + "You can also disable the check for this and all other files using the skipOverwriteProtection parameter."; List<Node> screens = getScreenNodes(document); for (Node screen : screens) { String expected = screen.valueOf("checksum"); if (expected.isEmpty()) { continue; } File file = getScreen(screen, webappDir); if (! file.exists()) { continue; } String actual = Files.asByteSource(file).hash(Hashing.sha256()).toString(); if (!actual.equals(expected)) { LOGGER.debug("Checksum mismatch - Expected: '{}' Actual: '{}'", expected, actual); throw new MojoExecutionException(String.format(msg, file.getCanonicalPath())); } } List<Node> datasources = getDataSourceNodes(document); for (Node ds : datasources) { String expected = ds.valueOf("checksum"); if (expected.isEmpty()) { continue; } File file = getDataSource(ds, webappDir); if (! file.exists()) { continue; } String actual = Files.asByteSource(file).hash(Hashing.sha256()).toString(); if (!actual.equals(expected)) { LOGGER.debug("Checksum mismatch - Expected: '{}' Actual: '{}'", expected, actual); throw new MojoExecutionException(String.format(msg, file.getCanonicalPath())); } } } /** * Requests the named project's metadata from the reify server. * * @return Document containing the result. * @throws Exception when any error occurs */ private Document downloadProjectDocument() throws Exception { LOGGER.info("Contacting server for Reify project metadata..."); HttpGet request = new HttpGet("/isomorphic/RESTHandler/hostedProjects?fileName=" + URLEncoder.encode(projectName) + "&isc_dataFormat=xml"); HttpResponse response = httpWorker.execute(request); String body = null; try { body = EntityUtils.toString(response.getEntity()); Document metadata = DocumentHelper.parseText(body); Node fileContents = metadata.selectSingleNode("//fileContents"); String project = fileContents.getText(); return DocumentHelper.parseText(project); } catch (Exception e) { LOGGER.error("Response from server:" + System.getProperty("line.separator") + body); throw new Exception(String.format("Unexpected response to request for project file. Check that user '%s' is able to access the project named '%s'", credentials.getUserName(), projectName)); } } /** * Requests the named project's export archive, including all screens and all datasources, * downloads it, and saves it to {@link #workdir}. * * @param project metadata used to provide the names of requested assets * @return zip file containing the export result * @throws Exception when any error occurs */ private File downloadProjectArchive(Document project) throws Exception { Map<String, Object> context = new HashMap<String, Object>(); context.put("datasourcesDir", datasourcesDir); context.put("uiDir", uiDir); context.put("projectFileDir", projectFileDir); context.put("projectFileName", projectFileName); context.put("zipFileName", zipFileName); context.put("screens", getScreenNames(project)); context.put("datasources", getDataSourceNames(project)); StringWriter writer = new StringWriter(); freemarkerConfig.getTemplate("transaction.ftl").process(context, writer); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("_transaction", writer.toString())); HttpPost request = new HttpPost("/isomorphic/IDACall?isc_rpc=1"); request.setEntity(new UrlEncodedFormEntity(params)); LOGGER.info("Downloading '{}' project export from '{}'...", projectName, host.getHostName()); HttpResponse response = httpWorker.execute(request); HttpEntity entity = response.getEntity(); if (! "application/zip".equals(entity.getContentType().getValue())) { throw new MojoExecutionException("Response does not contain zip file contents:\n" + EntityUtils.toString(entity)); } FileUtils.forceMkdir(workdir); FileUtils.cleanDirectory(workdir); File zip = new File(workdir + "/" + zipFileName); OutputStream outputStream = null; try { outputStream = new LoggingCountingOutputStream(new FileOutputStream(zip), entity.getContentLength()); entity.writeTo(outputStream); } catch (Exception e) { throw new MojoExecutionException("Error writing file to '" + zip.getAbsolutePath() + "'", e); } finally { IOUtils.closeQuietly(outputStream); } return zip; } /** * Calculates checksums for every file in the downloaded archive, writes them to * the given project file, and stores the result on disk at a folder named for * {@link #projectFileDir}, relative to the given parent. * * @param project metadata used to provide the names of requested assets * @param parent the parent directory * @throws Exception whenany error occurs */ private void writeProjectFile(Document project, File parent) throws Exception { for (Node screen : getScreenNodes(project)) { File file = getScreen(screen, parent); String checksum = Files.asByteSource(file).hash(Hashing.sha256()).toString(); Element element = ((Element) screen).addElement("checksum"); element.setText(checksum); } for (Node datasource : getDataSourceNodes(project)) { File file = getDataSource(datasource, parent); String checksum = Files.asByteSource(file).hash(Hashing.sha256()).toString(); Element element = ((Element) datasource).addElement("checksum"); element.setText(checksum); } // pretty print the file with changes File projectFile = FileUtils.getFile(parent, projectFileDir, projectFileName); OutputFormat purdy = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileWriter(projectFile), purdy); writer.write(project); writer.flush(); writer.close(); } /* * Convenience methods for returning various representations of screens from xml document */ private List<Node> getScreenNodes(Document project) { return project.selectNodes("/Project/screens/root/children/TreeNode"); } private List<String> getScreenNames(Document project) { List<Node> nodes = getScreenNodes(project); List<String> names = new ArrayList<String>(); for (Node node : nodes) { names.add(getScreenName(node)); } return names; } private String getScreenName(Node screen) { return screen.valueOf("fileName"); } private File getScreen(Node metadata, File parent) { return FileUtils.getFile(parent, uiDir, getScreenName(metadata) + ".ui.xml"); } /* * Convenience methods for returning various representations of datasources from xml doc */ private List<Node> getDataSourceNodes(Document project) { return project.selectNodes("/Project/datasources/Record"); } private List<String> getDataSourceNames(Document project) { List<Node> nodes = getDataSourceNodes(project); List<String> names = new ArrayList<String>(); for (Node node : nodes) { names.add(getDataSourceName(node)); } return names; } private String getDataSourceName(Node ds) { return ds.valueOf("dsName"); } private File getDataSource(Node metadata, File parent) { String name = getDataSourceName(metadata); // Check 'mock' subdirectory first, fallback to datasourcesDir if not found. File file = FileUtils.getFile(parent, datasourcesDir, "mock", name + ".ds.xml"); if (! file.exists()) { file = FileUtils.getFile(parent, datasourcesDir, name + ".ds.xml"); } return file; } /* * Setters to allow execution from an Ant build (ImportTask) */ protected void setWorkdir(File workdir) { this.workdir = workdir; } protected void setWebappDir(File webappDir) { this.webappDir = webappDir; } protected void setDatasourcesDir(String datasourcesDir) { this.datasourcesDir = datasourcesDir; } protected void setUiDir(String uiDir) { this.uiDir = uiDir; } protected void setProjectFileDir(String projectFileDir) { this.projectFileDir = projectFileDir; } protected void setProjectName(String projectName) { this.projectName = projectName; } protected void setProjectFileName(String projectFileName) { this.projectFileName = projectFileName; } protected void setZipFileName(String zipFileName) { this.zipFileName = zipFileName; } protected void setCredentials(UsernamePasswordCredentials credentials) { this.credentials = credentials; } protected void setProxy(Proxy proxy) { this.proxy = proxy; } }
Another minor tweak to javadoc
src/main/java/com/isomorphic/maven/mojo/reify/ImportMojo.java
Another minor tweak to javadoc
<ide><path>rc/main/java/com/isomorphic/maven/mojo/reify/ImportMojo.java <ide> /** <ide> * Provides for single-step download and extraction of assets hosted on the Reify platform. <ide> * While there is nothing to prevent a user from modifying the imported resources, changes <del> * should almost always be made using Reify and then re-imported. <del> * <p> <del> * If necessary, use the API (e.g., RPCManager.createScreen, Canvas.getByLocalId) to modify <del> * imported screen definitions at runtime. <del> * <p> <del> * Imported MockDataSources can be replaced using e.g., SQLDataSources having the same ID in <del> * another directory - there is no reason to modify the contents of the 'mock' subdirectory. <add> * should almost always be made using Reify and then re-imported. If necessary, use the API <add> * (e.g., RPCManager.createScreen, Canvas.getByLocalId) to modify imported screen definitions <add> * at runtime. Imported MockDataSources can simply be replaced using e.g., SQLDataSources <add> * having the same ID in another directory - there is no reason to modify the contents of the <add> * 'mock' subdirectory. <ide> * <p> <ide> * To encourage recommended usage, the reify-import goal takes steps to detect local changes <ide> * and fail when any are found. Refer to the {@link #skipOverwriteProtection}
Java
apache-2.0
8b26e46c9a81738d9e6320a591c4a9e9dfe0b624
0
dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android,dimagi/commcare-android
package org.commcare.utils; import android.os.AsyncTask; import android.os.Environment; import android.util.Log; import android.webkit.MimeTypeMap; import org.commcare.core.network.AuthenticationInterceptor; import org.commcare.core.network.CaptivePortalRedirectException; import org.commcare.network.CommcareRequestGenerator; import org.commcare.network.EncryptedFileBody; import org.commcare.tasks.DataSubmissionListener; import org.commcare.util.LogTypes; import org.javarosa.core.io.StreamsUtil; import org.javarosa.core.io.StreamsUtil.InputIOException; import org.javarosa.core.model.User; import org.javarosa.core.services.Logger; import org.javarosa.xml.ElementParser; import org.javarosa.xml.util.InvalidStructureException; import org.javarosa.xml.util.UnfullfilledRequirementsException; import org.kxml2.io.KXmlParser; import org.xmlpull.v1.XmlPullParserException; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.UnknownHostException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.annotation.Nullable; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Response; import static org.commcare.network.HttpUtils.parseUserVisibleError; public class FormUploadUtil { private static final String TAG = FormUploadUtil.class.getSimpleName(); /** * 15 MB size limit */ public static final long MAX_BYTES = (15 * 1048576) - 1024; // This list is also maintained server side and any changes to this should be replicated on server as well private static final String[] SUPPORTED_FILE_EXTS = {".xml", ".jpg", "jpeg", ".3gpp", ".3gp", ".3ga", ".3g2", ".mp3", ".wav", ".amr", ".mp4", ".3gp2", ".mpg4", ".mpeg4", ".m4v", ".mpg", ".mpeg", ".qcp", ".ogg"}; public static Cipher getDecryptCipher(SecretKeySpec key) { Cipher cipher; try { cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, key); return cipher; //TODO: Something smart here; } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) { e.printStackTrace(); } return null; } /** * Send unencrypted data to the server without user facing progress * reporting. * * @param submissionNumber For progress reporting * @param folder All supported files in this folder will be * attached to the submission * @param url Submission server url * @param user Used to build the http post * @return Submission status code * @throws FileNotFoundException Is raised if xml file isn't found on the * file-system */ public static FormUploadResult sendInstance(int submissionNumber, File folder, String url, User user) throws FileNotFoundException { return sendInstance(submissionNumber, folder, null, url, null, user); } /** * Send data to the server, encrypting xml files and reporting progress * along the way. * * @param submissionNumber For progress reporting * @param folder All supported files in this folder will be * attached to the submission * @param key For encrypting xml files * @param url Submission server url * @param listener Used to report progress to the calling task * @param user Used to build the http post * @return Submission status code * @throws FileNotFoundException Is raised if xml file isn't found on the * file-system */ public static FormUploadResult sendInstance(int submissionNumber, File folder, @Nullable SecretKeySpec key, String url, @Nullable DataSubmissionListener listener, User user) throws FileNotFoundException { File[] files = folder.listFiles(); if (files == null) { // make sure external storage is available to begin with. String state = Environment.getExternalStorageState(); if (!Environment.MEDIA_MOUNTED.equals(state)) { // If so, just bail as if the user had logged out. throw new SessionUnavailableException("External Storage Removed"); } else { throw new FileNotFoundException("No directory found at: " + folder.getAbsoluteFile()); } } // If we're listening, figure out how much (roughly) we have to send long bytes = estimateUploadBytes(files); if (listener != null) { listener.startSubmission(submissionNumber, bytes); } if (files.length == 0) { Log.e(TAG, "no files to upload"); throw new FileNotFoundException("Folder at path " + folder.getAbsolutePath() + " had no files."); } List<MultipartBody.Part> parts = new ArrayList<>(); if (!buildMultipartEntity(parts, key, files)) { return FormUploadResult.RECORD_FAILURE; } CommcareRequestGenerator generator = new CommcareRequestGenerator(user); return submitEntity(parts, url, generator); } /** * Submit multipart entity with plenty of logging * * @return submission status of multipart entity post */ private static FormUploadResult submitEntity(List<MultipartBody.Part> parts, String url, CommcareRequestGenerator generator) { Response<ResponseBody> response; try { response = generator.postMultipart(url, parts, new HashMap<>()); } catch (InputIOException ioe) { // This implies that there was a problem with the _source_ of the // transmission, not the processing or receiving end. Logger.log(LogTypes.TYPE_ERROR_STORAGE, "Internal error reading form record during submission: " + ioe.getWrapped().getMessage()); return FormUploadResult.RECORD_FAILURE; } catch (UnknownHostException e) { e.printStackTrace(); Logger.log(LogTypes.TYPE_WARNING_NETWORK, "Client network issues during submission: " + e.getMessage()); return FormUploadResult.TRANSPORT_FAILURE; } catch (AuthenticationInterceptor.PlainTextPasswordException e) { e.printStackTrace(); Logger.log(LogTypes.TYPE_ERROR_CONFIG_STRUCTURE, "Encountered PlainTextPasswordException while submission: Sending password over HTTP"); return FormUploadResult.AUTH_OVER_HTTP; } catch (CaptivePortalRedirectException e) { e.printStackTrace(); Logger.log(LogTypes.TYPE_WARNING_NETWORK, "Captive portal detected while form submission"); return FormUploadResult.CAPTIVE_PORTAL; } catch (IOException | IllegalStateException e) { Logger.exception("Error reading form during submission: " + e.getMessage(), e); return FormUploadResult.TRANSPORT_FAILURE; } ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { if (response.body() != null) { InputStream responseStream = response.body().byteStream(); StreamsUtil.writeFromInputToOutputNew(responseStream, bos); } } catch (IllegalStateException | IOException e) { e.printStackTrace(); } String responseString = new String(bos.toByteArray()); int responseCode = response.code(); logResponse(responseCode, responseString); if (responseCode >= 200 && responseCode < 300) { return FormUploadResult.FULL_SUCCESS; } else if (responseCode == 401) { return FormUploadResult.AUTH_FAILURE; } else if (responseCode == 406) { return processActionableFaiure(response); } else if (responseCode == 422) { return handleProcessingFailure(response.errorBody().byteStream()); } else if (responseCode == 503 || responseCode == 429) { return FormUploadResult.RATE_LIMITED; } else { return FormUploadResult.FAILURE; } } private static FormUploadResult processActionableFaiure(Response<ResponseBody> response) { String message = parseUserVisibleError(response); FormUploadResult result = FormUploadResult.ACTIONABLE_FAILURE; result.setErrorMessage(message); return result; } private static FormUploadResult handleProcessingFailure(InputStream responseStream) { FormUploadResult result = FormUploadResult.PROCESSING_FAILURE; try { result.setErrorMessage(parseProcessingFailureResponse(responseStream)); } catch (IOException | InvalidStructureException | XmlPullParserException | UnfullfilledRequirementsException e) { // If we can't parse out the failure reason then we won't quarantine this form, because // we won't have any clear info about what happened result = FormUploadResult.FAILURE; Logger.exception("Form processing failed", e); e.printStackTrace(); } return result; } private static void logResponse(int responseCode, String responseString) { String responseCodeMessage = "Response code to form submission attempt was: " + responseCode; Log.e(TAG, responseCodeMessage); Log.d(TAG, responseString); if (!(responseCode >= 200 && responseCode < 300)) { Logger.log(LogTypes.TYPE_WARNING_NETWORK, responseCodeMessage); Logger.log(LogTypes.TYPE_FORM_SUBMISSION, responseCodeMessage); if (!responseString.startsWith("<html>")) { // Only log this if it's going to be useful Logger.log(LogTypes.TYPE_FORM_SUBMISSION, "Response string to failed form submission attempt was: " + responseString); } } } /** * Validate the content body of the XML submission file. * * TODO: this should really be the responsibility of the form record, not * of the submission process, persay. * * NOTE: this is a shallow validation (everything should be more or else * constant time). Throws an exception if the file is gone because that's * a common issue that gets caught to check if storage got removed * * @param f xml file to check * @return false if the file is empty; otherwise true * @throws FileNotFoundException file in question isn't found on the * file-system */ private static boolean validateSubmissionFile(File f) throws FileNotFoundException { if (!f.exists()) { throw new FileNotFoundException("Submission file: " + f.getAbsolutePath()); } // Gotta check f exists here since f.length returns 0 if the file isn't // there for some reason. if (f.length() == 0 && f.exists()) { Logger.log(LogTypes.TYPE_ERROR_STORAGE, "Submission body has no content at: " + f.getAbsolutePath()); return false; } return true; } /** * @return The aggregated size in bytes the files of supported extension * type. */ private static long estimateUploadBytes(File[] files) { long bytes = 0; for (File file : files) { // Make sure we'll be sending it if (!isSupportedMultimediaFile(file.getName())) { continue; } bytes += file.length(); Log.d(TAG, "Added file: " + file.getName() + ". Bytes to send: " + bytes); } return bytes; } /** * Add files of supported type to the multipart entity, encrypting xml * files. * * @param parts Add files to this * @param key Used to encrypt xml files * @param files The files to be added to the entity, * @return false if invalid xml files are found; otherwise true. * @throws FileNotFoundException Is raised when an xml doesn't exist on the * file-system */ private static boolean buildMultipartEntity(List<MultipartBody.Part> parts, @Nullable SecretKeySpec key, File[] files) throws FileNotFoundException { int numAttachmentsInInstanceFolder = 0; int numAttachmentsSuccessfullyAdded = 0; for (File f : files) { if (f.getName().endsWith(".xml")) { if (key != null) { if (!validateSubmissionFile(f)) { return false; } parts.add(createEncryptedFilePart("xml_submission_file", f, "text/xml", key)); } else { parts.add(createFilePart("xml_submission_file", f, "text/xml")); } } else { String contentType = getFileContentType(f); if (contentType != null) { numAttachmentsInInstanceFolder++; numAttachmentsSuccessfullyAdded += addPartToEntity(parts, f, contentType); } else if (isSupportedMultimediaFile(f.getName())) { numAttachmentsInInstanceFolder++; numAttachmentsSuccessfullyAdded += addPartToEntity(parts, f, "application/octet-stream"); } else { Logger.log(LogTypes.TYPE_FORM_SUBMISSION, "Could not add unsupported file type to submission entity: " + f.getName()); } } } Logger.log(LogTypes.TYPE_FORM_SUBMISSION, "Attempted to add " + numAttachmentsInInstanceFolder + " attachments to submission entity"); Logger.log(LogTypes.TYPE_FORM_SUBMISSION, "Successfully added " + numAttachmentsSuccessfullyAdded + " attachments to submission entity"); return true; } private static int addPartToEntity(List<MultipartBody.Part> parts, File f, String contentType) { if (f.length() <= MAX_BYTES) { parts.add(createFilePart(f.getName(), f, contentType)); return 1; } else { Logger.log(LogTypes.TYPE_FORM_SUBMISSION, "Failed to add attachment to submission entity (too large): " + f.getName()); return 0; } } private static String getFileContentType(File f) { if (f.getName().endsWith(".xml")) { return "text/xml"; } else if (f.getName().endsWith(".jpg")) { return "image/jpeg"; } else if (f.getName().endsWith(".3gpp")) { return "audio/3gpp"; } else if (f.getName().endsWith(".3gp")) { return "video/3gpp"; } return null; } private static MultipartBody.Part createFilePart(String partName, File file, String contentType) { // create RequestBody instance from file RequestBody requestFile = RequestBody.create( MediaType.parse(contentType), file); // MultipartBody.Part is used to send also the actual file name return MultipartBody.Part.createFormData(partName, file.getName(), requestFile); } public static MultipartBody.Part createEncryptedFilePart(String partName, File file, String contentType, SecretKeySpec key) { // create RequestBody instance from file RequestBody requestFile = new EncryptedFileBody( MediaType.parse(contentType), file, FormUploadUtil.getDecryptCipher(key)); // MultipartBody.Part is used to send also the actual file name return MultipartBody.Part.createFormData(partName, file.getName(), requestFile); } /** * @return Is the filename's extension in the hard-coded list of supported * files or have a media mimetype? */ public static boolean isSupportedMultimediaFile(String filename) { for (String ext : SUPPORTED_FILE_EXTS) { if (filename.toLowerCase().endsWith(ext)) { return true; } } return isAudioVisualMimeType(filename); } /** * Use the file's extension to determine if it has an audio, * video, or image mimetype. * * @return true if the file has an audio, image, or video mimetype */ private static boolean isAudioVisualMimeType(String filename) { MimeTypeMap mtm = MimeTypeMap.getSingleton(); String[] filenameSegments = filename.split("\\."); if (filenameSegments.length > 1) { // use the file extension to determine the mimetype String ext = filenameSegments[filenameSegments.length - 1]; String mimeType = mtm.getMimeTypeFromExtension(ext); return (mimeType != null) && (mimeType.startsWith("audio") || mimeType.startsWith("image") || mimeType.startsWith("video")); } return false; } public static String parseProcessingFailureResponse(InputStream responseStream) throws IOException, InvalidStructureException, UnfullfilledRequirementsException, XmlPullParserException { KXmlParser baseParser = ElementParser.instantiateParser(responseStream); ElementParser<String> responseParser = new ElementParser<String>(baseParser) { @Override public String parse() throws InvalidStructureException, IOException, XmlPullParserException, UnfullfilledRequirementsException { checkNode("OpenRosaResponse"); nextTag("message"); String natureOfResponse = parser.getAttributeValue(null, "nature"); if ("processing_failure".equals(natureOfResponse)) { return parser.nextText(); } else { throw new UnfullfilledRequirementsException( "<message> for 422 response did not contain expected content"); } } }; return responseParser.parse(); } }
app/src/org/commcare/utils/FormUploadUtil.java
package org.commcare.utils; import android.os.AsyncTask; import android.os.Environment; import android.util.Log; import android.webkit.MimeTypeMap; import org.commcare.core.network.AuthenticationInterceptor; import org.commcare.core.network.CaptivePortalRedirectException; import org.commcare.network.CommcareRequestGenerator; import org.commcare.network.EncryptedFileBody; import org.commcare.tasks.DataSubmissionListener; import org.commcare.util.LogTypes; import org.javarosa.core.io.StreamsUtil; import org.javarosa.core.io.StreamsUtil.InputIOException; import org.javarosa.core.model.User; import org.javarosa.core.services.Logger; import org.javarosa.xml.ElementParser; import org.javarosa.xml.util.InvalidStructureException; import org.javarosa.xml.util.UnfullfilledRequirementsException; import org.kxml2.io.KXmlParser; import org.xmlpull.v1.XmlPullParserException; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.UnknownHostException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.annotation.Nullable; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Response; import static org.commcare.network.HttpUtils.parseUserVisibleError; public class FormUploadUtil { private static final String TAG = FormUploadUtil.class.getSimpleName(); /** * 15 MB size limit */ public static final long MAX_BYTES = (15 * 1048576) - 1024; // This list is also maintained server side and any changes to this should be replicated on server as well private static final String[] SUPPORTED_FILE_EXTS = {".xml", ".jpg", "jpeg", ".3gpp", ".3gp", ".3ga", ".3g2", ".mp3", ".wav", ".amr", ".mp4", ".3gp2", ".mpg4", ".mpeg4", ".m4v", ".mpg", ".mpeg", ".qcp", ".ogg"}; public static Cipher getDecryptCipher(SecretKeySpec key) { Cipher cipher; try { cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, key); return cipher; //TODO: Something smart here; } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) { e.printStackTrace(); } return null; } /** * Send unencrypted data to the server without user facing progress * reporting. * * @param submissionNumber For progress reporting * @param folder All supported files in this folder will be * attached to the submission * @param url Submission server url * @param user Used to build the http post * @return Submission status code * @throws FileNotFoundException Is raised if xml file isn't found on the * file-system */ public static FormUploadResult sendInstance(int submissionNumber, File folder, String url, User user) throws FileNotFoundException { return sendInstance(submissionNumber, folder, null, url, null, user); } /** * Send data to the server, encrypting xml files and reporting progress * along the way. * * @param submissionNumber For progress reporting * @param folder All supported files in this folder will be * attached to the submission * @param key For encrypting xml files * @param url Submission server url * @param listener Used to report progress to the calling task * @param user Used to build the http post * @return Submission status code * @throws FileNotFoundException Is raised if xml file isn't found on the * file-system */ public static FormUploadResult sendInstance(int submissionNumber, File folder, @Nullable SecretKeySpec key, String url, @Nullable DataSubmissionListener listener, User user) throws FileNotFoundException { File[] files = folder.listFiles(); if (files == null) { // make sure external storage is available to begin with. String state = Environment.getExternalStorageState(); if (!Environment.MEDIA_MOUNTED.equals(state)) { // If so, just bail as if the user had logged out. throw new SessionUnavailableException("External Storage Removed"); } else { throw new FileNotFoundException("No directory found at: " + folder.getAbsoluteFile()); } } // If we're listening, figure out how much (roughly) we have to send long bytes = estimateUploadBytes(files); if (listener != null) { listener.startSubmission(submissionNumber, bytes); } if (files.length == 0) { Log.e(TAG, "no files to upload"); throw new FileNotFoundException("Folder at path " + folder.getAbsolutePath() + " had no files."); } List<MultipartBody.Part> parts = new ArrayList<>(); if (!buildMultipartEntity(parts, key, files)) { return FormUploadResult.RECORD_FAILURE; } CommcareRequestGenerator generator = new CommcareRequestGenerator(user); return submitEntity(parts, url, generator); } /** * Submit multipart entity with plenty of logging * * @return submission status of multipart entity post */ private static FormUploadResult submitEntity(List<MultipartBody.Part> parts, String url, CommcareRequestGenerator generator) { Response<ResponseBody> response; try { response = generator.postMultipart(url, parts, new HashMap<>()); } catch (InputIOException ioe) { // This implies that there was a problem with the _source_ of the // transmission, not the processing or receiving end. Logger.log(LogTypes.TYPE_ERROR_STORAGE, "Internal error reading form record during submission: " + ioe.getWrapped().getMessage()); return FormUploadResult.RECORD_FAILURE; } catch (UnknownHostException e) { e.printStackTrace(); Logger.log(LogTypes.TYPE_WARNING_NETWORK, "Client network issues during submission: " + e.getMessage()); return FormUploadResult.TRANSPORT_FAILURE; } catch (AuthenticationInterceptor.PlainTextPasswordException e) { e.printStackTrace(); Logger.log(LogTypes.TYPE_ERROR_CONFIG_STRUCTURE, "Encountered PlainTextPasswordException while submission: Sending password over HTTP"); return FormUploadResult.AUTH_OVER_HTTP; } catch (CaptivePortalRedirectException e) { e.printStackTrace(); Logger.log(LogTypes.TYPE_WARNING_NETWORK, "Captive portal detected while form submission"); return FormUploadResult.CAPTIVE_PORTAL; } catch (IOException | IllegalStateException e) { Logger.exception("Error reading form during submission: " + e.getMessage(), e); return FormUploadResult.TRANSPORT_FAILURE; } ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { if (response.body() != null) { InputStream responseStream = response.body().byteStream(); StreamsUtil.writeFromInputToOutputNew(responseStream, bos); } } catch (IllegalStateException | IOException e) { e.printStackTrace(); } String responseString = new String(bos.toByteArray()); int responseCode = response.code(); logResponse(responseCode, responseString); if (responseCode >= 200 && responseCode < 300) { return FormUploadResult.FULL_SUCCESS; } else if (responseCode == 401) { return FormUploadResult.AUTH_FAILURE; } else if (responseCode == 406) { return processActionableFaiure(response); } else if (responseCode == 422) { return handleProcessingFailure(response.errorBody().byteStream()); } else if (responseCode == 503 || responseCode == 429) { return FormUploadResult.RATE_LIMITED; } else { return FormUploadResult.FAILURE; } } private static FormUploadResult processActionableFaiure(Response<ResponseBody> response) { String message = parseUserVisibleError(response); FormUploadResult result = FormUploadResult.ACTIONABLE_FAILURE; result.setErrorMessage(message); return result; } private static FormUploadResult handleProcessingFailure(InputStream responseStream) { FormUploadResult result = FormUploadResult.PROCESSING_FAILURE; try { result.setErrorMessage(parseProcessingFailureResponse(responseStream)); } catch (IOException | InvalidStructureException | XmlPullParserException | UnfullfilledRequirementsException e) { // If we can't parse out the failure reason then we won't quarantine this form, because // we won't have any clear info about what happened result = FormUploadResult.FAILURE; Logger.exception("Form processing failed", e); e.printStackTrace(); } return result; } private static void logResponse(int responseCode, String responseString) { String responseCodeMessage = "Response code to form submission attempt was: " + responseCode; Log.e(TAG, responseCodeMessage); Log.d(TAG, responseString); if (!(responseCode >= 200 && responseCode < 300)) { Logger.log(LogTypes.TYPE_WARNING_NETWORK, responseCodeMessage); Logger.log(LogTypes.TYPE_FORM_SUBMISSION, responseCodeMessage); if (!responseString.startsWith("<html>")) { // Only log this if it's going to be useful Logger.log(LogTypes.TYPE_FORM_SUBMISSION, "Response string to failed form submission attempt was: " + responseString); } } } /** * Validate the content body of the XML submission file. * * TODO: this should really be the responsibility of the form record, not * of the submission process, persay. * * NOTE: this is a shallow validation (everything should be more or else * constant time). Throws an exception if the file is gone because that's * a common issue that gets caught to check if storage got removed * * @param f xml file to check * @return false if the file is empty; otherwise true * @throws FileNotFoundException file in question isn't found on the * file-system */ private static boolean validateSubmissionFile(File f) throws FileNotFoundException { if (!f.exists()) { throw new FileNotFoundException("Submission file: " + f.getAbsolutePath()); } // Gotta check f exists here since f.length returns 0 if the file isn't // there for some reason. if (f.length() == 0 && f.exists()) { Logger.log(LogTypes.TYPE_ERROR_STORAGE, "Submission body has no content at: " + f.getAbsolutePath()); return false; } return true; } /** * @return The aggregated size in bytes the files of supported extension * type. */ private static long estimateUploadBytes(File[] files) { long bytes = 0; for (File file : files) { // Make sure we'll be sending it if (!isSupportedMultimediaFile(file.getName())) { continue; } bytes += file.length(); Log.d(TAG, "Added file: " + file.getName() + ". Bytes to send: " + bytes); } return bytes; } /** * Add files of supported type to the multipart entity, encrypting xml * files. * * @param parts Add files to this * @param key Used to encrypt xml files * @param files The files to be added to the entity, * @return false if invalid xml files are found; otherwise true. * @throws FileNotFoundException Is raised when an xml doesn't exist on the * file-system */ private static boolean buildMultipartEntity(List<MultipartBody.Part> parts, @Nullable SecretKeySpec key, File[] files) throws FileNotFoundException { int numAttachmentsInInstanceFolder = 0; int numAttachmentsSuccessfullyAdded = 0; for (File f : files) { if (f.getName().endsWith(".xml")) { if (key != null) { if (!validateSubmissionFile(f)) { return false; } parts.add(createEncryptedFilePart("xml_submission_file", f, "text/xml", key)); } else { parts.add(createFilePart("xml_submission_file", f, "text/xml")); } } else { String contentType = getFileContentType(f); if (contentType != null) { numAttachmentsInInstanceFolder++; numAttachmentsSuccessfullyAdded += addPartToEntity(parts, f, contentType); } else if (isSupportedMultimediaFile(f.getName())) { numAttachmentsInInstanceFolder++; numAttachmentsSuccessfullyAdded += addPartToEntity(parts, f, "application/octet-stream"); } else { Logger.log(LogTypes.TYPE_FORM_SUBMISSION, "Could not add unsupported file type to submission entity: " + f.getName()); } } } Logger.log(LogTypes.TYPE_FORM_SUBMISSION, "Attempted to add " + numAttachmentsInInstanceFolder + " attachments to submission entity"); Logger.log(LogTypes.TYPE_FORM_SUBMISSION, "Successfully added " + numAttachmentsSuccessfullyAdded + " attachments to submission entity"); return true; } private static int addPartToEntity(List<MultipartBody.Part> parts, File f, String contentType) { if (f.length() <= MAX_BYTES) { parts.add(createFilePart(f.getName(), f, contentType)); return 1; } else { Logger.log(LogTypes.TYPE_FORM_SUBMISSION, "Failed to add attachment to submission entity (too large): " + f.getName()); return 0; } } private static String getFileContentType(File f) { if (f.getName().endsWith(".xml")) { return "text/xml"; } else if (f.getName().endsWith(".jpg")) { return "image/jpeg"; } else if (f.getName().endsWith(".3gpp")) { return "audio/3gpp"; } else if (f.getName().endsWith(".3gp")) { return "video/3gpp"; } return null; } private static MultipartBody.Part createFilePart(String partName, File file, String contentType) { // create RequestBody instance from file RequestBody requestFile = RequestBody.create( MediaType.parse(contentType), file); // MultipartBody.Part is used to send also the actual file name return MultipartBody.Part.createFormData(partName, file.getName(), requestFile); } public static MultipartBody.Part createEncryptedFilePart(String partName, File file, String contentType, SecretKeySpec key) { // create RequestBody instance from file RequestBody requestFile = new EncryptedFileBody( MediaType.parse(contentType), file, FormUploadUtil.getDecryptCipher(key)); // MultipartBody.Part is used to send also the actual file name return MultipartBody.Part.createFormData(partName, file.getName(), requestFile); } /** * @return Is the filename's extension in the hard-coded list of supported * files or have a media mimetype? */ public static boolean isSupportedMultimediaFile(String filename) { for (String ext : SUPPORTED_FILE_EXTS) { if (filename.endsWith(ext)) { return true; } } return isAudioVisualMimeType(filename); } /** * Use the file's extension to determine if it has an audio, * video, or image mimetype. * * @return true if the file has an audio, image, or video mimetype */ private static boolean isAudioVisualMimeType(String filename) { MimeTypeMap mtm = MimeTypeMap.getSingleton(); String[] filenameSegments = filename.split("\\."); if (filenameSegments.length > 1) { // use the file extension to determine the mimetype String ext = filenameSegments[filenameSegments.length - 1]; String mimeType = mtm.getMimeTypeFromExtension(ext); return (mimeType != null) && (mimeType.startsWith("audio") || mimeType.startsWith("image") || mimeType.startsWith("video")); } return false; } public static String parseProcessingFailureResponse(InputStream responseStream) throws IOException, InvalidStructureException, UnfullfilledRequirementsException, XmlPullParserException { KXmlParser baseParser = ElementParser.instantiateParser(responseStream); ElementParser<String> responseParser = new ElementParser<String>(baseParser) { @Override public String parse() throws InvalidStructureException, IOException, XmlPullParserException, UnfullfilledRequirementsException { checkNode("OpenRosaResponse"); nextTag("message"); String natureOfResponse = parser.getAttributeValue(null, "nature"); if ("processing_failure".equals(natureOfResponse)) { return parser.nextText(); } else { throw new UnfullfilledRequirementsException( "<message> for 422 response did not contain expected content"); } } }; return responseParser.parse(); } }
Improve check for supported file extensions
app/src/org/commcare/utils/FormUploadUtil.java
Improve check for supported file extensions
<ide><path>pp/src/org/commcare/utils/FormUploadUtil.java <ide> */ <ide> public static boolean isSupportedMultimediaFile(String filename) { <ide> for (String ext : SUPPORTED_FILE_EXTS) { <del> if (filename.endsWith(ext)) { <add> if (filename.toLowerCase().endsWith(ext)) { <ide> return true; <ide> } <ide> }
JavaScript
mit
671949cbab9387c5bbb484fbb9264d7fe59a05b8
0
zerosquadron/ticTacToe,zerosquadron/ticTacToe
class Store { constructor () { const square = new Array(3).fill(''); const gameboard = new Array(3).fill(square); this.gameboard = gameboard; this.message = ''; this.marker = 'o'; } getState (id) { if (id === 'gameboard') { return this.gameboard; } if (id === 'message') { return this.message; } return id; } action (obj) { const {x, y} = obj; this.gameboard = this.gameboard.map((row, yIndex) => { return row.map((square, xIndex) => { const targetSquare = (yIndex === y && xIndex === x); const isEmpty = square === ''; if (targetSquare) { if (!isEmpty) { this.message = 'Pick an unoccupied square, hoser.'; return square; } this.marker = this.marker === 'x' ? 'o' : 'x'; return this.marker; } return square; }); }); if (this.callback) { this.callback(); } } register (callback) { if (!callback) { throw new Error('onChange needs a callback'); } this.callback = callback; } } module.exports = Store;
src/javascripts/store.js
class Store { constructor () { const square = new Array(3).fill(''); const gameboard = new Array(3).fill(square); this.gameboard = gameboard; this.message = ''; this.marker = 'o'; this.isValid = square === '' ? true : false; } getMarker () { console.log('get marker', this.marker) } getState (id) { if (id === 'gameboard') { return this.gameboard; } if (id === 'message') { return this.message; } return id; } action (obj) { const {x, y} = obj; this.gameboard = this.gameboard.map((row, yIndex) => { return row.map((square, xIndex) => { const targetSquare = (yIndex === y && xIndex === x); const isEmpty = square == ''; if (targetSquare) { if (!isEmpty) { this.message = 'Pick an unoccupied square, hoser.'; return square; } this.marker = this.marker === 'x' ? 'o' : 'x'; return this.marker; } return square; }); }); console.log('MARKER', this.marker, this.gameboard); if (this.callback) { this.callback(); } } register (callback) { if (!callback) { throw new Error('onChange needs a callback'); } this.callback = callback; } } module.exports = Store;
clean up
src/javascripts/store.js
clean up
<ide><path>rc/javascripts/store.js <ide> this.gameboard = gameboard; <ide> this.message = ''; <ide> this.marker = 'o'; <del> this.isValid = square === '' ? true : false; <del> } <del> <del> getMarker () { <del> console.log('get marker', this.marker) <ide> } <ide> <ide> getState (id) { <ide> <ide> return row.map((square, xIndex) => { <ide> const targetSquare = (yIndex === y && xIndex === x); <del> const isEmpty = square == ''; <add> const isEmpty = square === ''; <ide> if (targetSquare) { <ide> if (!isEmpty) { <ide> this.message = 'Pick an unoccupied square, hoser.'; <ide> return square; <ide> }); <ide> }); <del> console.log('MARKER', this.marker, this.gameboard); <add> <ide> if (this.callback) { <ide> this.callback(); <ide> }
Java
mit
222f200aa0c2fc469070ee07b66c76307a626c87
0
PhiCode/philib,PhiCode/philib
package ch.bind.philib.cache.lru; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import ch.bind.philib.validation.Validation; public final class SyncCache<K, V> implements Cache<K, V> { private final Lock lock = new ReentrantLock(); private final Cache<K, V> cache; public SyncCache(Cache<K, V> cache) { Validation.notNull(cache); this.cache = cache; } public static final <K, V> Cache<K, V> wrap(Cache<K, V> cache) { return new SyncCache<K, V>(cache); } @Override public void add(K key, V value) { lock.lock(); try { cache.add(key, value); } finally { lock.unlock(); } } @Override public V get(K key) { lock.lock(); try { return cache.get(key); } finally { lock.unlock(); } } @Override public void remove(K key) { lock.lock(); try { cache.remove(key); } finally { lock.unlock(); } } @Override public int capacity() { return cache.capacity(); } @Override public void clear() { lock.lock(); try { cache.clear(); } finally { lock.unlock(); } } }
src/main/java/ch/bind/philib/cache/lru/SyncCache.java
package ch.bind.philib.cache.lru; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import ch.bind.philib.validation.Validation; public final class SyncCache<K, V> implements Cache<K, V> { private final Lock lock = new ReentrantLock(); private final Cache<K, V> cache; public SyncCache(Cache<K, V> cache) { Validation.notNull(cache); this.cache = cache; } @Override public void add(K key, V value) { lock.lock(); try { cache.add(key, value); } finally { lock.unlock(); } } @Override public V get(K key) { lock.lock(); try { return cache.get(key); } finally { lock.unlock(); } } @Override public void remove(K key) { lock.lock(); try { cache.remove(key); } finally { lock.unlock(); } } @Override public int capacity() { return cache.capacity(); } @Override public void clear() { lock.lock(); try { cache.clear(); } finally { lock.unlock(); } } }
utility method for easier access
src/main/java/ch/bind/philib/cache/lru/SyncCache.java
utility method for easier access
<ide><path>rc/main/java/ch/bind/philib/cache/lru/SyncCache.java <ide> public SyncCache(Cache<K, V> cache) { <ide> Validation.notNull(cache); <ide> this.cache = cache; <add> } <add> <add> public static final <K, V> Cache<K, V> wrap(Cache<K, V> cache) { <add> return new SyncCache<K, V>(cache); <ide> } <ide> <ide> @Override
Java
apache-2.0
e22afb2c116b4e9ffb0d49021aeede8ad4d56785
0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.config.server; import com.yahoo.cloud.config.LbServicesConfig; import com.yahoo.cloud.config.LbServicesConfig.Tenants.Applications; import com.yahoo.config.model.api.ApplicationInfo; import com.yahoo.config.model.api.SuperModel; import com.yahoo.config.model.application.provider.FilesApplicationPackage; import com.yahoo.config.model.deploy.DeployState; import com.yahoo.config.model.deploy.TestProperties; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.ApplicationName; import com.yahoo.config.provision.InstanceName; import com.yahoo.config.provision.TenantName; import com.yahoo.config.provision.Zone; import com.yahoo.jrt.Request; import com.yahoo.vespa.config.ConfigKey; import com.yahoo.vespa.config.protocol.CompressionType; import com.yahoo.vespa.config.protocol.DefContent; import com.yahoo.vespa.config.protocol.JRTClientConfigRequestV3; import com.yahoo.vespa.config.protocol.JRTServerConfigRequestV3; import com.yahoo.vespa.config.protocol.Trace; import com.yahoo.vespa.config.server.model.SuperModelConfigProvider; import com.yahoo.vespa.config.server.rpc.UncompressedConfigResponseFactory; import com.yahoo.vespa.flags.InMemoryFlagSource; import com.yahoo.vespa.model.VespaModel; import org.junit.Before; import org.junit.Test; import org.xml.sax.SAXException; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import static com.yahoo.config.model.api.container.ContainerServiceType.QRSERVER; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; /** * @author Ulf Lilleengen */ public class SuperModelControllerTest { private SuperModelController handler; @Before public void setupHandler() throws IOException, SAXException { Map<ApplicationId, ApplicationInfo> models = new LinkedHashMap<>(); File testApp = new File("src/test/resources/deploy/app"); ApplicationId app = ApplicationId.from(TenantName.from("a"), ApplicationName.from("foo"), InstanceName.defaultName()); models.put(app, new ApplicationInfo(app, 4L, new VespaModel(FilesApplicationPackage.fromFile(testApp)))); SuperModel superModel = new SuperModel(models, true); handler = new SuperModelController(new SuperModelConfigProvider(superModel, Zone.defaultZone(), new InMemoryFlagSource()), new TestConfigDefinitionRepo(), 2, new UncompressedConfigResponseFactory()); } @Test public void test_lb_config_simple() { LbServicesConfig.Builder lb = new LbServicesConfig.Builder(); handler.getSuperModel().getConfig(lb); LbServicesConfig lbc = new LbServicesConfig(lb); assertThat(lbc.tenants().size(), is(1)); assertThat(lbc.tenants("a").applications().size(), is(1)); Applications app = lbc.tenants("a").applications("foo:prod:default:default"); assertTrue(app.hosts().size() > 0); } @Test(expected = UnknownConfigDefinitionException.class) public void test_unknown_config_definition() { String md5 = "asdfasf"; Request request = JRTClientConfigRequestV3.createWithParams(new ConfigKey<>("foo", "id", "bar", md5, null), DefContent.fromList(Collections.emptyList()), "fromHost", md5, 1, 1, Trace.createDummy(), CompressionType.UNCOMPRESSED, Optional.empty()) .getRequest(); JRTServerConfigRequestV3 v3Request = JRTServerConfigRequestV3.createFromRequest(request); handler.resolveConfig(v3Request); } @Test public void test_lb_config_multiple_apps() throws IOException, SAXException { Map<ApplicationId, ApplicationInfo> models = new LinkedHashMap<>(); TenantName t1 = TenantName.from("t1"); TenantName t2 = TenantName.from("t2"); File testApp1 = new File("src/test/resources/deploy/app"); File testApp2 = new File("src/test/resources/deploy/advancedapp"); File testApp3 = new File("src/test/resources/deploy/advancedapp"); ApplicationId simple = applicationId("mysimpleapp", t1); ApplicationId advanced = applicationId("myadvancedapp", t1); ApplicationId tooAdvanced = applicationId("minetooadvancedapp", t2); models.put(simple, createApplicationInfo(testApp1, simple, 4L)); models.put(advanced, createApplicationInfo(testApp2, advanced, 4L)); models.put(tooAdvanced, createApplicationInfo(testApp3, tooAdvanced, 4L)); SuperModel superModel = new SuperModel(models, true); SuperModelController han = new SuperModelController(new SuperModelConfigProvider(superModel, Zone.defaultZone(), new InMemoryFlagSource()), new TestConfigDefinitionRepo(), 2, new UncompressedConfigResponseFactory()); LbServicesConfig.Builder lb = new LbServicesConfig.Builder(); han.getSuperModel().getConfig(lb); LbServicesConfig lbc = new LbServicesConfig(lb); assertThat(lbc.tenants().size(), is(2)); assertThat(lbc.tenants("t1").applications().size(), is(2)); assertThat(lbc.tenants("t2").applications().size(), is(1)); assertThat(lbc.tenants("t2").applications("minetooadvancedapp:prod:default:default").hosts().size(), is(1)); assertQrServer(lbc.tenants("t2").applications("minetooadvancedapp:prod:default:default")); } private ApplicationId applicationId(String applicationName, TenantName tenantName) { return ApplicationId.from(tenantName, ApplicationName.from(applicationName), InstanceName.defaultName()); } private void assertQrServer(Applications app) { String host = app.hosts().keySet().iterator().next(); Applications.Hosts hosts = app.hosts(host); assertThat(hosts.hostname(), is(host)); for (Map.Entry<String, Applications.Hosts.Services> e : app.hosts(host).services().entrySet()) { if (QRSERVER.serviceName.equals(e.getKey())) { Applications.Hosts.Services s = e.getValue(); assertThat(s.type(), is("qrserver")); assertThat(s.ports().size(), is(4)); assertThat(s.ports().get(0).number(), is(8000)); assertThat(s.index(), is(0)); return; } } org.junit.Assert.fail("No container service in config"); } private DeployState createDeployState(File applicationPackage, ApplicationId applicationId) { return new DeployState.Builder() .applicationPackage(FilesApplicationPackage.fromFile(applicationPackage)) .properties(new TestProperties().setApplicationId(applicationId)) .build(); } private ApplicationInfo createApplicationInfo(File applicationPackage, ApplicationId applicationId, long generation) throws IOException, SAXException { DeployState deployState = createDeployState(applicationPackage, applicationId); return new ApplicationInfo(applicationId, generation, new VespaModel(deployState)); } }
configserver/src/test/java/com/yahoo/vespa/config/server/SuperModelControllerTest.java
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.config.server; import com.yahoo.cloud.config.LbServicesConfig; import com.yahoo.cloud.config.LbServicesConfig.Tenants.Applications; import com.yahoo.config.model.api.ApplicationInfo; import com.yahoo.config.model.api.SuperModel; import com.yahoo.config.model.application.provider.FilesApplicationPackage; import com.yahoo.config.model.deploy.DeployState; import com.yahoo.config.model.deploy.TestProperties; import com.yahoo.config.provision.ApplicationId; import com.yahoo.config.provision.ApplicationName; import com.yahoo.config.provision.InstanceName; import com.yahoo.config.provision.TenantName; import com.yahoo.config.provision.Zone; import com.yahoo.jrt.Request; import com.yahoo.vespa.config.ConfigKey; import com.yahoo.vespa.config.protocol.CompressionType; import com.yahoo.vespa.config.protocol.DefContent; import com.yahoo.vespa.config.protocol.JRTClientConfigRequestV3; import com.yahoo.vespa.config.protocol.JRTServerConfigRequestV3; import com.yahoo.vespa.config.protocol.Trace; import com.yahoo.vespa.config.server.model.SuperModelConfigProvider; import com.yahoo.vespa.config.server.rpc.UncompressedConfigResponseFactory; import com.yahoo.vespa.flags.InMemoryFlagSource; import com.yahoo.vespa.model.VespaModel; import org.junit.Before; import org.junit.Test; import org.xml.sax.SAXException; import java.io.File; import java.io.IOException; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.Optional; import static com.yahoo.config.model.api.container.ContainerServiceType.QRSERVER; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; /** * @author Ulf Lilleengen */ public class SuperModelControllerTest { private SuperModelController handler; @Before public void setupHandler() throws IOException, SAXException { Map<ApplicationId, ApplicationInfo> models = new LinkedHashMap<>(); File testApp = new File("src/test/resources/deploy/app"); ApplicationId app = ApplicationId.from(TenantName.from("a"), ApplicationName.from("foo"), InstanceName.defaultName()); models.put(app, new ApplicationInfo(app, 4L, new VespaModel(FilesApplicationPackage.fromFile(testApp)))); SuperModel superModel = new SuperModel(models, true); handler = new SuperModelController(new SuperModelConfigProvider(superModel, Zone.defaultZone(), new InMemoryFlagSource()), new TestConfigDefinitionRepo(), 2, new UncompressedConfigResponseFactory()); } @Test public void test_lb_config_simple() { LbServicesConfig.Builder lb = new LbServicesConfig.Builder(); handler.getSuperModel().getConfig(lb); LbServicesConfig lbc = new LbServicesConfig(lb); assertThat(lbc.tenants().size(), is(1)); assertThat(lbc.tenants("a").applications().size(), is(1)); Applications app = lbc.tenants("a").applications("foo:prod:default:default"); assertTrue(app.hosts().size() > 0); } @Test(expected = UnknownConfigDefinitionException.class) public void test_unknown_config_definition() { String md5 = "asdfasf"; Request request = JRTClientConfigRequestV3.createWithParams(new ConfigKey<>("foo", "id", "bar", md5, null), DefContent.fromList(Collections.emptyList()), "fromHost", md5, 1, 1, Trace.createDummy(), CompressionType.UNCOMPRESSED, Optional.empty()) .getRequest(); JRTServerConfigRequestV3 v3Request = JRTServerConfigRequestV3.createFromRequest(request); handler.resolveConfig(v3Request); } @Test public void test_lb_config_multiple_apps_legacy_super_model() throws IOException, SAXException { Map<ApplicationId, ApplicationInfo> models = new LinkedHashMap<>(); TenantName t1 = TenantName.from("t1"); TenantName t2 = TenantName.from("t2"); File testApp1 = new File("src/test/resources/deploy/app"); File testApp2 = new File("src/test/resources/deploy/advancedapp"); File testApp3 = new File("src/test/resources/deploy/advancedapp"); ApplicationId simple = applicationId("mysimpleapp", t1); ApplicationId advanced = applicationId("myadvancedapp", t1); ApplicationId tooAdvanced = applicationId("minetooadvancedapp", t2); models.put(simple, createApplicationInfo(testApp1, simple, 4L)); models.put(advanced, createApplicationInfo(testApp2, advanced, 4L)); models.put(tooAdvanced, createApplicationInfo(testApp3, tooAdvanced, 4L)); SuperModel superModel = new SuperModel(models, true); SuperModelController han = new SuperModelController(new SuperModelConfigProvider(superModel, Zone.defaultZone(), new InMemoryFlagSource()), new TestConfigDefinitionRepo(), 2, new UncompressedConfigResponseFactory()); LbServicesConfig.Builder lb = new LbServicesConfig.Builder(); han.getSuperModel().getConfig(lb); LbServicesConfig lbc = new LbServicesConfig(lb); assertThat(lbc.tenants().size(), is(2)); assertThat(lbc.tenants("t1").applications().size(), is(2)); assertThat(lbc.tenants("t2").applications().size(), is(1)); assertThat(lbc.tenants("t2").applications("minetooadvancedapp:prod:default:default").hosts().size(), is(1)); assertQrServer(lbc.tenants("t2").applications("minetooadvancedapp:prod:default:default")); } @Test public void test_lb_config_multiple_apps() throws IOException, SAXException { Map<ApplicationId, ApplicationInfo> models = new LinkedHashMap<>(); TenantName t1 = TenantName.from("t1"); TenantName t2 = TenantName.from("t2"); File testApp1 = new File("src/test/resources/deploy/app"); File testApp2 = new File("src/test/resources/deploy/advancedapp"); File testApp3 = new File("src/test/resources/deploy/advancedapp"); ApplicationId simple = applicationId("mysimpleapp", t1); ApplicationId advanced = applicationId("myadvancedapp", t1); ApplicationId tooAdvanced = applicationId("minetooadvancedapp", t2); models.put(simple, createApplicationInfo(testApp1, simple, 4L)); models.put(advanced, createApplicationInfo(testApp2, advanced, 4L)); models.put(tooAdvanced, createApplicationInfo(testApp3, tooAdvanced, 4L)); SuperModel superModel = new SuperModel(models, true); SuperModelController han = new SuperModelController(new SuperModelConfigProvider(superModel, Zone.defaultZone(), new InMemoryFlagSource()), new TestConfigDefinitionRepo(), 2, new UncompressedConfigResponseFactory()); LbServicesConfig.Builder lb = new LbServicesConfig.Builder(); han.getSuperModel().getConfig(lb); LbServicesConfig lbc = new LbServicesConfig(lb); assertThat(lbc.tenants().size(), is(2)); assertThat(lbc.tenants("t1").applications().size(), is(2)); assertThat(lbc.tenants("t2").applications().size(), is(1)); assertThat(lbc.tenants("t2").applications("minetooadvancedapp:prod:default:default").hosts().size(), is(1)); assertQrServer(lbc.tenants("t2").applications("minetooadvancedapp:prod:default:default")); } private ApplicationId applicationId(String applicationName, TenantName tenantName) { return ApplicationId.from(tenantName, ApplicationName.from(applicationName), InstanceName.defaultName()); } private void assertQrServer(Applications app) { String host = app.hosts().keySet().iterator().next(); Applications.Hosts hosts = app.hosts(host); assertThat(hosts.hostname(), is(host)); for (Map.Entry<String, Applications.Hosts.Services> e : app.hosts(host).services().entrySet()) { if (QRSERVER.serviceName.equals(e.getKey())) { Applications.Hosts.Services s = e.getValue(); assertThat(s.type(), is("qrserver")); assertThat(s.ports().size(), is(4)); assertThat(s.ports().get(0).number(), is(8000)); assertThat(s.index(), is(0)); return; } } org.junit.Assert.fail("No container service in config"); } private DeployState createDeployState(File applicationPackage, ApplicationId applicationId) { return new DeployState.Builder() .applicationPackage(FilesApplicationPackage.fromFile(applicationPackage)) .properties(new TestProperties().setApplicationId(applicationId)) .build(); } private ApplicationInfo createApplicationInfo(File applicationPackage, ApplicationId applicationId, long generation) throws IOException, SAXException { DeployState deployState = createDeployState(applicationPackage, applicationId); return new ApplicationInfo(applicationId, generation, new VespaModel(deployState)); } }
Remove legacy test that is now identical to the ordinary test
configserver/src/test/java/com/yahoo/vespa/config/server/SuperModelControllerTest.java
Remove legacy test that is now identical to the ordinary test
<ide><path>onfigserver/src/test/java/com/yahoo/vespa/config/server/SuperModelControllerTest.java <ide> } <ide> <ide> @Test <del> public void test_lb_config_multiple_apps_legacy_super_model() throws IOException, SAXException { <del> Map<ApplicationId, ApplicationInfo> models = new LinkedHashMap<>(); <del> TenantName t1 = TenantName.from("t1"); <del> TenantName t2 = TenantName.from("t2"); <del> File testApp1 = new File("src/test/resources/deploy/app"); <del> File testApp2 = new File("src/test/resources/deploy/advancedapp"); <del> File testApp3 = new File("src/test/resources/deploy/advancedapp"); <del> <del> ApplicationId simple = applicationId("mysimpleapp", t1); <del> ApplicationId advanced = applicationId("myadvancedapp", t1); <del> ApplicationId tooAdvanced = applicationId("minetooadvancedapp", t2); <del> models.put(simple, createApplicationInfo(testApp1, simple, 4L)); <del> models.put(advanced, createApplicationInfo(testApp2, advanced, 4L)); <del> models.put(tooAdvanced, createApplicationInfo(testApp3, tooAdvanced, 4L)); <del> <del> SuperModel superModel = new SuperModel(models, true); <del> SuperModelController han = new SuperModelController(new SuperModelConfigProvider(superModel, Zone.defaultZone(), new InMemoryFlagSource()), new TestConfigDefinitionRepo(), 2, new UncompressedConfigResponseFactory()); <del> LbServicesConfig.Builder lb = new LbServicesConfig.Builder(); <del> han.getSuperModel().getConfig(lb); <del> LbServicesConfig lbc = new LbServicesConfig(lb); <del> assertThat(lbc.tenants().size(), is(2)); <del> assertThat(lbc.tenants("t1").applications().size(), is(2)); <del> assertThat(lbc.tenants("t2").applications().size(), is(1)); <del> assertThat(lbc.tenants("t2").applications("minetooadvancedapp:prod:default:default").hosts().size(), is(1)); <del> assertQrServer(lbc.tenants("t2").applications("minetooadvancedapp:prod:default:default")); <del> } <del> <del> @Test <ide> public void test_lb_config_multiple_apps() throws IOException, SAXException { <ide> Map<ApplicationId, ApplicationInfo> models = new LinkedHashMap<>(); <ide> TenantName t1 = TenantName.from("t1");
Java
apache-2.0
911f681ddc5b1e8b3c8f886e6efdf34ad2b9251f
0
cherryhill/collectionspace-application
package org.collectionspace.chain.csp.webui.record; import org.apache.commons.lang.StringUtils; import org.collectionspace.chain.csp.config.ConfigException; import org.collectionspace.chain.csp.schema.Record; import org.collectionspace.chain.csp.schema.Spec; import org.collectionspace.chain.csp.webui.main.Request; import org.collectionspace.chain.csp.webui.main.WebMethod; import org.collectionspace.chain.csp.webui.main.WebUI; import org.collectionspace.csp.api.persistence.ExistException; import org.collectionspace.csp.api.persistence.Storage; import org.collectionspace.csp.api.persistence.UnderlyingStorageException; import org.collectionspace.csp.api.persistence.UnimplementedException; import org.collectionspace.csp.api.ui.Operation; import org.collectionspace.csp.api.ui.UIException; import org.collectionspace.csp.api.ui.UIRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RecordCreateUpdate implements WebMethod { private static final Logger log=LoggerFactory.getLogger(RecordCreateUpdate.class); private String url_base,base; private boolean create; private Spec spec; private RecordRead reader; private RecordSearchList searcher; public RecordCreateUpdate(Record r,boolean create) { spec=r.getSpec(); this.url_base=r.getWebURL(); this.base=r.getID(); this.create=create; this.reader=new RecordRead(r); this.reader.configure(spec); this.searcher = new RecordSearchList(r,false); } private void deleteAllRelations(Storage storage,String csid) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException { JSONObject r=new JSONObject(); r.put("src",base+"/"+csid); // XXX needs pagination support CSPACE-1819 JSONObject data = storage.getPathsJSON("relations/main",r); String[] paths = (String[]) data.get("listItems"); for(String relation : paths) { storage.deleteJSON("relations/main/"+relation); } } private void setRelations(Storage storage,String csid,JSONArray relations) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException { deleteAllRelations(storage,csid); for(int i=0;i<relations.length();i++) { // Extract data from miniobject JSONObject in=relations.getJSONObject(i); String dst_type=spec.getRecordByWebUrl(in.getString("recordtype")).getID(); String dst_id=in.getString("csid"); String type=in.getString("relationshiptype"); // Create relation JSONObject r=new JSONObject(); r.put("src",base+"/"+csid); r.put("dst",dst_type+"/"+dst_id); r.put("type",type); storage.autocreateJSON("relations/main",r); } } private String sendJSON(Storage storage,String path,JSONObject data) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException { JSONObject fields=data.optJSONObject("fields"); JSONArray relations=data.optJSONArray("relations"); if(path!=null) { // Update if(fields!=null) storage.updateJSON(base+"/"+path,fields); } else { // Create if(fields!=null) path=storage.autocreateJSON(base,fields); } if(relations!=null) setRelations(storage,path,relations); return path; } private JSONObject getPerm(Storage storage, String resourceName, String permlevel) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException, UIException{ JSONObject permitem = new JSONObject(); String actions = ""; ///cspace-services/authorization/permissions?res=acquisition&actGrp=CRUDL String queryString = "CRUDL"; if(permlevel.equals("none")){ queryString = ""; actions = "[]"; return permitem; } if(permlevel.equals("read")){ queryString = "RL"; actions = "[{\"name\":\"READ\"},{\"name\":\"SEARCH\"}]"; } if(permlevel.equals("write")){ queryString = "CRUL"; actions = "[{\"name\":\"CREATE\"},{\"name\":\"READ\"},{\"name\":\"UPDATE\"},{\"name\":\"SEARCH\"}]"; } if(permlevel.equals("delete")){ queryString = "CRUDL"; actions = "[{\"name\":\"CREATE\"},{\"name\":\"READ\"},{\"name\":\"UPDATE\"},{\"name\":\"DELETE\"},{\"name\":\"SEARCH\"}]"; } JSONObject permrestrictions = new JSONObject(); permrestrictions.put("keywords", resourceName); permrestrictions.put("queryTerm", "actGrp"); permrestrictions.put("queryString", queryString); String permbase = spec.getRecordByWebUrl("permission").getID(); JSONObject data = searcher.getJSON(storage,permrestrictions,"items",permbase); String permid = ""; JSONArray items = data.getJSONArray("items"); for(int i=0;i<items.length();i++){ JSONObject item = items.getJSONObject(i); JSONObject permission = new JSONObject(); String resourcename = item.getString("summary"); String actionGroup = item.getString("number"); //need to do a double check as the query is an inexact match if(resourcename.equals(resourceName) && actionGroup.equals(queryString)){ permid = item.getString("csid"); } } if(permid.equals("")){ //create the permission /** * { "effect": "PERMIT", "resourceName": "testthing2", "action":[{"name":"CREATE"},{"name":"READ"},{"name":"UPDATE"},{"name":"DELETE"},{"name":"SEARCH"}] } */ JSONObject permission_add = new JSONObject(); JSONArray allactions = new JSONArray(actions); permission_add.put("effect", "PERMIT"); permission_add.put("resourceName", resourceName); permission_add.put("actionGroup", queryString); permission_add.put("actions", allactions); permid=storage.autocreateJSON(spec.getRecordByWebUrl("permission").getID(),permission_add); } if(!permid.equals("")){ permitem.put("resourceName", resourceName); permitem.put("permissionId", permid); permitem.put("actionGroup", queryString); } return permitem; } private void assignPermissions(Storage storage, String path, JSONObject data) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException, UIException{ JSONObject fields=data.optJSONObject("fields"); JSONArray permdata = new JSONArray(); if(fields.has("permissions")){ JSONArray permissions = fields.getJSONArray("permissions"); for(int i=0;i<permissions.length();i++){ JSONObject perm = permissions.getJSONObject(i); JSONObject permitem = getPerm(storage,perm.getString("resourceName"),perm.getString("permission")); if(permitem.has("permissionId")){ permdata.put(permitem); } } } JSONObject roledata = new JSONObject(); roledata.put("roleName", fields.getString("roleName")); String[] ids=path.split("/"); roledata.put("roleId", ids[ids.length - 1]); JSONObject accountrole = new JSONObject(); JSONObject arfields = new JSONObject(); arfields.put("role", roledata); arfields.put("permission", permdata); accountrole.put("fields", arfields); if(fields!=null) path=storage.autocreateJSON(spec.getRecordByWebUrl("permrole").getID(),arfields); } private void store_set(Storage storage,UIRequest request,String path) throws UIException { try { JSONObject data=request.getJSONBody(); if(create) { path=sendJSON(storage,null,data); data.put("csid",path); data.getJSONObject("fields").put("csid",path); } else path=sendJSON(storage,path,data); if(path==null) throw new UIException("Insufficient data for create (no fields?)"); if(this.base.equals("role")){ assignPermissions(storage,path,data); } data=reader.getJSON(storage,path); request.sendJSONResponse(data); request.setOperationPerformed(create?Operation.CREATE:Operation.UPDATE); if(create) request.setSecondaryRedirectPath(new String[]{url_base,path}); } catch (JSONException x) { throw new UIException("Failed to parse json: "+x,x); } catch (ExistException x) { throw new UIException("Existence exception: "+x,x); } catch (UnimplementedException x) { throw new UIException("Unimplemented exception: "+x,x); } catch (UnderlyingStorageException x) { throw new UIException("Problem storing: "+x,x); } } public void run(Object in, String[] tail) throws UIException { Request q=(Request)in; store_set(q.getStorage(),q.getUIRequest(),StringUtils.join(tail,"/")); } public void configure() throws ConfigException {} public void configure(WebUI ui,Spec spec) {} }
cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/record/RecordCreateUpdate.java
package org.collectionspace.chain.csp.webui.record; import org.apache.commons.lang.StringUtils; import org.collectionspace.chain.csp.config.ConfigException; import org.collectionspace.chain.csp.schema.Record; import org.collectionspace.chain.csp.schema.Spec; import org.collectionspace.chain.csp.webui.main.Request; import org.collectionspace.chain.csp.webui.main.WebMethod; import org.collectionspace.chain.csp.webui.main.WebUI; import org.collectionspace.csp.api.persistence.ExistException; import org.collectionspace.csp.api.persistence.Storage; import org.collectionspace.csp.api.persistence.UnderlyingStorageException; import org.collectionspace.csp.api.persistence.UnimplementedException; import org.collectionspace.csp.api.ui.Operation; import org.collectionspace.csp.api.ui.UIException; import org.collectionspace.csp.api.ui.UIRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class RecordCreateUpdate implements WebMethod { private static final Logger log=LoggerFactory.getLogger(RecordCreateUpdate.class); private String url_base,base; private boolean create; private Spec spec; private RecordRead reader; private RecordSearchList searcher; public RecordCreateUpdate(Record r,boolean create) { spec=r.getSpec(); this.url_base=r.getWebURL(); this.base=r.getID(); this.create=create; this.reader=new RecordRead(r); this.reader.configure(spec); this.searcher = new RecordSearchList(r,false); } private void deleteAllRelations(Storage storage,String csid) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException { JSONObject r=new JSONObject(); r.put("src",base+"/"+csid); // XXX needs pagination support CSPACE-1819 JSONObject data = storage.getPathsJSON("relations/main",r); String[] paths = (String[]) data.get("listItems"); for(String relation : paths) { storage.deleteJSON("relations/main/"+relation); } } private void setRelations(Storage storage,String csid,JSONArray relations) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException { deleteAllRelations(storage,csid); for(int i=0;i<relations.length();i++) { // Extract data from miniobject JSONObject in=relations.getJSONObject(i); String dst_type=spec.getRecordByWebUrl(in.getString("recordtype")).getID(); String dst_id=in.getString("csid"); String type=in.getString("relationshiptype"); // Create relation JSONObject r=new JSONObject(); r.put("src",base+"/"+csid); r.put("dst",dst_type+"/"+dst_id); r.put("type",type); storage.autocreateJSON("relations/main",r); } } private String sendJSON(Storage storage,String path,JSONObject data) throws ExistException, UnimplementedException, UnderlyingStorageException, JSONException { JSONObject fields=data.optJSONObject("fields"); JSONArray relations=data.optJSONArray("relations"); if(path!=null) { // Update if(fields!=null) storage.updateJSON(base+"/"+path,fields); } else { // Create if(fields!=null) path=storage.autocreateJSON(base,fields); } if(relations!=null) setRelations(storage,path,relations); return path; } private JSONObject getPerm(Storage storage, String resourceName, String permlevel) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException, UIException{ JSONObject permitem = new JSONObject(); String actions = ""; ///cspace-services/authorization/permissions?res=acquisition&actGrp=CRUDL String queryString = "CRUDL"; if(permlevel.equals("none")){ queryString = ""; actions = "[]"; return permitem; } if(permlevel.equals("read")){ queryString = "RL"; actions = "[{\"name\":\"READ\"},{\"name\":\"SEARCH\"}]"; } if(permlevel.equals("write")){ queryString = "CRUL"; actions = "[{\"name\":\"CREATE\"},{\"name\":\"READ\"},{\"name\":\"UPDATE\"},{\"name\":\"SEARCH\"}]"; } if(permlevel.equals("delete")){ queryString = "CRUDL"; actions = "[{\"name\":\"CREATE\"},{\"name\":\"READ\"},{\"name\":\"UPDATE\"},{\"name\":\"DELETE\"},{\"name\":\"SEARCH\"}]"; } JSONObject permrestrictions = new JSONObject(); permrestrictions.put("keywords", resourceName); permrestrictions.put("queryTerm", "actGrp"); permrestrictions.put("queryString", queryString); String permbase = spec.getRecordByWebUrl("permission").getID(); JSONObject data = searcher.getJSON(storage,permrestrictions,"items",permbase); String permid = ""; JSONArray items = data.getJSONArray("items"); for(int i=0;i<items.length();i++){ JSONObject item = items.getJSONObject(i); JSONObject permission = new JSONObject(); String resourcename = item.getString("summary"); String actionGroup = item.getString("number"); //need to do a double check as the query is an inexact match if(resourcename.equals(resourceName) && actionGroup.equals(queryString)){ permid = item.getString("csid"); } } if(!permid.equals("")){ //create the permission /** * { "effect": "PERMIT", "resourceName": "testthing2", "action":[{"name":"CREATE"},{"name":"READ"},{"name":"UPDATE"},{"name":"DELETE"},{"name":"SEARCH"}] } */ JSONObject permission_add = new JSONObject(); JSONArray allactions = new JSONArray(actions); permission_add.put("effect", "PERMIT"); permission_add.put("resourceName", resourceName); permission_add.put("actionGroup", queryString); permission_add.put("actions", allactions); permid=storage.autocreateJSON(spec.getRecordByWebUrl("permission").getID(),permission_add); } if(!permid.equals("")){ permitem.put("resourceName", resourceName); permitem.put("permissionId", permid); permitem.put("actionGroup", queryString); } return permitem; } private void assignPermissions(Storage storage, String path, JSONObject data) throws JSONException, ExistException, UnimplementedException, UnderlyingStorageException, UIException{ JSONObject fields=data.optJSONObject("fields"); JSONArray permdata = new JSONArray(); if(fields.has("permissions")){ JSONArray permissions = fields.getJSONArray("permissions"); for(int i=0;i<permissions.length();i++){ JSONObject perm = permissions.getJSONObject(i); JSONObject permitem = getPerm(storage,perm.getString("resourceName"),perm.getString("permission")); if(permitem.has("permissionId")){ permdata.put(permitem); } } } JSONObject roledata = new JSONObject(); roledata.put("roleName", fields.getString("roleName")); String[] ids=path.split("/"); roledata.put("roleId", ids[ids.length - 1]); JSONObject accountrole = new JSONObject(); JSONObject arfields = new JSONObject(); arfields.put("role", roledata); arfields.put("permission", permdata); accountrole.put("fields", arfields); if(fields!=null) path=storage.autocreateJSON(spec.getRecordByWebUrl("permrole").getID(),arfields); } private void store_set(Storage storage,UIRequest request,String path) throws UIException { try { JSONObject data=request.getJSONBody(); if(create) { path=sendJSON(storage,null,data); data.put("csid",path); data.getJSONObject("fields").put("csid",path); } else path=sendJSON(storage,path,data); if(path==null) throw new UIException("Insufficient data for create (no fields?)"); if(this.base.equals("role")){ assignPermissions(storage,path,data); } data=reader.getJSON(storage,path); request.sendJSONResponse(data); request.setOperationPerformed(create?Operation.CREATE:Operation.UPDATE); if(create) request.setSecondaryRedirectPath(new String[]{url_base,path}); } catch (JSONException x) { throw new UIException("Failed to parse json: "+x,x); } catch (ExistException x) { throw new UIException("Existence exception: "+x,x); } catch (UnimplementedException x) { throw new UIException("Unimplemented exception: "+x,x); } catch (UnderlyingStorageException x) { throw new UIException("Problem storing: "+x,x); } } public void run(Object in, String[] tail) throws UIException { Request q=(Request)in; store_set(q.getStorage(),q.getUIRequest(),StringUtils.join(tail,"/")); } public void configure() throws ConfigException {} public void configure(WebUI ui,Spec spec) {} }
CSPACE-2641 fix issue with inexact match against services by doing a double check on the payload returned
cspi-webui/src/main/java/org/collectionspace/chain/csp/webui/record/RecordCreateUpdate.java
CSPACE-2641 fix issue with inexact match against services by doing a double check on the payload returned
<ide><path>spi-webui/src/main/java/org/collectionspace/chain/csp/webui/record/RecordCreateUpdate.java <ide> permid = item.getString("csid"); <ide> } <ide> } <del> if(!permid.equals("")){ <add> if(permid.equals("")){ <ide> <ide> //create the permission <ide> /**